当前位置:   article > 正文

RSA非对称加密-前端加密,java 后端解密_前端用非对称加密的公钥解密

前端用非对称加密的公钥解密

思路:

  1. 后端生成私钥、公钥。
  2. 前端用公钥对信息加密,后端用私钥解密。

后端代码:

  1. package com.example.demo.utils;
  2. import com.sun.org.apache.xml.internal.security.exceptions.Base64DecodingException;
  3. import com.sun.org.apache.xml.internal.security.utils.Base64;
  4. import lombok.AllArgsConstructor;
  5. import lombok.Data;
  6. import javax.crypto.BadPaddingException;
  7. import javax.crypto.Cipher;
  8. import javax.crypto.IllegalBlockSizeException;
  9. import javax.crypto.NoSuchPaddingException;
  10. import java.security.*;
  11. import java.security.interfaces.RSAPrivateKey;
  12. import java.security.interfaces.RSAPublicKey;
  13. import java.security.spec.InvalidKeySpecException;
  14. import java.security.spec.PKCS8EncodedKeySpec;
  15. import java.security.spec.X509EncodedKeySpec;
  16. public class RSAUtil {
  17. public static String RSA_ALGORITHM = "RSA";
  18. public static String UTF8 = "UTF-8";
  19. /**
  20. * 密钥长度,DSA算法的默认密钥长度是1024
  21. * 密钥长度必须是64的倍数,在512到65536位之间
  22. * */
  23. private static final int KEY_SIZE=1024;
  24. public static void test() throws Exception {
  25. String password = "jiang=xxu&xxuxu-aa=xxxx@cummins.com%";
  26. RSAKey key = createKey();
  27. byte[] encryptByPublicKey = encryptByPublicKey(password.getBytes(), Base64.decode(key.getPublicKey()));
  28. System.out.println("使用公钥加密后的数据:"+Base64.encode(encryptByPublicKey));
  29. byte[] decryptByPrivateKey = decryptByPrivateKey(encryptByPublicKey, Base64.decode(key.getPrivateKey()));
  30. System.out.println("使用私钥解密后的数据:"+new String(decryptByPrivateKey));
  31. }
  32. public static void main(String[] args) throws Exception {
  33. String pwd_encode =
  34. "TI6CDLwMb3Wbmgt4MPiGGTIqIBeFoyp8SF6lbsoCI8j5ee9qFB7q0OLpgQGwYD1DddU1+mLmnq62cp4dfm42EpSDU8+P3prxiKJeuwAKcOnIq2Uf1MpCF+eEyzLYxiAHjTDcW7o0070bASxz92O0uL0D87wKAx5sO4ch2Rr1kcI=" ;
  35. /**
  36. * 放在前端加密
  37. */
  38. String publicKey = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCeFyVkUDrMAbn0WhDzI1IA+/z0m1k286A3AgzckLT0JKRFXvykkfQEYcymS4ncuCq/Im+CHVCs5L1ZU/hPoXvNhfwMEiXWx4PG1JUOrufl5cueizrsxIMJvQQki058wDyxEm0p6d8v9lFw5IAlTA5pQS6mZEhdPPdxVGABS1e0JQIDAQAB";
  39. /**
  40. * 放在后端解密
  41. */
  42. String privateKey = "MIICdwIBADANBgkqhkiG9w0BAQEFAASCAmEwggJdAgEAAoGBAJ4XJWRQOswBufRaEPMjUgD7/PSbWTbzoDcCDNyQtPQkpEVe/KSR9ARhzKZLidy4Kr8ib4IdUKzkvVlT+E+he82F/AwSJdbHg8bUlQ6u" +
  43. "5+Xly56LOuzEgwm9BCSLTnzAPLESbSnp3y/2UXDkgCVMDmlBLqZkSF0893FUYAFLV7QlAgMBAAEC" +
  44. "gYBLxAoOnojfVwB5BGVVMZtOj3Y3APDr7izd0CS73Lpsu9bizFhGwxBwvTJojJFg7/7EpctNT6Fn" +
  45. "iyTYV+8Msvby0sDmm40CJOQJazMyqUjAWnzsVsdBKRjZlAmc37T38U0Rmq1dARmhKAPQAvp8PEhh" +
  46. "gx4xh/DrSYuUmwZk/4hYAQJBANbh0PkcGzjKgkSPBsAdimq/C386ILakixbf/zyX4WqokEcTYpbd" +
  47. "IaTWYZ9PMoJ2gN0Ad0YXkfZTItrtlCGQBgECQQC8V1cwYl9FFyB2Q0qf6AD3khbzCH/1PPZGdeeI" +
  48. "MS954575ij6HtlwgSuGzzl/HO5zjjy2gEuNMx75qwGcAgtYlAkEAtS0WvkMFbL/KUDXrsiX2JATK" +
  49. "k84V8QkRQQtCL/u7EuvnIhZlJOBz0oDzNJhY9Qkno68V4eJTrkXweHiiUh4WAQJAfEfuIuFnGIJQ" +
  50. "S3nQDoDb0oI2Xp0nQr69jHVVGUvLllUbnHMbHBa76BtBoJL4JNIzjv32D4EnOI0+G9dmoLG1eQJB" +
  51. "AMcM+8LIuJjp8WzHZ7OqaWlmHaEBwax+luvYPSd4ozBUyQlEmipQHdCBxXU+kBtQaDDaGKYxOGW5" +
  52. "Y0nK8/bT+jg=";
  53. byte[] old = decryptByPrivateKey(Base64.decode(pwd_encode),Base64.decode(privateKey));
  54. System.out.println(new String(old));
  55. }
  56. public static RSAKey createKey() throws NoSuchAlgorithmException {
  57. KeyStore keys = createKeyStore();
  58. byte[] publicKey = getPublicKey(keys);
  59. byte[] privateKey = getPrivateKey(keys);
  60. String encode_publicKey = Base64.encode(publicKey);
  61. System.out.println("公钥:"+encode_publicKey );
  62. System.out.println();
  63. String endcode_privateKey = Base64.encode(privateKey);
  64. System.out.println("私钥:"+ endcode_privateKey);
  65. return new RSAKey(endcode_privateKey,encode_publicKey);
  66. }
  67. @Data
  68. public static class RSAKey{
  69. private String privateKey;
  70. private String publicKey;
  71. public RSAKey(String privateKey, String publicKey) {
  72. this.privateKey = privateKey;
  73. this.publicKey = publicKey;
  74. }
  75. }
  76. /**
  77. * 生成密钥对
  78. * @return 密钥对对象
  79. * @throws NoSuchAlgorithmException
  80. */
  81. private static KeyStore createKeyStore() throws NoSuchAlgorithmException {
  82. //KeyPairGenerator用于生成公钥和私钥对。密钥对生成器是使用 getInstance 工厂方法
  83. KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance(RSA_ALGORITHM);
  84. keyPairGenerator.initialize(KEY_SIZE);
  85. KeyPair keyPair = keyPairGenerator.generateKeyPair();
  86. RSAPrivateKey privateKey = (RSAPrivateKey)keyPair.getPrivate();
  87. RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();
  88. KeyStore keyStore = new KeyStore( publicKey, privateKey);
  89. return keyStore;
  90. }
  91. /**
  92. * 获取私钥
  93. * @param keyStore
  94. * @return
  95. */
  96. private static byte[] getPrivateKey(KeyStore keyStore){
  97. return ((RSAPrivateKey)keyStore.privateKey).getEncoded();
  98. }
  99. /**
  100. * 获取公钥
  101. * @param keyStore
  102. * @return
  103. */
  104. private static byte[] getPublicKey(KeyStore keyStore){
  105. return ((RSAPublicKey)keyStore.publicKey).getEncoded();
  106. }
  107. /**
  108. * 私钥加密
  109. * @param data 待加密数据
  110. * @param key 密钥
  111. * @return byte[] 加密数据
  112. * */
  113. public static byte[] encryptByPrivateKey(byte[] data,byte[] key) throws Exception{
  114. //取得私钥
  115. PKCS8EncodedKeySpec pkcs8KeySpec=new PKCS8EncodedKeySpec(key);
  116. KeyFactory keyFactory= KeyFactory.getInstance(RSA_ALGORITHM);
  117. //生成私钥
  118. PrivateKey privateKey=keyFactory.generatePrivate(pkcs8KeySpec);
  119. //数据加密
  120. Cipher cipher=Cipher.getInstance(keyFactory.getAlgorithm());
  121. cipher.init(Cipher.ENCRYPT_MODE, privateKey);
  122. return cipher.doFinal(data);
  123. }
  124. /**
  125. * 公钥加密
  126. * @param data
  127. * @param key
  128. * @return
  129. * @throws NoSuchAlgorithmException
  130. * @throws InvalidKeySpecException
  131. * @throws NoSuchPaddingException
  132. * @throws BadPaddingException
  133. * @throws IllegalBlockSizeException
  134. * @throws InvalidKeyException
  135. */
  136. private static byte[] encryptByPublicKey(byte[] data, byte[] key) throws NoSuchAlgorithmException,
  137. InvalidKeySpecException, NoSuchPaddingException, BadPaddingException, IllegalBlockSizeException, InvalidKeyException {
  138. //实例化密钥工厂
  139. KeyFactory keyFactory = KeyFactory.getInstance(RSA_ALGORITHM);
  140. //初始化公钥,根据给定的编码密钥创建一个新的 X509EncodedKeySpec。
  141. X509EncodedKeySpec x509EncodedKeySpec = new X509EncodedKeySpec(key);
  142. PublicKey publicKey = keyFactory.generatePublic(x509EncodedKeySpec);
  143. //数据加密
  144. Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
  145. cipher.init(Cipher.ENCRYPT_MODE,publicKey);
  146. return cipher.doFinal(data);
  147. }
  148. /**
  149. * 私钥解密
  150. * @param data 待解密数据
  151. * @param key 密钥
  152. * @return byte[] 解密数据
  153. * */
  154. public static byte[] decryptByPrivateKey(byte[] data,byte[] key) throws Exception{
  155. //取得私钥
  156. PKCS8EncodedKeySpec pkcs8KeySpec=new PKCS8EncodedKeySpec(key);
  157. KeyFactory keyFactory=KeyFactory.getInstance(RSA_ALGORITHM);
  158. //生成私钥
  159. PrivateKey privateKey=keyFactory.generatePrivate(pkcs8KeySpec);
  160. //数据解密
  161. Cipher cipher=Cipher.getInstance(keyFactory.getAlgorithm());
  162. cipher.init(Cipher.DECRYPT_MODE, privateKey);
  163. return cipher.doFinal(data);
  164. }
  165. /**
  166. * 公钥解密
  167. * @param data 待解密数据
  168. * @param key 密钥
  169. * @return byte[] 解密数据
  170. * */
  171. public static byte[] decryptByPublicKey(byte[] data,byte[] key) throws Exception{
  172. //实例化密钥工厂
  173. KeyFactory keyFactory=KeyFactory.getInstance(RSA_ALGORITHM);
  174. //初始化公钥
  175. //密钥材料转换
  176. X509EncodedKeySpec x509KeySpec=new X509EncodedKeySpec(key);
  177. //产生公钥
  178. PublicKey pubKey=keyFactory.generatePublic(x509KeySpec);
  179. //数据解密
  180. Cipher cipher=Cipher.getInstance(keyFactory.getAlgorithm());
  181. cipher.init(Cipher.DECRYPT_MODE, pubKey);
  182. return cipher.doFinal(data);
  183. }
  184. //定义密钥类
  185. @Data
  186. @AllArgsConstructor
  187. public static class KeyStore{
  188. private Object publicKey;
  189. private Object privateKey;
  190. }
  191. }

