首页 > 代码库 > rsa加密算法,前后端实现。

rsa加密算法,前后端实现。

前端js:

  下载地址:http://travistidwell.com/jsencrypt/

js第一版本:

 1 // 对数据加密 2     function encrypt(enStr){ 3         //没有加载jsencrypt.js 4         if(typeof(JSEncrypt) != "function"){ 5             return enStr; 6         }  7         if(!window.rsa){     8             window.rsa = new JSEncrypt(); 9             window.rsa.setPublicKey("MIGeMA0GCSqGSIb3DQEBAQUAA4GMADCBiAKBgHz+GrcnJ4w246LUsKeodDYKEQW2tUHvneYETB4/WtCWNJNH9A4NXJOKrF5eXtGB6hWw6DfkBrNawQi13Cok30HGAGOsqNC3TrG+lFH/MdnIFLc0bc4SNKy0aL6h9Og+OnEfqyGe9hBmviVkYVONMwXAM+mkd74ZEEw1rlTodKf9AgMBAAE=");10         }11         12         var result = window.rsa.encrypt(enStr);13         // 加密失败返回原数据14         if(result === false){15             return enStr;16         }17         return JSON.stringify(result);18     }

ps:经测试发现,rsa最多只能对117个字节进行加密。超过117个字节就会加密失败。

js第二版本:

思路:若超过117个字节,就切分开分别进行加密。

 1 // 对数据分段加密 2     function segmentEncrypt(enStr){ 3         if(typeof(JSEncrypt) === "function"){ 4             if(!window.rsa){     5                 window.rsa = new JSEncrypt(); 6                 window.rsa.setPublicKey("MIGeMA0GCSqGSIb3DQEBAQUAA4GMADCBiAKBgHz+GrcnJ4w246LUsKeodDYKEQW2tUHvneYETB4/WtCWNJNH9A4NXJOKrF5eXtGB6hWw6DfkBrNawQi13Cok30HGAGOsqNC3TrG+lFH/MdnIFLc0bc4SNKy0aL6h9Og+OnEfqyGe9hBmviVkYVONMwXAM+mkd74ZEEw1rlTodKf9AgMBAAE="); 7             } 8         }else{ 9             return enStr;10         } 11         12         var result = [],13             offSet = 0,14             cache = ‘‘,15             i = 1,16             inputLen = enStr.length;17         18         while (inputLen - offSet > 0) {19             if (inputLen - offSet > 117) {20                 cache = window.rsa.encrypt(enStr.substring(offSet, 117 * i));21             } else {22                 cache = window.rsa.encrypt(enStr.substring(offSet));23             }24             // 加密失败返回原数据25             if(cache === false){26                 return enStr;27             }28             offSet = i++ * 117;29             30             result.push(cache);31         }32         return JSON.stringify(result);33     }

