博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
RSA 非对称加密【转】
阅读量:6710 次
发布时间:2019-06-25

本文共 26855 字,大约阅读时间需要 89 分钟。

演示代码:

 

Base64工具类,可以让rsa编码的乱码变成一串字符序列

1 package com.utils;  2   3 import java.io.ByteArrayInputStream;  4 import java.io.ByteArrayOutputStream;  5 import java.io.File;  6 import java.io.FileInputStream;  7 import java.io.FileOutputStream;  8 import java.io.InputStream;  9 import java.io.OutputStream; 10  11 import it.sauronsoftware.base64.Base64; 12  13 /** */ 14 /** 15  * 

16 * BASE64编码解码工具包 17 *

18 *

19 * 依赖javabase64-1.3.1.jar 20 *

21 * 22 * @author IceWee 23 * @date 2012-5-19 24 * @version 1.0 25 */ 26 public class Base64Utils { 27 28 /** */ 29 /** 30 * 文件读取缓冲区大小 31 */ 32 private static final int CACHE_SIZE = 1024; 33 34 /** */ 35 /** 36 *

37 * BASE64字符串解码为二进制数据 38 *

39 * 40 * @param base64 41 * @return 42 * @throws Exception 43 */ 44 public static byte[] decode(String base64) throws Exception { 45 return Base64.decode(base64.getBytes()); 46 } 47 48 /** */ 49 /** 50 *

51 * 二进制数据编码为BASE64字符串 52 *

53 * 54 * @param bytes 55 * @return 56 * @throws Exception 57 */ 58 public static String encode(byte[] bytes) throws Exception { 59 return new String(Base64.encode(bytes)); 60 } 61 62 /** */ 63 /** 64 *

65 * 将文件编码为BASE64字符串 66 *

67 *

68 * 大文件慎用,可能会导致内存溢出 69 *

70 * 71 * @param filePath 72 * 文件绝对路径 73 * @return 74 * @throws Exception 75 */ 76 public static String encodeFile(String filePath) throws Exception { 77 byte[] bytes = fileToByte(filePath); 78 return encode(bytes); 79 } 80 81 /** */ 82 /** 83 *

84 * BASE64字符串转回文件 85 *

86 * 87 * @param filePath 88 * 文件绝对路径 89 * @param base64 90 * 编码字符串 91 * @throws Exception 92 */ 93 public static void decodeToFile(String filePath, String base64) throws Exception { 94 byte[] bytes = decode(base64); 95 byteArrayToFile(bytes, filePath); 96 } 97 98 /** */ 99 /**100 *

101 * 文件转换为二进制数组102 *

103 * 104 * @param filePath105 * 文件路径106 * @return107 * @throws Exception108 */109 public static byte[] fileToByte(String filePath) throws Exception {110 byte[] data = new byte[0];111 File file = new File(filePath);112 if (file.exists()) {113 FileInputStream in = new FileInputStream(file);114 ByteArrayOutputStream out = new ByteArrayOutputStream(2048);115 byte[] cache = new byte[CACHE_SIZE];116 int nRead = 0;117 while ((nRead = in.read(cache)) != -1) {118 out.write(cache, 0, nRead);119 out.flush();120 }121 out.close();122 in.close();123 data = out.toByteArray();124 }125 return data;126 }127 128 /** */129 /**130 *

131 * 二进制数据写文件132 *

133 * 134 * @param bytes135 * 二进制数据136 * @param filePath137 * 文件生成目录138 */139 public static void byteArrayToFile(byte[] bytes, String filePath) throws Exception {140 InputStream in = new ByteArrayInputStream(bytes);141 File destFile = new File(filePath);142 if (!destFile.getParentFile().exists()) {143 destFile.getParentFile().mkdirs();144 }145 destFile.createNewFile();146 OutputStream out = new FileOutputStream(destFile);147 byte[] cache = new byte[CACHE_SIZE];148 int nRead = 0;149 while ((nRead = in.read(cache)) != -1) {150 out.write(cache, 0, nRead);151 out.flush();152 }153 out.close();154 in.close();155 }156 157 }
RsaUtil工具类,可以调用里面的方法,产生公钥私钥对,和采用公钥加密,私钥加密等
1 package com.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.PrivateKey;  9 import java.security.PublicKey; 10 import java.security.Signature; 11 import java.security.interfaces.RSAPrivateKey; 12 import java.security.interfaces.RSAPublicKey; 13 import java.security.spec.PKCS8EncodedKeySpec; 14 import java.security.spec.X509EncodedKeySpec; 15 import java.util.HashMap; 16 import java.util.Map; 17  18 import javax.crypto.Cipher; 19  20 /** */ 21 /** 22  * 

23 * RSA公钥/私钥/签名工具包 24 *

25 *

26 * 罗纳德·李维斯特(Ron [R]ivest)、阿迪·萨莫尔(Adi [S]hamir)和伦纳德·阿德曼(Leonard [A]dleman) 27 *

28 *

29 * 字符串格式的密钥在未在特殊说明情况下都为BASE64编码格式

30 * 由于非对称加密速度极其缓慢,一般文件不使用它来加密而是使用对称加密,
31 * 非对称加密算法可以用来对对称加密的密钥加密,这样保证密钥的安全也就保证了数据的安全 32 *

33 * 34 * @author IceWee 35 * @date 2012-4-26 36 * @version 1.0 37 */ 38 public class RSAUtils { 39 40 /** */ 41 /** 42 * 加密算法RSA 43 */ 44 public static final String KEY_ALGORITHM = "RSA"; 45 46 /** */ 47 /** 48 * 签名算法 49 */ 50 public static final String SIGNATURE_ALGORITHM = "MD5withRSA"; 51 52 /** */ 53 /** 54 * 获取公钥的key 55 */ 56 private static final String PUBLIC_KEY = "RSAPublicKey"; 57 58 /** */ 59 /** 60 * 获取私钥的key 61 */ 62 private static final String PRIVATE_KEY = "RSAPrivateKey"; 63 64 /** */ 65 /** 66 * RSA最大加密明文大小 67 */ 68 private static final int MAX_ENCRYPT_BLOCK = 117; 69 70 /** */ 71 /** 72 * RSA最大解密密文大小 73 */ 74 private static final int MAX_DECRYPT_BLOCK = 128; 75 76 /** */ 77 /** 78 *

79 * 生成密钥对(公钥和私钥) 80 *

81 * 82 * @return 83 * @throws Exception 84 */ 85 public static Map
genKeyPair() throws Exception { 86 KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance(KEY_ALGORITHM); 87 keyPairGen.initialize(1024); 88 KeyPair keyPair = keyPairGen.generateKeyPair(); 89 RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic(); 90 RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate(); 91 Map
keyMap = new HashMap
(2); 92 keyMap.put(PUBLIC_KEY, publicKey); 93 keyMap.put(PRIVATE_KEY, privateKey); 94 return keyMap; 95 } 96 97 /** */ 98 /** 99 *

100 * 用私钥对信息生成数字签名101 *

102 * 103 * @param data104 * 已加密数据105 * @param privateKey106 * 私钥(BASE64编码)107 * 108 * @return109 * @throws Exception110 */111 public static String sign(byte[] data, String privateKey) throws Exception {112 byte[] keyBytes = Base64Utils.decode(privateKey);113 PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(keyBytes);114 KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);115 PrivateKey privateK = keyFactory.generatePrivate(pkcs8KeySpec);116 Signature signature = Signature.getInstance(SIGNATURE_ALGORITHM);117 signature.initSign(privateK);118 signature.update(data);119 return Base64Utils.encode(signature.sign());120 }121 122 /** */123 /**124 *

125 * 校验数字签名126 *

127 * 128 * @param data129 * 已加密数据130 * @param publicKey131 * 公钥(BASE64编码)132 * @param sign133 * 数字签名134 * 135 * @return136 * @throws Exception137 * 138 */139 public static boolean verify(byte[] data, String publicKey, String sign) throws Exception {140 byte[] keyBytes = Base64Utils.decode(publicKey);141 X509EncodedKeySpec keySpec = new X509EncodedKeySpec(keyBytes);142 KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);143 PublicKey publicK = keyFactory.generatePublic(keySpec);144 Signature signature = Signature.getInstance(SIGNATURE_ALGORITHM);145 signature.initVerify(publicK);146 signature.update(data);147 return signature.verify(Base64Utils.decode(sign));148 }149 150 /** */151 /**152 *

153 * 私钥解密154 *

155 * 156 * @param encryptedData157 * 已加密数据158 * @param privateKey159 * 私钥(BASE64编码)160 * @return161 * @throws Exception162 */163 public static byte[] decryptByPrivateKey(byte[] encryptedData, String privateKey) throws Exception {164 byte[] keyBytes = Base64Utils.decode(privateKey);165 PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(keyBytes);166 KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);167 Key privateK = keyFactory.generatePrivate(pkcs8KeySpec);168 Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());169 cipher.init(Cipher.DECRYPT_MODE, privateK);170 int inputLen = encryptedData.length;171 ByteArrayOutputStream out = new ByteArrayOutputStream();172 int offSet = 0;173 byte[] cache;174 int i = 0;175 // 对数据分段解密176 while (inputLen - offSet > 0) {177 if (inputLen - offSet > MAX_DECRYPT_BLOCK) {178 cache = cipher.doFinal(encryptedData, offSet, MAX_DECRYPT_BLOCK);179 } else {180 cache = cipher.doFinal(encryptedData, offSet, inputLen - offSet);181 }182 out.write(cache, 0, cache.length);183 i++;184 offSet = i * MAX_DECRYPT_BLOCK;185 }186 byte[] decryptedData = out.toByteArray();187 out.close();188 return decryptedData;189 }190 191 /** */192 /**193 *

