SM4对应的常用的加密算法是DES对称加密算法,公私钥是同一个,秘钥长度128位,这里介绍通过KeyGenerator来实现,使用BouncyCastleProvider
//加密
public byte[] encode(byte[] message,String mode,String padding,String passwordType , byte[]password,byte[]iv) throws Exception {
Security.addProvider(new BouncyCastleProvider());
Key key = SecretUtil.getKey("SM4", 128, passwordType, password);
Cipher cipher = SecretUtil.getCipher(key, "SM4", mode, padding, Cipher.ENCRYPT_MODE, iv, new BouncyCastleProvider());
return cipher.doFinal(message);
}
//解密
public byte[] decode(byte[] encode,String mode,String padding,String passwordType , byte[]password,byte[]iv) throws Exception {
Security.addProvider(new BouncyCastleProvider());
Key key = SecretUtil.getKey("SM4", 128, passwordType, password);
Cipher cipher = SecretUtil.getCipher(key, "SM4", mode, padding, Cipher.DECRYPT_MODE, iv, new BouncyCastleProvider());
return cipher.doFinal(encode);
}
public static Key getKey(String algorithm, int length, String passwordType, byte[] password)
throws NoSuchAlgorithmException {
Key key;
if (passwordType == null || passwordType.equals("fix")) {
key = new SecretKeySpec(password, algorithm);
} else {
KeyGenerator keyGenerator = KeyGenerator.getInstance(algorithm);
SecureRandom secureRandom = SecureRandom.getInstance("SHA1PRNG");
secureRandom.setSeed(password);
keyGenerator.init(length, secureRandom);
SecretKey secretKey = keyGenerator.generateKey();
key = new SecretKeySpec(secretKey.getEncoded(), algorithm);
}
return key;
}