登录
原创

java SM4加解密实现

发布于 2020-10-26 阅读 84
  • 后端
  • 算法
  • Java
原创

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;
   }

评论区

梦飞
0粉丝

励志做一条安静的咸鱼,从此走上人生巅峰。

0

0

0