194 * 公钥解密195 *

196 * 197 * @param encryptedData198 * 已加密数据199 * @param publicKey200 * 公钥(BASE64编码)201 * @return202 * @throws Exception203 */204 public static byte[] decryptByPublicKey(byte[] encryptedData, String publicKey) throws Exception {205 byte[] keyBytes = Base64Utils.decode(publicKey);206 X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(keyBytes);207 KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);208 Key publicK = keyFactory.generatePublic(x509KeySpec);209 Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());210 cipher.init(Cipher.DECRYPT_MODE, publicK);211 int inputLen = encryptedData.length;212 ByteArrayOutputStream out = new ByteArrayOutputStream();213 int offSet = 0;214 byte[] cache;215 int i = 0;216 // 对数据分段解密217 while (inputLen - offSet > 0) {218 if (inputLen - offSet > MAX_DECRYPT_BLOCK) {219 cache = cipher.doFinal(encryptedData, offSet, MAX_DECRYPT_BLOCK);220 } else {221 cache = cipher.doFinal(encryptedData, offSet, inputLen - offSet);222 }223 out.write(cache, 0, cache.length);224 i++;225 offSet = i * MAX_DECRYPT_BLOCK;226 }227 byte[] decryptedData = out.toByteArray();228 out.close();229 return decryptedData;230 }231 232 /** */233 /**234 *

