当前位置:   article > 正文

前后端加密传输,采用RSA算法_rsa 实现前后端加解密

rsa 实现前后端加解密

后端代码 

  1. package org.jeecg.modules.system.util;
  2. import java.io.ByteArrayOutputStream;
  3. import java.security.Key;
  4. import java.security.KeyFactory;
  5. import java.security.KeyPair;
  6. import java.security.KeyPairGenerator;
  7. import java.security.NoSuchAlgorithmException;
  8. import java.security.SecureRandom;
  9. import java.security.interfaces.RSAPrivateKey;
  10. import java.security.interfaces.RSAPublicKey;
  11. import java.security.spec.InvalidKeySpecException;
  12. import java.security.spec.PKCS8EncodedKeySpec;
  13. import java.security.spec.X509EncodedKeySpec;
  14. import java.util.HashMap;
  15. import java.util.Map;
  16. import javax.crypto.Cipher;
  17. import org.apache.commons.codec.binary.Base64;
  18. import org.apache.commons.io.IOUtils;
  19. public class RSAUtils {
  20. public static final String CHARSET = "UTF-8";
  21. public static final String RSA_ALGORITHM = "RSA";
  22. public static final KeyPair keyPair = initKeys();
  23. private static KeyPair initKeys() {
  24. KeyPairGenerator kpg;
  25. try{
  26. kpg = KeyPairGenerator.getInstance(RSA_ALGORITHM);
  27. }catch(NoSuchAlgorithmException e){
  28. throw new IllegalArgumentException("No such algorithm-->[" + RSA_ALGORITHM + "]");
  29. }
  30. int keySize = 1024;
  31. SecureRandom random = new SecureRandom();
  32. //初始化KeyPairGenerator对象,密钥长度
  33. kpg.initialize(keySize, random);
  34. //生成密匙对
  35. KeyPair keyPair = kpg.generateKeyPair();
  36. return keyPair;
  37. }
  38. public static Map<String, String> createKeys(){
  39. //为RSA算法创建一个KeyPairGenerator对象
  40. KeyPairGenerator kpg;
  41. try{
  42. kpg = KeyPairGenerator.getInstance(RSA_ALGORITHM);
  43. }catch(NoSuchAlgorithmException e){
  44. throw new IllegalArgumentException("No such algorithm-->[" + RSA_ALGORITHM + "]");
  45. }
  46. int keySize = 1024;
  47. //初始化KeyPairGenerator对象,密钥长度
  48. kpg.initialize(keySize);
  49. //生成密匙对
  50. //KeyPair keyPair = kpg.generateKeyPair();
  51. //得到公钥
  52. Key publicKey = keyPair.getPublic();
  53. String publicKeyStr = Base64.encodeBase64URLSafeString(publicKey.getEncoded());
  54. //得到私钥
  55. Key privateKey = keyPair.getPrivate();
  56. String privateKeyStr = Base64.encodeBase64URLSafeString(privateKey.getEncoded());
  57. Map<String, String> keyPairMap = new HashMap<String, String>();
  58. keyPairMap.put("publicKey", publicKeyStr);
  59. keyPairMap.put("privateKey", privateKeyStr);
  60. return keyPairMap;
  61. }
  62. public static String getPublicKey() {
  63. Key publicKey = keyPair.getPublic();
  64. String publicKeyStr = Base64.encodeBase64URLSafeString(publicKey.getEncoded());
  65. return publicKeyStr;
  66. }
  67. public static String getPrivateKey() {
  68. Key privateKey = keyPair.getPrivate();
  69. String privateKeyStr = Base64.encodeBase64URLSafeString(privateKey.getEncoded());
  70. return privateKeyStr;
  71. }
  72. /**
  73. * 得到公钥
  74. * @param publicKey 密钥字符串(经过base64编码)
  75. * @throws Exception
  76. */
  77. public static RSAPublicKey getPublicKey(String publicKey) throws NoSuchAlgorithmException, InvalidKeySpecException {
  78. //通过X509编码的Key指令获得公钥对象
  79. KeyFactory keyFactory = KeyFactory.getInstance(RSA_ALGORITHM);
  80. X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(Base64.decodeBase64(publicKey));
  81. RSAPublicKey key = (RSAPublicKey) keyFactory.generatePublic(x509KeySpec);
  82. return key;
  83. }
  84. /**
  85. * 得到私钥
  86. * @param privateKey 密钥字符串(经过base64编码)
  87. * @throws Exception
  88. */
  89. public static RSAPrivateKey getPrivateKey(String privateKey) throws NoSuchAlgorithmException, InvalidKeySpecException {
  90. //通过PKCS#8编码的Key指令获得私钥对象
  91. KeyFactory keyFactory = KeyFactory.getInstance(RSA_ALGORITHM);
  92. PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(Base64.decodeBase64(privateKey));
  93. RSAPrivateKey key = (RSAPrivateKey) keyFactory.generatePrivate(pkcs8KeySpec);
  94. return key;
  95. }
  96. /**
  97. * 公钥加密
  98. * @param data
  99. * @param publicKey
  100. * @return
  101. */
  102. public static String publicEncrypt(String data, RSAPublicKey publicKey){
  103. try{
  104. Cipher cipher = Cipher.getInstance(RSA_ALGORITHM);
  105. cipher.init(Cipher.ENCRYPT_MODE, publicKey);
  106. return Base64.encodeBase64URLSafeString(rsaSplitCodec(cipher, Cipher.ENCRYPT_MODE, data.getBytes(CHARSET), publicKey.getModulus().bitLength()));
  107. }catch(Exception e){
  108. throw new RuntimeException("加密字符串[" + data + "]时遇到异常", e);
  109. }
  110. }
  111. /**
  112. * 私钥解密
  113. * @param data
  114. * @param privateKey
  115. * @return
  116. */
  117. public static String privateDecrypt(String data, RSAPrivateKey privateKey){
  118. try{
  119. Cipher cipher = Cipher.getInstance(RSA_ALGORITHM);
  120. cipher.init(Cipher.DECRYPT_MODE, privateKey);
  121. return new String(rsaSplitCodec(cipher, Cipher.DECRYPT_MODE, Base64.decodeBase64(data), privateKey.getModulus().bitLength()), CHARSET);
  122. }catch(Exception e){
  123. throw new RuntimeException("解密字符串[" + data + "]时遇到异常", e);
  124. }
  125. }
  126. /**
  127. * 私钥加密
  128. * @param data
  129. * @param privateKey
  130. * @return
  131. */
  132. public static String privateEncrypt(String data, RSAPrivateKey privateKey){
  133. try{
  134. Cipher cipher = Cipher.getInstance(RSA_ALGORITHM);
  135. cipher.init(Cipher.ENCRYPT_MODE, privateKey);
  136. return Base64.encodeBase64URLSafeString(rsaSplitCodec(cipher, Cipher.ENCRYPT_MODE, data.getBytes(CHARSET), privateKey.getModulus().bitLength()));
  137. }catch(Exception e){
  138. throw new RuntimeException("加密字符串[" + data + "]时遇到异常", e);
  139. }
  140. }
  141. /**
  142. * 公钥解密
  143. * @param data
  144. * @param publicKey
  145. * @return
  146. */
  147. public static String publicDecrypt(String data, RSAPublicKey publicKey){
  148. try{
  149. Cipher cipher = Cipher.getInstance(RSA_ALGORITHM);
  150. cipher.init(Cipher.DECRYPT_MODE, publicKey);
  151. return new String(rsaSplitCodec(cipher, Cipher.DECRYPT_MODE, Base64.decodeBase64(data), publicKey.getModulus().bitLength()), CHARSET);
  152. }catch(Exception e){
  153. throw new RuntimeException("解密字符串[" + data + "]时遇到异常", e);
  154. }
  155. }
  156. private static byte[] rsaSplitCodec(Cipher cipher, int opmode, byte[] datas, int keySize){
  157. int maxBlock = 0;
  158. if(opmode == Cipher.DECRYPT_MODE){
  159. maxBlock = keySize / 8;
  160. }else{
  161. maxBlock = keySize / 8 - 11;
  162. }
  163. ByteArrayOutputStream
  164. out = new ByteArrayOutputStream();
  165. int offSet = 0;
  166. byte[] buff;
  167. int i = 0;
  168. try{
  169. while(datas.length > offSet){
  170. if(datas.length-offSet > maxBlock){
  171. buff = cipher.doFinal(datas, offSet, maxBlock);
  172. }else{
  173. buff = cipher.doFinal(datas, offSet, datas.length-offSet);
  174. }
  175. out.write(buff, 0, buff.length);
  176. i++;
  177. offSet = i * maxBlock;
  178. }
  179. }catch(Exception e){
  180. throw new RuntimeException("加解密阀值为["+maxBlock+"]的数据时发生异常", e);
  181. }
  182. byte[] resultDatas = out.toByteArray();
  183. IOUtils.closeQuietly(out);
  184. return resultDatas;
  185. }
  186. public static void main (String[] args) throws Exception {
  187. for (int i = 0; i <= 1; i++) {
  188. Map<String, String> keyMap = RSAUtils.createKeys();
  189. String publicKey = keyMap.get("publicKey");
  190. String privateKey = keyMap.get("privateKey");
  191. System.out.println("公钥: \n\r" + publicKey);
  192. System.out.println("私钥: \n\r" + privateKey);
  193. System.out.println("公钥加密——私钥解密");
  194. String str = "code_cayden";
  195. System.out.println("\r明文:\r\n" + str);
  196. System.out.println("\r明文大小:\r\n" + str.getBytes().length);
  197. System.out.println("加密用的公钥:\r\n"+ RSAUtils.getPublicKey(publicKey));
  198. System.out.println("解密用的私钥:\r\n"+ RSAUtils.getPrivateKey(privateKey));
  199. String encodedData = RSAUtils.publicEncrypt(str, RSAUtils.getPublicKey(publicKey));
  200. System.out.println("密文:\r\n" + encodedData);
  201. String decodedData = RSAUtils.privateDecrypt(encodedData, RSAUtils.getPrivateKey(privateKey));
  202. System.out.println("解密后文字: \r\n" + decodedData);
  203. }
  204. }
  205. }
  1. @ApiOperation("获取登录公钥")
  2. @RequestMapping(value = "/getPublicKey", method = RequestMethod.POST)
  3. public Result<String> getPublicKey(){
  4. Result<String> result = new Result<String>();
  5. String publicKey = RSAUtils.getPublicKey();
  6. result.setResult(publicKey);
  7. result.setSuccess(true);
  8. result.setCode(CommonConstant.SC_OK_200);
  9. return result;
  10. }
  11. @ApiOperation("登录接口")
  12. @RequestMapping(value = "/login", method = RequestMethod.POST)
  13. public Result<JSONObject> login(@RequestBody SysLoginModel sysLoginModel){
  14. Result<JSONObject> result = new Result<JSONObject>();
  15. String username = sysLoginModel.getUsername();
  16. String password = sysLoginModel.getPassword();
  17. String privateKey = RSAUtils.getPrivateKey();
  18. try {
  19. RSAPrivateKey rsaPrivateKey = RSAUtils.getPrivateKey(privateKey);
  20. username = RSAUtils.privateDecrypt(username, rsaPrivateKey);
  21. password = RSAUtils.privateDecrypt(password, rsaPrivateKey);
  22. } catch (NoSuchAlgorithmException e) {
  23. // TODO Auto-generated catch block
  24. e.printStackTrace();
  25. } catch (InvalidKeySpecException e) {
  26. // TODO Auto-generated catch block
  27. e.printStackTrace();
  28. }
  29. 。。。。。。。。

前端代码

  1. cnpm install jsencrypt --save
  2. ---------
  3. import JsEncrypt from 'jsencrypt'
  4. getPublicKey () {
  5. postAction('/sys/getPublicKey')
  6. .then(res => {
  7. if (res.success === true) {
  8. this.publicKey = res.result
  9. } else {
  10. this.$notification[ 'error' ]({
  11. message: '获取公钥失败',
  12. description: '获取公钥失败',
  13. duration: 4
  14. })
  15. }
  16. })
  17. .catch(err => {
  18. this.$notification[ 'error' ]({
  19. message: '获取公钥失败',
  20. description: '获取公钥失败',
  21. duration: 4
  22. })
  23. })
  24. },
  25. ---
  26. let encrypt = new JsEncrypt()
  27. encrypt.setPublicKey(this.publicKey)
  28. loginParams.username = encrypt.encrypt(values.username)
  29. loginParams.password = encrypt.encrypt(values.password)

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

闽ICP备14008679号