最近的项目需要用到SM4算法来进行加密和解密,所以研究了一下记录在下:

一.SM4简介:

SM4是一种我国采用的一种分组密码标准,由国家密码局由2012年发布。

分组加密(英语:Block cipher),又称分块加密块密码,是一种对称密钥算法。它将明文分成多个等长的模块(block),使用确定的算法和对称密钥对每组分别加密解密。分组加密是极其重要的加密协议组成,其中典型的如DES和AES作为美国政府核定的标准加密算法,应用领域从电子邮件加密到银行交易转帐,非常广泛。

国密即国家密码局认定的国产密码算法。主要有SM1,SM2,SM3,SM4。密钥长度和分组长度均为128位。

SM1为对称加密。其加密强度与AES相当。该算法不公开,调用该算法时,需要通过加密芯片的接口进行调用。

SM2为非对称加密,基于ECC。该算法已公开。由于该算法基于ECC,故其签名速度与秘钥生成速度都快于RSA。ECC 256位(SM2采用的就是ECC 256位的一种)安全强度比RSA 2048位高,但运算速度快于RSA。

SM3消息摘要。可以用MD5作为对比理解。该算法已公开。校验结果为256位。

SM4无线局域网标准的分组数据算法。对称加密,密钥长度和分组长度均为128位。

上述可以总结为:SM4是一种过长加密算法。采用分组加密,对称加密。密钥长度和分组长度均为128位。

二.SM4的原理

参考https://blog.csdn/weixin_37569048/article/details/94983841

三.Java实现SM4加密解密

代码演示如下,可以直接使用

 public String encrypt(String plainText, String secretKey) {
    try {
      SM4_Context ctx = new SM4_Context();
      ctx.isPadding = true;
      ctx.mode = SM4.SM4_ENCRYPT;

      byte[] keyBytes;
      keyBytes = secretKey.getBytes();
      SM4 sm4 = new SM4();
      sm4.sm4_setkey_enc(ctx, keyBytes);
      byte[] encrypted = sm4.sm4_crypt_ecb(ctx, plainText.getBytes(CHARSET));
      String cipherText = Base64.encodeBase64String(encrypted);
      if (cipherText != null && cipherText.trim().length() > 0) {
        Pattern p = Patternpile("\\s*|\t|\r|\n");
        Matcher m = p.matcher(cipherText);
        cipherText = m.replaceAll("");
      }
      return cipherText;
    } catch (Exception e) {
      e.printStackTrace();
      return null;
    }
  }

  public String decrypt(String cipherText, String secretKey) {
    try {
      SM4_Context ctx = new SM4_Context();
      ctx.isPadding = true;
      ctx.mode = SM4.SM4_DECRYPT;

      byte[] keyBytes;
      keyBytes = secretKey.getBytes();
      SM4 sm4 = new SM4();
      sm4.sm4_setkey_dec(ctx, keyBytes);
      byte[] decrypted = sm4.sm4_crypt_ecb(ctx, Base64.decodeBase64(cipherText.getBytes(CHARSET)));
      return new String(decrypted, CHARSET);
    } catch (Exception e) {
      e.printStackTrace();
      return null;
    }
  }

 

 

 

 

更多推荐

国产加密算法SM4实现(Java)