所需jar包:html
bcprov-jdk15on-1.59.jarjava
commons-lang3-3.1.jarweb
import org.bouncycastle.crypto.digests.SM3Digest; import org.bouncycastle.crypto.macs.HMac; import org.bouncycastle.crypto.params.KeyParameter; import org.bouncycastle.jce.provider.BouncyCastleProvider; import org.bouncycastle.pqc.math.linearalgebra.ByteUtils; import java.io.UnsupportedEncodingException; import java.security.Security; import java.util.Arrays;
/** * sm3加密算法工具類 * @explain 加密與加密結果驗證(不可逆算法) * @author Marydon * @creationTime 2018年7月5日上午10:01:24 * @version 1.0 * @since * @email marydon20170307@163.com */ public class Sm3Utils { private static final String ENCODING = "UTF-8"; static { Security.addProvider(new BouncyCastleProvider()); } }
2.SM3加密算法
方式一:不提供密鑰json
/** * sm3算法加密 * @explain * @param paramStr * 待加密字符串 * @return 返回加密後,固定長度=32的16進制字符串 */ public static String encrypt(String paramStr){ // 將返回的hash值轉換成16進制字符串 String resultHexString = ""; try { // 將字符串轉換成byte數組 byte[] srcData = paramStr.getBytes(ENCODING); // 調用hash() byte[] resultHash = hash(srcData); // 將返回的hash值轉換成16進制字符串 resultHexString = ByteUtils.toHexString(resultHash); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } return resultHexString; } /** * 返回長度=32的byte數組 * @explain 生成對應的hash值 * @param srcData * @return */ public static byte[] hash(byte[] srcData) { SM3Digest digest = new SM3Digest(); digest.update(srcData, 0, srcData.length); byte[] hash = new byte[digest.getDigestSize()]; digest.doFinal(hash, 0); return hash; }
方式二:自定義密鑰數組
/** * 經過密鑰進行加密 * @explain 指定密鑰進行加密 * @param key * 密鑰 * @param srcData * 被加密的byte數組 * @return */ public static byte[] hmac(byte[] key, byte[] srcData) { KeyParameter keyParameter = new KeyParameter(key); SM3Digest digest = new SM3Digest(); HMac mac = new HMac(digest); mac.init(keyParameter); mac.update(srcData, 0, srcData.length); byte[] result = new byte[mac.getMacSize()]; mac.doFinal(result, 0); return result; }
/** * 判斷源數據與加密數據是否一致 * @explain 經過驗證原數組和生成的hash數組是否爲同一數組,驗證2者是否爲同一數據 * @param srcStr * 原字符串 * @param sm3HexString * 16進制字符串 * @return 校驗結果 */ public static boolean verify(String srcStr, String sm3HexString) { boolean flag = false; try { byte[] srcData = srcStr.getBytes(ENCODING); byte[] sm3Hash = ByteUtils.fromHexString(sm3HexString); byte[] newHash = hash(srcData); if (Arrays.equals(newHash, sm3Hash)) flag = true; } catch (UnsupportedEncodingException e) { e.printStackTrace(); } return flag; }
public static void main(String[] args) { // 測試二:json String json = "{\"name\":\"Marydon\",\"website\":\"http://www.cnblogs.com/Marydon20170307\"}"; String hex = Sm3Utils.encrypt(json); System.out.println(hex);// 0b0880f6f2ccd817809a432420e42b66d3772dc18d80789049d0f9654efeae5c // 驗證加密後的16進制字符串與加密前的字符串是否相同 boolean flag = Sm3Utils.verify(json, hex); System.out.println(flag);// true }