235 * 公钥加密236 *

237 * 238 * @param data239 * 源数据240 * @param publicKey241 * 公钥(BASE64编码)242 * @return243 * @throws Exception244 */245 public static byte[] encryptByPublicKey(byte[] data, String publicKey) throws Exception {246 byte[] keyBytes = Base64Utils.decode(publicKey);247 X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(keyBytes);248 KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);249 Key publicK = keyFactory.generatePublic(x509KeySpec);250 // 对数据加密251 Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());252 cipher.init(Cipher.ENCRYPT_MODE, publicK);253 int inputLen = data.length;254 ByteArrayOutputStream out = new ByteArrayOutputStream();255 int offSet = 0;256 byte[] cache;257 int i = 0;258 // 对数据分段加密259 while (inputLen - offSet > 0) {260 if (inputLen - offSet > MAX_ENCRYPT_BLOCK) {261 cache = cipher.doFinal(data, offSet, MAX_ENCRYPT_BLOCK);262 } else {263 cache = cipher.doFinal(data, offSet, inputLen - offSet);264 }265 out.write(cache, 0, cache.length);266 i++;267 offSet = i * MAX_ENCRYPT_BLOCK;268 }269 byte[] encryptedData = out.toByteArray();270 out.close();271 return encryptedData;272 }273 274 /** */275 /**276 *

