当前位置:   article > 正文

Java 实现 国密SM4/ECB/PKCS7Padding对称加密解密_java sm4 ecb

java sm4 ecb

Java 实现 国密SM4/ECB/PKCS7Padding对称加密解密,为了演示方便本问使用的是IntelliJ IDEA 2022.1 (Community Edition)来构建代码的

1、pom.xml文件添加需要的jar

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <project xmlns="http://maven.apache.org/POM/4.0.0"
  3. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  4. xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  5. <modelVersion>4.0.0</modelVersion>
  6. <groupId>org.example</groupId>
  7. <artifactId>SM345</artifactId>
  8. <version>1.0-SNAPSHOT</version>
  9. <properties>
  10. <maven.compiler.source>8</maven.compiler.source>
  11. <maven.compiler.target>8</maven.compiler.target>
  12. </properties>
  13. <dependencies>
  14. <!--sm3,sm4加密算法-->
  15. <dependency>
  16. <groupId>org.bouncycastle</groupId>
  17. <artifactId>bcprov-jdk15on</artifactId>
  18. <version>1.66</version>
  19. </dependency>
  20. </dependencies>
  21. </project>

2、java代码

  1. import java.nio.charset.StandardCharsets;
  2. import java.security.Key;
  3. import java.security.NoSuchAlgorithmException;
  4. import java.security.NoSuchProviderException;
  5. import java.security.SecureRandom;
  6. import java.security.Security;
  7. import java.util.Arrays;
  8. import javax.crypto.Cipher;
  9. import javax.crypto.KeyGenerator;
  10. import javax.crypto.spec.SecretKeySpec;
  11. import org.bouncycastle.jce.provider.BouncyCastleProvider;
  12. import org.bouncycastle.pqc.math.linearalgebra.ByteUtils;
  13. import org.apache.commons.codec.binary.Base64;
  14. /**
  15. * sm4加密算法工具类
  16. *
  17. * @author Marydon
  18. * @version 1.0
  19. * @explain sm4加密、解密与加密结果验证
  20. * 可逆算法
  21. * @creationTime 2018年7月6日上午11:46:59
  22. * @email marydon20170307@163.com
  23. * @since
  24. */
  25. public class Sm4Util {
  26. static {
  27. Security.addProvider(new BouncyCastleProvider());
  28. }
  29. private static final String ENCODING = "UTF-8";
  30. public static final String ALGORITHM_NAME = "SM4";
  31. // 加密算法/分组加密模式/分组填充方式
  32. // PKCS5Padding-以8个字节为一组进行分组加密
  33. // 定义分组加密模式使用:PKCS5Padding
  34. public static final String ALGORITHM_NAME_ECB_PADDING7 = "SM4/ECB/PKCS5Padding";
  35. public static final String ALGORITHM_NAME_ECB_PADDING = "SM4/ECB/PKCS7Padding";
  36. // 64-1616进制;128-3216进制;256-6416进制
  37. public static final int DEFAULT_KEY_SIZE = 128;
  38. /**
  39. * 生成ECB暗号
  40. *
  41. * @param algorithmName 算法名称
  42. * @param mode 模式
  43. * @param key
  44. * @return
  45. * @throws Exception
  46. * @explain ECB模式(电子密码本模式:Electronic codebook)
  47. */
  48. private static Cipher generateEcbCipher(String algorithmName, int mode, byte[] key) throws Exception {
  49. Cipher cipher = Cipher.getInstance(algorithmName, BouncyCastleProvider.PROVIDER_NAME);
  50. Key sm4Key = new SecretKeySpec(key, ALGORITHM_NAME);
  51. cipher.init(mode, sm4Key);
  52. return cipher;
  53. }
  54. // 产生密钥
  55. /**
  56. * 自动生成密钥
  57. *
  58. * @return
  59. * @throws NoSuchAlgorithmException
  60. * @throws NoSuchProviderException
  61. * @explain
  62. */
  63. public static byte[] generateKey() throws Exception {
  64. return generateKey(DEFAULT_KEY_SIZE);
  65. }
  66. /**
  67. * @param keySize
  68. * @return
  69. * @throws Exception
  70. * @explain
  71. */
  72. public static byte[] generateKey(int keySize) throws Exception {
  73. KeyGenerator kg = KeyGenerator.getInstance(ALGORITHM_NAME, BouncyCastleProvider.PROVIDER_NAME);
  74. kg.init(keySize, new SecureRandom());
  75. return kg.generateKey().getEncoded();
  76. }
  77. /**
  78. * sm4加密
  79. *
  80. * @param hexKey 16进制密钥(忽略大小写)
  81. * @param paramStr 待加密字符串
  82. * @return 返回16进制的加密字符串
  83. * @throws Exception
  84. * @explain 加密模式:ECB
  85. * 密文长度不固定,会随着被加密字符串长度的变化而变化
  86. */
  87. public static String encryptEcb(String hexKey, String paramStr) throws Exception {
  88. String cipherText = "";
  89. // 16进制字符串-->byte[]
  90. //byte[] keyData = ByteUtils.fromHexString(hexKey);
  91. byte[] keyData = hexKey.getBytes(ENCODING);
  92. // String-->byte[]
  93. byte[] srcData = paramStr.getBytes(ENCODING);
  94. // 加密后的数组
  95. byte[] cipherArray = encrypt_Ecb_Padding(keyData, srcData);
  96. // byte[]-->hexString
  97. //cipherText = ByteUtils.toHexString(cipherArray);
  98. cipherText = Base64.encodeBase64String(cipherArray);
  99. return cipherText;
  100. }
  101. /**
  102. * 加密模式之Ecb
  103. *
  104. * @param key
  105. * @param data
  106. * @return
  107. * @throws Exception
  108. * @explain
  109. */
  110. public static byte[] encrypt_Ecb_Padding(byte[] key, byte[] data) throws Exception {
  111. Cipher cipher = generateEcbCipher(ALGORITHM_NAME_ECB_PADDING, Cipher.ENCRYPT_MODE, key);
  112. return cipher.doFinal(data);
  113. }
  114. /**
  115. * sm4解密
  116. *
  117. * @param hexKey 16进制密钥
  118. * @param cipherText 16进制的加密字符串(忽略大小写)
  119. * @return 解密后的字符串
  120. * @throws Exception
  121. * @explain 解密模式:采用ECB
  122. */
  123. public static String decryptEcb(String hexKey, String cipherText) throws Exception {
  124. // 用于接收解密后的字符串
  125. String decryptStr = "";
  126. // hexString-->byte[]
  127. //byte[] keyData = ByteUtils.fromHexString(hexKey);
  128. byte[] keyData = hexKey.getBytes(ENCODING);
  129. // hexString-->byte[]
  130. //byte[] cipherData = ByteUtils.fromHexString(cipherText);
  131. byte[] cipherData =Base64.decodeBase64(cipherText);
  132. // 解密
  133. byte[] srcData = decrypt_Ecb_Padding(keyData, cipherData);
  134. // byte[]-->String
  135. decryptStr = new String(srcData, ENCODING);
  136. return decryptStr;
  137. }
  138. /**
  139. * 解密
  140. *
  141. * @param key
  142. * @param cipherText
  143. * @return
  144. * @throws Exception
  145. * @explain
  146. */
  147. public static byte[] decrypt_Ecb_Padding(byte[] key, byte[] cipherText) throws Exception {
  148. Cipher cipher = generateEcbCipher(ALGORITHM_NAME_ECB_PADDING, Cipher.DECRYPT_MODE, key);
  149. return cipher.doFinal(cipherText);
  150. }
  151. /**
  152. * 校验加密前后的字符串是否为同一数据
  153. *
  154. * @param hexKey 16进制密钥(忽略大小写)
  155. * @param cipherText 16进制加密后的字符串
  156. * @param paramStr 加密前的字符串
  157. * @return 是否为同一数据
  158. * @throws Exception
  159. * @explain
  160. */
  161. public static boolean verifyEcb(String hexKey, String cipherText, String paramStr) throws Exception {
  162. // 用于接收校验结果
  163. boolean flag = false;
  164. // hexString-->byte[]
  165. //byte[] keyData = ByteUtils.fromHexString(hexKey);
  166. byte[] keyData = hexKey.getBytes(ENCODING);
  167. //16进制字符串转换成数组
  168. //byte[] cipherData = ByteUtils.fromHexString(cipherText);
  169. byte[] cipherData = Base64.decodeBase64(cipherText);
  170. // 解密
  171. byte[] decryptData = decrypt_Ecb_Padding(keyData, cipherData);
  172. // 将原字符串转换成byte[]
  173. byte[] srcData = paramStr.getBytes(ENCODING);
  174. // 判断2个数组是否一致
  175. flag = Arrays.equals(decryptData, srcData);
  176. return flag;
  177. }
  178. }