注意事项:后端生成 私钥(base64加密的私钥)和公钥(base64加密的公钥),记得保存。

然后将上面公钥复制到前端,前端对信息加密即可。

  1. <!DOCTYPE html>
  2. <html>
  3. <head>
  4. <!-- <script src="./encode/base64.js"></script> -->
  5. <script src="./encode/jsencrypt.js"></script>
  6. </head>
  7. <body>
  8. hello ,world!
  9. <div id="pwd_encode"></div>
  10. </body>
  11. <script>
  12. // 非对称加密(RSA)
  13. // 密钥对生成 http://web.chacuo.net/netrsakeypair
  14. /**
  15. * 前端加密时需要公钥
  16. */
  17. const publicKey = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCeFyVkUDrMAbn0WhDzI1IA+/z0m1k286A3AgzckLT0JKRFXvykkfQEYcymS4ncuCq/Im+CHVCs5L1ZU/hPoXvNhfwMEiXWx4PG1JUOrufl5cueizrsxIMJvQQki058wDyxEm0p6d8v9lFw5IAlTA5pQS6mZEhdPPdxVGABS1e0JQIDAQAB";
  18. /**
  19. * 没啥用
  20. */
  21. const privateKey = ''
  22. // 加密
  23. function encrypt(txt) {
  24. const encryptor = new JSEncrypt()
  25. encryptor.setPublicKey(publicKey) // 设置公钥
  26. return encryptor.encrypt(txt) // 对数据进行加密
  27. }
  28. // 解密
  29. function decrypt(txt) {
  30. const encryptor = new JSEncrypt()
  31. encryptor.setPrivateKey(privateKey) // 设置私钥
  32. return encryptor.decrypt(txt) // 对数据进行解密
  33. }
  34. //4.将需要的数据进行加密即可
  35. let pwd = "jiang=xxu&xxuxu-aa=xxxx@cummins.com%";
  36. let pwd_encode = encrypt(pwd)
  37. document.getElementById("pwd_encode").innerHTML=pwd_encode;
  38. </script>
  39. </html>

jsencrypt 库 可以去官网下载:下载

或者直接下载:https://download.csdn.net/download/rainyspring4540/89100890

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

闽ICP备14008679号