277 * 私钥加密278 *

279 * 280 * @param data281 * 源数据282 * @param privateKey283 * 私钥(BASE64编码)284 * @return285 * @throws Exception286 */287 public static byte[] encryptByPrivateKey(byte[] data, String privateKey) throws Exception {288 byte[] keyBytes = Base64Utils.decode(privateKey);289 PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(keyBytes);290 KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);291 Key privateK = keyFactory.generatePrivate(pkcs8KeySpec);292 Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());293 cipher.init(Cipher.ENCRYPT_MODE, privateK);294 int inputLen = data.length;295 ByteArrayOutputStream out = new ByteArrayOutputStream();296 int offSet = 0;297 byte[] cache;298 int i = 0;299 // 对数据分段加密300 while (inputLen - offSet > 0) {301 if (inputLen - offSet > MAX_ENCRYPT_BLOCK) {302 cache = cipher.doFinal(data, offSet, MAX_ENCRYPT_BLOCK);303 } else {304 cache = cipher.doFinal(data, offSet, inputLen - offSet);305 }306 out.write(cache, 0, cache.length);307 i++;308 offSet = i * MAX_ENCRYPT_BLOCK;309 }310 byte[] encryptedData = out.toByteArray();311 out.close();312 return encryptedData;313 }314 315 /** */316 /**317 *

318 * 获取私钥319 *