3、本文用到了一个Base64的jar加包commons-codec-1.16.0.jar,import org.apache.commons.codec.binary.Base64;需要下载添加引用即可

选择 文件  项目结构 项目设置  库  点击最右边的+ 选择 下载的commons-codec-1.16.0.jar加包即可。

4、使用代码

  1. import java.security.Key;
  2. import java.security.NoSuchAlgorithmException;
  3. import java.security.NoSuchProviderException;
  4. import java.security.SecureRandom;
  5. import java.security.Security;
  6. import java.util.Arrays;
  7. import javax.crypto.Cipher;
  8. import javax.crypto.KeyGenerator;
  9. import javax.crypto.spec.SecretKeySpec;
  10. import org.bouncycastle.jce.provider.BouncyCastleProvider;
  11. import org.bouncycastle.pqc.math.linearalgebra.ByteUtils;
  12. //import org.apache.commons.codec.binary.Hex;
  13. //import org.apache.commons.codec.binary.Base64;
  14. public class Longteng {
  15. public static void main(String[] args) {
  16. try {
  17. String json = "{\"name\":\"Marydon\",\"website\":\"http://www.cnblogs.com/Marydon20170307\"}";
  18. json = "1234567890abcdefghijklmnopqrstuvwxyz";
  19. System.out.println("国密SM4加密解密:");
  20. // 自定义的3216进制密钥
  21. // String key = "86C63180C2806ED1F47B859DE501215B";
  22. String key = "1234567890123456";
  23. String cipher = Sm4Util.encryptEcb(key, json);
  24. System.out.println("国密SM4加密解密:\r\n密钥:" + key + " \n加密内容:" + json + " \n加密后v" + cipher);
  25. //System.out.println(cipher);
  26. //比对加密解密信息
  27. System.out.println(Sm4Util.verifyEcb(key, cipher, json));// true
  28. json = Sm4Util.decryptEcb(key, cipher);
  29. System.out.println("国密SM4加密解密:\n密钥:" + key + " \n加密内容:" + cipher + " \n解密后:" + json);
  30. //System.out.println(json);
  31. } catch (Exception e) {
  32. e.printStackTrace();
  33. }
  34. }
  35. }

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/笔触狂放9/article/detail/809959
推荐阅读
相关标签
  

闽ICP备14008679号