java代码:

  1 package com.test.utils;  2   3 import java.io.ByteArrayOutputStream;  4 import java.security.Key;  5 import java.security.KeyFactory;  6 import java.security.KeyPair;  7 import java.security.KeyPairGenerator;  8 import java.security.SecureRandom;  9 import java.security.interfaces.RSAPrivateKey; 10 import java.security.interfaces.RSAPublicKey; 11 import java.security.spec.PKCS8EncodedKeySpec; 12 import java.security.spec.X509EncodedKeySpec; 13 import java.util.HashMap; 14 import java.util.Map; 15  16 import javax.crypto.Cipher; 17  18 import org.apache.commons.codec.binary.Base64; 19 import org.slf4j.Logger; 20 import org.slf4j.LoggerFactory; 21  22 public class RSAUtil { 23     private static Logger logger = LoggerFactory.getLogger(RSAUtil.class);    //日志记录 24     private static final String KEY_ALGORITHM = "RSA"; 25      26     //临时使用 27     public static final String RSA_PUB_KEY = "MIGeMA0GCSqGSIb3DQEBAQUAA4GMADCBiAKBgHz+GrcnJ4w246LUsKeodDYKEQW2 28 tUHvneYETB4/WtCWNJNH9A4NXJOKrF5eXtGB6hWw6DfkBrNawQi13Cok30HGAGOs 29 qNC3TrG+lFH/MdnIFLc0bc4SNKy0aL6h9Og+OnEfqyGe9hBmviVkYVONMwXAM+mk 30 d74ZEEw1rlTodKf9AgMBAAE="; 31     public static final String RSA_PRI_KEY = "MIICWgIBAAKBgHz+GrcnJ4w246LUsKeodDYKEQW2tUHvneYETB4/WtCWNJNH9A4N 32 XJOKrF5eXtGB6hWw6DfkBrNawQi13Cok30HGAGOsqNC3TrG+lFH/MdnIFLc0bc4S 33 NKy0aL6h9Og+OnEfqyGe9hBmviVkYVONMwXAM+mkd74ZEEw1rlTodKf9AgMBAAEC 34 gYAv3vJEa06OOQd9+Y+e5rl7aOeUFKHfGvKSgdrVStZxRNXmAozKRPvL1jSl/+a4 35 vtT0cci+fyrBzmRX/a7QxUZr1ROryeqv/DLnz8b1fXbIIXfO0MiNniytG0qzEHda 36 Vxof3reibaHLCL6wM266qgTVd2FMo8igATUgWvpMS/xuAQJBAMBcyxa/Vv496Fq7 37 ynvuXWIzdCJSYBe9CFjICgOeHLrz+9d66GiHfjkgU/RygUhLbgA1ogEsx+/4LshV 38 t3Tt02ECQQCmV771jice594L8PQmfSgHEZpzk8F2LkGB8BznVzcRpr/EtI6Bfux5 39 +HWAGW7CEwvv5r1oPzbYd9lggkanNXYdAkBvBd+NTHfoG1D89T/jkWrCX9IacRLX 40 AJpNq37kIaCRYnorHtv+YJ1AWWE7R89IK4jchBfxt6fZ35MYuyg8S3thAkAZSPlE 41 Bkm4DvLXydazCw9Mk8ZwjyM3PazDfaZHHCDI1BoOYovO72Yu3C+wOy103sRPwTlF 42 YWaK3Rzz6JmozR2ZAkBQsQhOXafSG1cGGx43mSzSAtBD1kfQAD2YVvR4B9NtOoWc 43 6Zyxf+Ek2P21ZIEWihTCM7XS9BYkJWHvcyun7Xeb"; 44      45     //map 键名 46     public static final String PUBLIC_KEY = "RSAPublicKey"; 47     public static final String PRIVATE_KEY = "RSAPrivateKey"; 48  49      50     /** 51      * 初始化密钥 52      * @return 53      */ 54     public static Map<String, String> initKey() { 55         Map<String, String> map = new HashMap<String, String>(); 56         try { 57             // 随机生成密钥对 58             KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance(KEY_ALGORITHM); 59              60             // 按照指定字符串生成密钥对 61             keyPairGen.initialize(1024, new SecureRandom()); 62  63             KeyPair keyPair = keyPairGen.generateKeyPair(); 64              65             // 公钥 66             RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic(); 67             String pubkey = new String(Base64.encodeBase64(publicKey.getEncoded())); 68  69             // 私钥 70             RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate(); 71             String prikey = new String(Base64.encodeBase64(privateKey.getEncoded())); 72              73             map.put(PUBLIC_KEY, pubkey); 74             map.put(PRIVATE_KEY, prikey); 75         } catch (Exception e) { 76             logger.error("生成秘钥失败", e); 77         } 78         return map; 79     } 80     /** 81      * 公钥加密 82      *  83      * @param data 84      * @param key 85      * @return 86      */ 87     public static String encryptByPublicKey(String data, String key) { 88         try { 89             // 取得公钥 90             X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(Base64.decodeBase64(key)); 91             KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM); 92             Key publicKey = keyFactory.generatePublic(x509KeySpec); 93  94             Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm()); 95             cipher.init(Cipher.ENCRYPT_MODE, publicKey); 96  97             byte[] encryptedData = http://www.mamicode.com/data.getBytes("utf-8"); 98             int inputLen = encryptedData.length; 99             ByteArrayOutputStream out = new ByteArrayOutputStream();100             int offSet = 0;101             byte[] cache;102             int i = 0;103             // 对数据分段加密104             while (inputLen - offSet > 0) {105                 if (inputLen - offSet > 117) {106                     cache = cipher.doFinal(encryptedData, offSet, 117);107                 } else {108                     cache = cipher.doFinal(encryptedData, offSet, inputLen - offSet);109                 }110                 out.write(cache, 0, cache.length);111                 i++;112                 offSet = i * 117;113             }114             byte[] decryptedData =http://www.mamicode.com/ out.toByteArray();115             out.close();116             117             return new String(Base64.encodeBase64(decryptedData));118         } catch (Exception e) {119              logger.error("公钥加密异常!", e);120         }121         return data;122     }123     124     /**125      * 私钥解密126      * 127      * @param data128      * @param key129      * @return130      */131     public static String decryptByPrivateKey(String data, String key) {132         try {133             // 对密钥解密134             byte[] keyBytes = Base64.decodeBase64(key);135 136             // 取得私钥137             PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(keyBytes);138             KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);139             Key privateKey = keyFactory.generatePrivate(pkcs8KeySpec);140 141             Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());142             cipher.init(Cipher.DECRYPT_MODE, privateKey);143 144             byte[] encryptedData =http://www.mamicode.com/ Base64.decodeBase64(data);145 146             int inputLen = encryptedData.length;147             ByteArrayOutputStream out = new ByteArrayOutputStream();148             int offSet = 0;149             byte[] cache;150             int i = 0;151             // 对数据分段解密152             while (inputLen - offSet > 0) {153                 if (inputLen - offSet > 128) {154                     cache = cipher.doFinal(encryptedData, offSet, 128);155                 } else {156                     cache = cipher.doFinal(encryptedData, offSet, inputLen - offSet);157                 }158                 out.write(cache, 0, cache.length);159                 i++;160                 offSet = i * 128;161             }162             byte[] decryptedData =http://www.mamicode.com/ out.toByteArray();163             out.close();164 165             return new String(decryptedData, "utf-8");166 167         } catch (Exception e) {168             logger.error("私钥解密异常", e);169         }170         return data;171     }172 }

 

  

rsa加密算法,前后端实现。