320 * 321 * @param keyMap322 * 密钥对323 * @return324 * @throws Exception325 */326 public static String getPrivateKey(Map
keyMap) throws Exception {327 Key key = (Key) keyMap.get(PRIVATE_KEY);328 return Base64Utils.encode(key.getEncoded());329 }330 331 /** */332 /**333 *

334 * 获取公钥335 *

336 * 337 * @param keyMap338 * 密钥对339 * @return340 * @throws Exception341 */342 public static String getPublicKey(Map
keyMap) throws Exception {343 Key key = (Key) keyMap.get(PUBLIC_KEY);344 return Base64Utils.encode(key.getEncoded());345 }346 347 /**348 * java端公钥加密349 */350 public static String encryptedDataOnJava(String data, String PUBLICKEY) {351 try {352 data = Base64Utils.encode(encryptByPublicKey(data.getBytes(), PUBLICKEY));353 } catch (Exception e) {354 // TODO Auto-generated catch block355 e.printStackTrace();356 }357 return data;358 }359 360 /**361 * java端私钥解密362 */363 public static String decryptDataOnJava(String data, String PRIVATEKEY) {364 String temp = "";365 try {366 byte[] rs = Base64Utils.decode(data);367 temp = new String(RSAUtils.decryptByPrivateKey(rs, PRIVATEKEY),"UTF-8"); //以utf-8的方式生成字符串368 369 } catch (Exception e) {370 e.printStackTrace();371 }372 return temp;373 }374 375 }

json工具类

1 package com.utils; 2  3 import com.google.gson.Gson; 4 import com.google.gson.GsonBuilder; 5 import com.google.gson.JsonNull; 6  7 public class JsonUtil { 8  9     private static Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd").serializeNulls().create();10 11     /**12      * @MethodName : toJson13      * @Description : 将对象转为JSON串,此方法能够满足大部分需求14      * @param src15      *            :将要被转化的对象16      * @return :转化后的JSON串17      */18     public static String toJson(Object src) {19         if (src == null) {20             return gson.toJson(JsonNull.INSTANCE);21         }22         return gson.toJson(src);23     }24 }

 

 到这一步我们的工具类准备的差不多了,可以开始进入我们的主题了,java端Rsa测试类和web端交互的demo了

Rsa测试java测试类

1 package com.test; 2  3 import java.util.Map; 4  5 import org.junit.Test; 6  7 import com.utils.Base64Utils; 8 import com.utils.RSAUtils; 9 10 public class RSATester {11 12     static String publicKey;13     static String privateKey;14 15     static {16         try {17             Map
keyMap = RSAUtils.genKeyPair();18 publicKey = RSAUtils.getPublicKey(keyMap);19 privateKey = RSAUtils.getPrivateKey(keyMap);20 System.err.println("公钥: \n\r" + publicKey);21 System.err.println("私钥: \n\r" + privateKey);22 } catch (Exception e) {23 e.printStackTrace();24 }25 }26 27 public static void main(String[] args) throws Exception {28 testJavaRsa();29 }30 31 @Test32 public void tests() throws Exception {33 String data = "hNYdT0/8wxljGvLQVPYUDeoWS217rmB5msKOljb6OBsOhdL1Domxt6Sy3BqdGqS3StGJuZuQ9wEFzGdyoTQ7IRiC0gRrkLuxvCUq8FANt1JpJCBqvzLdQD/ygCjkJMWWkMU4EFUW3xYkAsidqM8Zynhpk+mdja3789Ng4s68xJI=";34 35 String privateKey = "MIICdgIBADANBgkqhkiG9w0BAQEFAASCAmAwggJcAgEAAoGBAIn2zWqU7K/2qm5pOpq5bp9R+3MTnStWTfJU9nC/Vo7UKH9dITPvrELCTK+qlqpx5Fes+l0GY7n6u4n4jyiw4ejsvkZYQ5ww477yLOn2FcoEGuZEwPgSCmfTST0OFUgQqn+/J11k9L92jEHyieE3qmhMkMt0UsVUSJwx/nZxo30ZAgMBAAECgYBD3YHigeuEC4R+14iaf8jo2j0kuGtB3Cxvnlez0otTqw1YyYkBsU49cLKkXvfKVEgM0Ow/QltgKvSBxCE31PrrDka5TygVMqqA/IM7NrDvjUcGLjyoeNmLA8660fWcDxUTlAGN5kxIvUATayVwKVflpWPWu0FPKsWrZustnEo+4QJBAMCmYsWqAKWYMVRXFP3/XGRfio8DV793TOckyBSN9eh8UhgoZyT3u7oeHmDJEwm4aNMHlg1Pcdc6tNsvi1FRCiUCQQC3VNzfF4xOtUgX7vWPL8YVljLuXmy12iVYmg6ofu9l31nwM9FLQ1TRFglvF5LWrIXTQb07PgGd5DJMAQWGsqLlAkAPE7Z9M73TN+L8b8hDzJ1leZi1cpSGdoa9PEKwYR/SrxAZtefEm+LEQSEtf+8OfrEtetWCeyo0pvKKiOEFXytFAkEAgynL/DC0yXsZYUYtmYvshHU5ayFTVagFICbYZeSrEo+BoUDxdI9vl0fU6A5NmBlGhaZ65G+waG5jLc1tTrlvoQJAXBEoPcBNAosiZHQfYBwHqU6mJ9/ZacJh3MtJzGGebfEwJgtln5b154iANqNWXpySBLvkK+Boq7FYRiD83pqmUg==";36 byte[] rs = Base64Utils.decode(data);37 38 String r1 = new String(RSAUtils.decryptByPrivateKey(rs, privateKey));39 40 System.out.println("\r\n\r\n" + r1 + "okb");41 42 }43 44 static void testSign() throws Exception {45 System.err.println("私钥加密——公钥解密");46 String source = "32232";47 System.out.println("原文字:\r\n" + source);48 byte[] data = source.getBytes();49 byte[] encodedData = RSAUtils.encryptByPrivateKey(data, privateKey);50 System.out.println("加密后:\r\n" + new String(encodedData));51 byte[] decodedData = RSAUtils.decryptByPublicKey(encodedData, publicKey);52 String target = new String(decodedData);53 System.out.println("解密后: \r\n" + target);54 System.err.println("私钥签名——公钥验证签名");55 String sign = RSAUtils.sign(encodedData, privateKey);56 System.err.println("签名:\r" + sign);57 boolean status = RSAUtils.verify(encodedData, publicKey, sign);58 System.err.println("验证结果:\r" + status);59 }60 61 static void test() throws Exception {62 System.err.println("公钥加密——私钥解密");63 String source = "这是一行没有任何意义的文字,你看完了等于没看,不是吗?";64 System.out.println("\r加密前文字:\r\n" + source);65 byte[] data = source.getBytes();66 byte[] encodedData = RSAUtils.encryptByPublicKey(data, publicKey);67 System.out.println("加密后文字:\r\n" + new String(encodedData));68 System.out.println("----------------:base64处理:" + Base64Utils.encode(encodedData));69 byte[] decodedData = RSAUtils.decryptByPrivateKey(encodedData, privateKey);70 String target = new String(decodedData);71 System.out.println("解密后文字: \r\n" + target);72 }73 74 /*75 * 测试自己封装java端加密和解密的方法76 */77 78 static void testJavaRsa() {79 String PUBLICKEY = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCcd+0zTY9Gn94iqkQJTlxYnEnCeFsLkk0a7hoAvi2B74VzDVV3xH0ZO9RkXvo1SgCB+uzbEWdrgQkzTqyjfTtgOguu3OnkVxIMJF34ibchTY0LWHGxq1m2gLGuVVqrlu1LtdV0X7xo/5zc8Mr+46veWb86kSpqe6rOAm69WWo5GwIDAQAB";80 String PRIVATEKEY = "MIICdgIBADANBgkqhkiG9w0BAQEFAASCAmAwggJcAgEAAoGBAJx37TNNj0af3iKqRAlOXFicScJ4WwuSTRruGgC+LYHvhXMNVXfEfRk71GRe+jVKAIH67NsRZ2uBCTNOrKN9O2A6C67c6eRXEgwkXfiJtyFNjQtYcbGrWbaAsa5VWquW7Uu11XRfvGj/nNzwyv7jq95ZvzqRKmp7qs4Cbr1ZajkbAgMBAAECgYAHp349EkA+DjgJrhah9elilFKvZr/dcwy+koNHIgaL4rG+jRpvP3d3MowTVOocjUA1G5dWqCVNBwTyM5kSbl/nIxSCYwdUoDid4r0JbqkXkTTsIq3euHG8eiWr9rr3SDmwDojWoJEc4liVlfme8dQuMfgxe1QKq7wTrJwCKwbeMQJBAPwpknRPRK8W9hefbbtEu8mlbzUy+ER8Puq6dvS+lnWzJ8n2chJcHRYQFwWpjl4+SZuKeEcDmYmuQ7xuqEIayO0CQQCe2YeaxcU4uuDC45RAwCcMaNw1nDJuA+Gi47lXbroBXoeOiNZunViSZVUgDgrV/Ku6V54TaZIzZ21QFjf7mXEnAkEA7dZwMpAJonOvzfwrzbQ4wyrsx2q5zC68UT1qsdGJrJ48azutwC9tp7+pV0fj5nQtjS1/4Ms+aCQb84ET5rXIyQJAM0m45tgEHZT5DPO94kooUXFp6EVOYwcNyzILnZc6p0aGLhcwZPaYqmvdWEQwa3bxW3D+sPXdJou2V61U1f9s8QJALccvYwwWlCTq1iTmegYk9fOoc+isZKH+Z0YW70kFi94AYEO+utYwmXBEAqQ5VC/bywa1O71xdL4/RGCOSxBf2A==";81 String data = "你好啊,冯老师!s 223 1@324234234sfsfsf";82 data = RSAUtils.encryptedDataOnJava(data, PUBLICKEY);83 System.out.println("加密数据:" + data);84 85 System.out.println("解密数据:" + RSAUtils.decryptDataOnJava(data, PRIVATEKEY));86 }87 88 static void testFrontEncrptAndAfterDecrypt() {89 String PRIVATEKEY = "MIICdgIBADANBgkqhkiG9w0BAQEFAASCAmAwggJcAgEAAoGBAIn2zWqU7K/2qm5pOpq5bp9R+3MTnStWTfJU9nC/Vo7UKH9dITPvrELCTK+qlqpx5Fes+l0GY7n6u4n4jyiw4ejsvkZYQ5ww477yLOn2FcoEGuZEwPgSCmfTST0OFUgQqn+/J11k9L92jEHyieE3qmhMkMt0UsVUSJwx/nZxo30ZAgMBAAECgYBD3YHigeuEC4R+14iaf8jo2j0kuGtB3Cxvnlez0otTqw1YyYkBsU49cLKkXvfKVEgM0Ow/QltgKvSBxCE31PrrDka5TygVMqqA/IM7NrDvjUcGLjyoeNmLA8660fWcDxUTlAGN5kxIvUATayVwKVflpWPWu0FPKsWrZustnEo+4QJBAMCmYsWqAKWYMVRXFP3/XGRfio8DV793TOckyBSN9eh8UhgoZyT3u7oeHmDJEwm4aNMHlg1Pcdc6tNsvi1FRCiUCQQC3VNzfF4xOtUgX7vWPL8YVljLuXmy12iVYmg6ofu9l31nwM9FLQ1TRFglvF5LWrIXTQb07PgGd5DJMAQWGsqLlAkAPE7Z9M73TN+L8b8hDzJ1leZi1cpSGdoa9PEKwYR/SrxAZtefEm+LEQSEtf+8OfrEtetWCeyo0pvKKiOEFXytFAkEAgynL/DC0yXsZYUYtmYvshHU5ayFTVagFICbYZeSrEo+BoUDxdI9vl0fU6A5NmBlGhaZ65G+waG5jLc1tTrlvoQJAXBEoPcBNAosiZHQfYBwHqU6mJ9/ZacJh3MtJzGGebfEwJgtln5b154iANqNWXpySBLvkK+Boq7FYRiD83pqmUg==";90 String data = "FBGU7sQfpSfCgB2hqFuIqkivEUHVRHD8JFdyxYeWqQHsTj9UEuVmvi28n1fOHRwW+3aZD3ttdzfUHWiXD2NErcX/CYs5BtSXT7RcJfWWcXvegq5BBDEAJCADWCRdYnblN+SLUC+ctDXcLw4xmjwAajowSzhCfY/lU3TdnJjO488=";91 System.out.println("解密数据:" + RSAUtils.decryptDataOnJava(data, PRIVATEKEY));92 }93 94 }

 前端加密jsp页面

 

1 <%@ page language="java" contentType="text/html; charset=UTF-8" 2     pageEncoding="UTF-8"%> 3  4  5  6 
7 Insert title here 8 9 10 11 12 13 41

公钥:

42 44

私钥

45 46

47
48 用户名:
密码:
50

51 用户密文52
54 密码密文55
57
58
59 60 61

 后端servlet解密

1 package com; 2  3 import java.io.IOException; 4 import java.util.HashMap; 5  6 import javax.servlet.ServletException; 7 import javax.servlet.http.HttpServlet; 8 import javax.servlet.http.HttpServletRequest; 9 import javax.servlet.http.HttpServletResponse;10 11 import com.utils.JsonUtil;12 import com.utils.RSAUtils;13 14 /**15  * Servlet implementation class JieMiServlet16  */17 public class JieMiServlet extends HttpServlet {18     private static final long serialVersionUID = 1L;19 20     protected void doGet(HttpServletRequest request, HttpServletResponse response)21             throws ServletException, IOException {22         doPost(request, response);23     }24 25     protected void doPost(HttpServletRequest request, HttpServletResponse response)26             throws ServletException, IOException {27         // 获取数据28         String uname = request.getParameter("uname");29         String password = request.getParameter("password");30         String PRIVATEKEY = "MIICdgIBADANBgkqhkiG9w0BAQEFAASCAmAwggJcAgEAAoGBAIn2zWqU7K/2qm5pOpq5bp9R+3MTnStWTfJU9nC/Vo7UKH9dITPvrELCTK+qlqpx5Fes+l0GY7n6u4n4jyiw4ejsvkZYQ5ww477yLOn2FcoEGuZEwPgSCmfTST0OFUgQqn+/J11k9L92jEHyieE3qmhMkMt0UsVUSJwx/nZxo30ZAgMBAAECgYBD3YHigeuEC4R+14iaf8jo2j0kuGtB3Cxvnlez0otTqw1YyYkBsU49cLKkXvfKVEgM0Ow/QltgKvSBxCE31PrrDka5TygVMqqA/IM7NrDvjUcGLjyoeNmLA8660fWcDxUTlAGN5kxIvUATayVwKVflpWPWu0FPKsWrZustnEo+4QJBAMCmYsWqAKWYMVRXFP3/XGRfio8DV793TOckyBSN9eh8UhgoZyT3u7oeHmDJEwm4aNMHlg1Pcdc6tNsvi1FRCiUCQQC3VNzfF4xOtUgX7vWPL8YVljLuXmy12iVYmg6ofu9l31nwM9FLQ1TRFglvF5LWrIXTQb07PgGd5DJMAQWGsqLlAkAPE7Z9M73TN+L8b8hDzJ1leZi1cpSGdoa9PEKwYR/SrxAZtefEm+LEQSEtf+8OfrEtetWCeyo0pvKKiOEFXytFAkEAgynL/DC0yXsZYUYtmYvshHU5ayFTVagFICbYZeSrEo+BoUDxdI9vl0fU6A5NmBlGhaZ65G+waG5jLc1tTrlvoQJAXBEoPcBNAosiZHQfYBwHqU6mJ9/ZacJh3MtJzGGebfEwJgtln5b154iANqNWXpySBLvkK+Boq7FYRiD83pqmUg==";31         // 解密32         uname = RSAUtils.decryptDataOnJava(uname, PRIVATEKEY);33         password = RSAUtils.decryptDataOnJava(password, PRIVATEKEY);34         // 用map封装返回的数据35         HashMap
result = new HashMap
();36 result.put("uname", uname);37 result.put("password", password);38 39 response.getWriter().print(JsonUtil.toJson(result));40 41 }42 43 }

转自【https://www.cnblogs.com/nanyangke-cjz/p/5898361.html】

你可能感兴趣的文章
JVM调优总结
查看>>
Linux 6下yum方式安装配置LAMP平台
查看>>
OpenCASCADE Coordinate Transforms
查看>>
loadrunner安装
查看>>
pt-query-digest查询日志分析工具
查看>>
张明贵-Linux基础命令学习-5
查看>>
模拟Linux开机故障与解决方案
查看>>
三大范式和五大约束
查看>>
vmware DELL定制
查看>>
&nb
查看>>
lombok的builder设置默认值的问题
查看>>
lvs的nat模式
查看>>
Java 数组 之 一维数组 追加 元素
查看>>
Keil uVision4复杂运用教程
查看>>
OSPF 基本配置
查看>>
猜拳游戏
查看>>
MySQL学习笔记(三)
查看>>
磁盘和文件系统管理
查看>>
Kafka connect介绍、部署及开发
查看>>
运维知识总结1
查看>>