写在前面
安全测试需要, 要修改一下登录时密码传输逻辑, 保证密码传输保密性和完整性以及新增用户保存用户密码时存储保密性及完整性, 以下是测试方提供的思路:

关于传输保密性及完整性
前台js代码(关键代码已加粗), 关于数据进行RSA加密部分详细可参考:RSA前台加密后台解密的应用
var data = $(":input").each(function() {
if (this.name == 'password') { //只加密密码
//获取公钥系数
var modulus = $('#hid_modulus').val();
//获取公钥指数
var exponent = $('#hid_exponent').val();
//获取最终公钥
var key = RSAUtils.getKeyPair(exponent, '', modulus);
//获取需加密的值(口令)
var passwordVal = $("#" + this.name).val();
//将口令md5
var hexMd5 = hex_md5(passwordVal);
//生成uuid
var uuid = guid();
//合并口令+md5(口令)+uuid
passwordVal = passwordVal + hexMd5 + uuid;//进行数据加密
var ap = RSAUtils.encryptedString(key, encodeURI(passwordVal));
formData[this.name] = ap;
} else {
formData[this.name] = $("#" + this.name).val();
}
});
$.ajax({
async: false,
cache: false,
type: 'POST',
url: checkurl,// 请求的action路径
data: formData,......
前台引用生成md5及生成uuid的js
生成uuid
// 生成随机数
function guid() {
return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
var r = Math.random() * 16 | 0, v = c == 'x' ? r : (r & 0x3 | 0x8);
return v.toString(16);
});
}
md5.js
/*
* A JavaScript implementation of the RSA Data Security, Inc. MD5 Message
* Digest Algorithm, as defined in RFC 1321.
* Version 2.1 Copyright (C) Paul Johnston 1999 - 2002.
* Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet
* Distributed under the BSD License
* See http://pajhome.org.uk/crypt/md5 for more info.
*/
/*
* Configurable variables. You may need to tweak these to be compatible with
* the server-side, but the defaults work in most cases.
*/
var hexcase = 0; /* hex output format. 0 - lowercase; 1 - uppercase */
var b64pad = ""; /* base-64 pad character. "=" for strict RFC compliance */
var chrsz = 8; /* bits per input character. 8 - ASCII; 16 - Unicode */
/*
* These are the functions you'll usually want to call
* They take string arguments and return either hex or base-64 encoded strings
*/
function hex_md5(s){ return binl2hex(core_md5(str2binl(s), s.length * chrsz));}
function b64_md5(s){ return binl2b64(core_md5(str2binl(s), s.length * chrsz));}
function str_md5(s){ return binl2str(core_md5(str2binl(s), s.length * chrsz));}
function hex_hmac_md5(key, data) { return binl2hex(core_hmac_md5(key, data)); }
function b64_hmac_md5(key, data) { return binl2b64(core_hmac_md5(key, data)); }
function str_hmac_md5(key, data) { return binl2str(core_hmac_md5(key, data)); }
/*
* Perform a simple self-test to see if the VM is working
*/
function md5_vm_test()
{
return hex_md5("abc") == "900150983cd24fb0d6963f7d28e17f72";
}
/*
* Calculate the MD5 of an array of little-endian words, and a bit length
*/
function core_md5(x, len)
{
/* append padding */
x[len >> 5] |= 0x80 << ((len) % 32);
x[(((len + 64) >>> 9) << 4) + 14] = len;
var a = 1732584193;
var b = -271733879;
var c = -1732584194;
var d = 271733878;
for(var i = 0; i < x.length; i += 16)
{
var olda = a;
var oldb = b;
var oldc = c;
var oldd = d;
a = md5_ff(a, b, c, d, x[i+ 0], 7 , -680876936);
d = md5_ff(d, a, b, c, x[i+ 1], 12, -389564586);
c = md5_ff(c, d, a, b, x[i+ 2], 17, 606105819);
b = md5_ff(b, c, d, a, x[i+ 3], 22, -1044525330);
a = md5_ff(a, b, c, d, x[i+ 4], 7 , -176418897);
d = md5_ff(d, a, b, c, x[i+ 5], 12, 1200080426);
c = md5_ff(c, d, a, b, x[i+ 6], 17, -1473231341);
b = md5_ff(b, c, d, a, x[i+ 7], 22, -45705983);
a = md5_ff(a, b, c, d, x[i+ 8], 7 , 1770035416);
d = md5_ff(d, a, b, c, x[i+ 9], 12, -1958414417);
c = md5_ff(c, d, a, b, x[i+10], 17, -42063);
b = md5_ff(b, c, d, a, x[i+11], 22, -1990404162);
a = md5_ff(a, b, c, d, x[i+12], 7 , 1804603682);
d = md5_ff(d, a, b, c, x[i+13], 12, -40341101);
c = md5_ff(c, d, a, b, x[i+14], 17, -1502002290);
b = md5_ff(b, c, d, a, x[i+15], 22, 1236535329);
a = md5_gg(a, b, c, d, x[i+ 1], 5 , -165796510);
d = md5_gg(d, a, b, c, x[i+ 6], 9 , -1069501632);
c = md5_gg(c, d, a, b, x[i+11], 14, 643717713);
b = md5_gg(b, c, d, a, x[i+ 0], 20, -373897302);
a = md5_gg(a, b, c, d, x[i+ 5], 5 , -701558691);
d = md5_gg(d, a, b, c, x[i+10], 9 , 38016083);
c = md5_gg(c, d, a, b, x[i+15], 14, -660478335);
b = md5_gg(b, c, d, a, x[i+ 4], 20, -405537848);
a = md5_gg(a, b, c, d, x[i+ 9], 5 , 568446438);
d = md5_gg(d, a, b, c, x[i+14], 9 , -1019803690);
c = md5_gg(c, d, a, b, x[i+ 3], 14, -187363961);
b = md5_gg(b, c, d, a, x[i+ 8], 20, 1163531501);
a = md5_gg(a, b, c, d, x[i+13], 5 , -1444681467);
d = md5_gg(d, a, b, c, x[i+ 2], 9 , -51403784);
c = md5_gg(c, d, a, b, x[i+ 7], 14, 1735328473);
b = md5_gg(b, c, d, a, x[i+12], 20, -1926607734);
a = md5_hh(a, b, c, d, x[i+ 5], 4 , -378558);
d = md5_hh(d, a, b, c, x[i+ 8], 11, -2022574463);
c = md5_hh(c, d, a, b, x[i+11], 16, 1839030562);
b = md5_hh(b, c, d, a, x[i+14], 23, -35309556);
a = md5_hh(a, b, c, d, x[i+ 1], 4 , -1530992060);
d = md5_hh(d, a, b, c, x[i+ 4], 11, 1272893353);
c = md5_hh(c, d, a, b, x[i+ 7], 16, -155497632);
b = md5_hh(b, c, d, a, x[i+10], 23, -1094730640);
a = md5_hh(a, b, c, d, x[i+13], 4 , 681279174);
d = md5_hh(d, a, b, c, x[i+ 0], 11, -358537222);
c = md5_hh(c, d, a, b, x[i+ 3], 16, -722521979);
b = md5_hh(b, c, d, a, x[i+ 6], 23, 76029189);
a = md5_hh(a, b, c, d, x[i+ 9], 4 , -640364487);
d = md5_hh(d, a, b, c, x[i+12], 11, -421815835);
c = md5_hh(c, d, a, b, x[i+15], 16, 530742520);
b = md5_hh(b, c, d, a, x[i+ 2], 23, -995338651);
a = md5_ii(a, b, c, d, x[i+ 0], 6 , -198630844);
d = md5_ii(d, a, b, c, x[i+ 7], 10, 1126891415);
c = md5_ii(c, d, a, b, x[i+14], 15, -1416354905);
b = md5_ii(b, c, d, a, x[i+ 5], 21, -57434055);
a = md5_ii(a, b, c, d, x[i+12], 6 , 1700485571);
d = md5_ii(d, a, b, c, x[i+ 3], 10, -1894986606);
c = md5_ii(c, d, a, b, x[i+10], 15, -1051523);
b = md5_ii(b, c, d, a, x[i+ 1], 21, -2054922799);
a = md5_ii(a, b, c, d, x[i+ 8], 6 , 1873313359);
d = md5_ii(d, a, b, c, x[i+15], 10, -30611744);
c = md5_ii(c, d, a, b, x[i+ 6], 15, -1560198380);
b = md5_ii(b, c, d, a, x[i+13], 21, 1309151649);
a = md5_ii(a, b, c, d, x[i+ 4], 6 , -145523070);
d = md5_ii(d, a, b, c, x[i+11], 10, -1120210379);
c = md5_ii(c, d, a, b, x[i+ 2], 15, 718787259);
b = md5_ii(b, c, d, a, x[i+ 9], 21, -343485551);
a = safe_add(a, olda);
b = safe_add(b, oldb);
c = safe_add(c, oldc);
d = safe_add(d, oldd);
}
return Array(a, b, c, d);
}
/*
* These functions implement the four basic operations the algorithm uses.
*/
function md5_cmn(q, a, b, x, s, t)
{
return safe_add(bit_rol(safe_add(safe_add(a, q), safe_add(x, t)), s),b);
}
function md5_ff(a, b, c, d, x, s, t)
{
return md5_cmn((b & c) | ((~b) & d), a, b, x, s, t);
}
function md5_gg(a, b, c, d, x, s, t)
{
return md5_cmn((b & d) | (c & (~d)), a, b, x, s, t);
}
function md5_hh(a, b, c, d, x, s, t)
{
return md5_cmn(b ^ c ^ d, a, b, x, s, t);
}
function md5_ii(a, b, c, d, x, s, t)
{
return md5_cmn(c ^ (b | (~d)), a, b, x, s, t);
}
/*
* Calculate the HMAC-MD5, of a key and some data
*/
function core_hmac_md5(key, data)
{
var bkey = str2binl(key);
if(bkey.length > 16) bkey = core_md5(bkey, key.length * chrsz);
var ipad = Array(16), opad = Array(16);
for(var i = 0; i < 16; i++)
{
ipad[i] = bkey[i] ^ 0x36363636;
opad[i] = bkey[i] ^ 0x5C5C5C5C;
}
var hash = core_md5(ipad.concat(str2binl(data)), 512 + data.length * chrsz);
return core_md5(opad.concat(hash), 512 + 128);
}
/*
* Add integers, wrapping at 2^32. This uses 16-bit operations internally
* to work around bugs in some JS interpreters.
*/
function safe_add(x, y)
{
var lsw = (x & 0xFFFF) + (y & 0xFFFF);
var msw = (x >> 16) + (y >> 16) + (lsw >> 16);
return (msw << 16) | (lsw & 0xFFFF);
}
/*
* Bitwise rotate a 32-bit number to the left.
*/
function bit_rol(num, cnt)
{
return (num << cnt) | (num >>> (32 - cnt));
}
/*
* Convert a string to an array of little-endian words
* If chrsz is ASCII, characters >255 have their hi-byte silently ignored.
*/
function str2binl(str)
{
var bin = Array();
var mask = (1 << chrsz) - 1;
for(var i = 0; i < str.length * chrsz; i += chrsz)
bin[i>>5] |= (str.charCodeAt(i / chrsz) & mask) << (i%32);
return bin;
}
/*
* Convert an array of little-endian words to a string
*/
function binl2str(bin)
{
var str = "";
var mask = (1 << chrsz) - 1;
for(var i = 0; i < bin.length * 32; i += chrsz)
str += String.fromCharCode((bin[i>>5] >>> (i % 32)) & mask);
return str;
}
/*
* Convert an array of little-endian words to a hex string.
*/
function binl2hex(binarray)
{
var hex_tab = hexcase ? "0123456789ABCDEF" : "0123456789abcdef";
var str = "";
for(var i = 0; i < binarray.length * 4; i++)
{
str += hex_tab.charAt((binarray[i>>2] >> ((i%4)*8+4)) & 0xF) +
hex_tab.charAt((binarray[i>>2] >> ((i%4)*8 )) & 0xF);
}
return str;
}
/*
* Convert an array of little-endian words to a base-64 string
*/
function binl2b64(binarray)
{
var tab = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
var str = "";
for(var i = 0; i < binarray.length * 4; i += 3)
{
var triplet = (((binarray[i >> 2] >> 8 * ( i %4)) & 0xFF) << 16)
| (((binarray[i+1 >> 2] >> 8 * ((i+1)%4)) & 0xFF) << 8 )
| ((binarray[i+2 >> 2] >> 8 * ((i+2)%4)) & 0xFF);
for(var j = 0; j < 4; j++)
{
if(i * 8 + j * 6 > binarray.length * 32) str += b64pad;
else str += tab.charAt((triplet >> 6*(3-j)) & 0x3F);
}
}
return str;
}
后台java代码(关键代码已加粗)
userName = req.getParameter("userName");
password = req.getParameter("password");
//解密后的字符串
String complexStr = RSAUtils.decryptStringByJs(password);
// 获取明文
String pwd = MD5Check4RecvPwd.getPwd(complexStr);
// 判断密码是否被破坏
boolean isFit = MD5Check4RecvPwd.isFit(pwd, MD5Check4RecvPwd.getMD5Str(complexStr));
if (isFit) {
password = pwd;
} else {
j.setSuccess(false);
j.setRsaStr(GetRSAStr.getResStr(false));// notpass明文
j.setMsg("密码传输过程中被破坏,登录失败!");
return j;
}
关于存储保密性及完整性
tsUser.setPassword(oConvertUtils.isEmpty(tsUserVO.getPassword()) ? "" : AESDecoder.aesEncrypt(MD5Check4RecvPwd.getPwd(RSAUtils.decryptStringByJs(tsUserVO.getPassword()))));// 登录密码:aes(md5(口令)) tsUser.setAttr1(MD5Util.MD5Encode(MD5Check4RecvPwd.getPwd(RSAUtils.decryptStringByJs(tsUserVO.getPassword())), "UTF-8"));// 校验字段:md5(口令)
这里只是添加了校验字段, 并没有进行比对验证完整性.
RSA解密工具类详细可参考:RSA前台加密后台解密的应用, 以下是AES加密工具类和MD5工具类:
AESDecoder.java
package org.jeecgframework.core.util;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.lang.StringUtils;
import sun.misc.BASE64Decoder;
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.spec.SecretKeySpec;
import java.math.BigInteger;
import java.security.SecureRandom;
public class AESDecoder {
//密钥 (需要前端和后端保持一致)
public static final String KEY = "NARI@KD_123@Help";
//算法
private static final String ALGORITHMSTR = "AES/ECB/PKCS5Padding";
/**
* 随机生成指定长度的字符串
*/
public static String getRandomString(int length) { //length表示生成字符串的长度
String base = "abcdef#ghi$jkl!mno&pqrstu%vwxyz0_@123456789";
SecureRandom random = new SecureRandom();
StringBuffer sb = new StringBuffer();
for (int i = 0; i < length; i++) {
int number = random.nextInt(base.length());
sb.append(base.charAt(number));
}
return sb.toString();
}
/**
* aes解密
*
* @param encrypt 内容
* @return
* @throws Exception
*/
public static String aesDecrypt(String encrypt) {
try {
return aesDecrypt(encrypt, KEY);
} catch (Exception e) {
e.printStackTrace();
return "";
}
}
/**
* aes加密
*
* @param content
* @return
* @throws Exception
*/
public static String aesEncrypt(String content) {
try {
return aesEncrypt(content, KEY);
} catch (Exception e) {
e.printStackTrace();
return "";
}
}
/**
* 将byte[]转为各种进制的字符串
*
* @param bytes byte[]
* @param radix 可以转换进制的范围,从Character.MIN_RADIX到Character.MAX_RADIX,超出范围后变为10进制
* @return 转换后的字符串
*/
public static String binary(byte[] bytes, int radix) {
return new BigInteger(1, bytes).toString(radix);// 这里的1代表正数
}
/**
* base 64 encode
*
* @param bytes 待编码的byte[]
* @return 编码后的base 64 code
*/
public static String base64Encode(byte[] bytes) {
return Base64.encodeBase64String(bytes);
}
/**
* base 64 decode
*
* @param base64Code 待解码的base 64 code
* @return 解码后的byte[]
* @throws Exception
*/
public static byte[] base64Decode(String base64Code) throws Exception {
return StringUtils.isEmpty(base64Code) ? null : new BASE64Decoder().decodeBuffer(base64Code);
}
/**
* AES加密
*
* @param content 待加密的内容
* @param encryptKey 加密密钥
* @return 加密后的byte[]
* @throws Exception
*/
public static byte[] aesEncryptToBytes(String content, String encryptKey) throws Exception {
KeyGenerator kgen = KeyGenerator.getInstance("AES");
kgen.init(128);
Cipher cipher = Cipher.getInstance(ALGORITHMSTR);
cipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(encryptKey.getBytes(), "AES"));
return cipher.doFinal(content.getBytes("utf-8"));
}
/**
* AES加密为base 64 code
*
* @param content 待加密的内容
* @param encryptKey 加密密钥
* @return 加密后的base 64 code
* @throws Exception
*/
public static String aesEncrypt(String content, String encryptKey) throws Exception {
return base64Encode(aesEncryptToBytes(content, encryptKey));
}
/**
* AES解密
*
* @param encryptBytes 待解密的byte[]
* @param decryptKey 解密密钥
* @return 解密后的String
* @throws Exception
*/
public static String aesDecryptByBytes(byte[] encryptBytes, String decryptKey) throws Exception {
KeyGenerator kgen = KeyGenerator.getInstance("AES");
kgen.init(128);
Cipher cipher = Cipher.getInstance(ALGORITHMSTR);
cipher.init(Cipher.DECRYPT_MODE, new SecretKeySpec(decryptKey.getBytes(), "AES"));
byte[] decryptBytes = cipher.doFinal(encryptBytes);
return new String(decryptBytes);
}
/**
* 将base 64 code AES解密
*
* @param encryptStr 待解密的base 64 code
* @param decryptKey 解密密钥
* @return 解密后的string
* @throws Exception
*/
public static String aesDecrypt(String encryptStr, String decryptKey) throws Exception {
return StringUtils.isEmpty(encryptStr) ? null : aesDecryptByBytes(base64Decode(encryptStr), decryptKey);
}
public static String decrypt(String encryptStr) {
try {
return aesDecrypt(encryptStr, KEY);
} catch (Exception e) {
return null;
}
}
public static void main(String[] args) {
String encryCont = "";
System.out.println(encryCont = AESDecoder.aesEncrypt("jeecg"));//TGDXh7Ex6EFRLOIIhdp54g==
System.out.println(AESDecoder.aesDecrypt(encryCont));//Welcome@19
}
}
MD5Check4RecvPwd.java
package org.jeecgframework.web.system.util;
import org.jeecgframework.core.util.AESDecoder;
import org.jeecgframework.core.util.MD5Util;
import org.jeecgframework.core.util.oConvertUtils;
public class MD5Check4RecvPwd {
/**
* rsastr规则为:口令+md5(口令)+uuid
* 口令以123123为例,形如1231234297f44b13955235245b2497399d7a93de4096ac-6d6d-471c-9785-61ac8cd61d20
*/
public static String getPwd(String rsastr) {
String pwd = "";
if (oConvertUtils.isNotEmpty(rsastr)) {
pwd = rsastr.substring(0, rsastr.length() - 68);
}
return pwd;
}
public static String getMD5Str(String rsastr) {
String md5val = "";
if (oConvertUtils.isNotEmpty(rsastr)) {
md5val = rsastr.substring(rsastr.length() - 68, rsastr.length() - 36);
}
return md5val;
}
public static boolean isFit(String pwd, String md5) {
boolean flag = true;
String generateMd5 = MD5Util.MD5Encode(pwd, "UTF-8");
if (!generateMd5.equals(md5)) {
flag = false;
}
return flag;
}
public static void main(String[] args) {
String val = "1231234297f44b13955235245b2497399d7a93de4096ac-6d6d-471c-9785-61ac8cd61d20";
System.out.println(getPwd(val));// 123123
System.out.println(getMD5Str(val));// 4297f44b13955235245b2497399d7a93
System.out.println(isFit(getPwd(val), getMD5Str(val)));// true
String xiaoming = AESDecoder.aesEncrypt(MD5Util.MD5Encode("123456", "UTF-8"));
System.out.println(xiaoming);
}
}
RSAUtils.java
package org.jeecgframework.web.system.util;
import org.apache.commons.lang3.StringUtils;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.bouncycastle.util.encoders.Hex;
import javax.crypto.Cipher;
import java.io.UnsupportedEncodingException;
import java.math.BigInteger;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.security.*;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
/**
* RSA算法加密/解密工具类。
* 以下代码可以使用,唯一需要注意的是: org.bouncycastle...这个jar包需要找一到放到项目中,RSA所需jar包在java中已经自带了.
*
* @author liuyan
*/
public class RSAUtils {
/**
* 算法名称
*/
private static final String ALGORITHOM = "RSA";
/**
* 密钥大小
*/
private static final int KEY_SIZE = 1024;
/**
* 默认的安全服务提供者
*/
private static final Provider DEFAULT_PROVIDER = new BouncyCastleProvider();
private static KeyPairGenerator keyPairGen = null;
private static KeyFactory keyFactory = null;
/**
* 缓存的密钥对。
*/
private static KeyPair oneKeyPair = null;
//密文种子, 当想更换RSA钥匙的时候,只需要修改密文种子,即可更换
private static final String radamKey = "nari";//你自己随便写上数字或者英文即可
//类加载后进行初始化数据
static {
try {
keyPairGen = KeyPairGenerator.getInstance(ALGORITHOM,
DEFAULT_PROVIDER);
keyFactory = KeyFactory.getInstance(ALGORITHOM, DEFAULT_PROVIDER);
} catch (NoSuchAlgorithmException ex) {
ex.printStackTrace();
}
}
/**
* 根据指定的密文种子,生成并返回RSA密钥对。
*/
private static synchronized KeyPair generateKeyPair() {
try {
keyPairGen.initialize(KEY_SIZE,
new SecureRandom(radamKey.getBytes()));
oneKeyPair = keyPairGen.generateKeyPair();
return oneKeyPair;
} catch (InvalidParameterException ex) {
ex.printStackTrace();
} catch (NullPointerException ex) {
ex.printStackTrace();
}
return null;
}
/**
* 返回初始化时默认的公钥。
*/
public static RSAPublicKey getDefaultPublicKey() {
KeyPair keyPair = generateKeyPair();
if (keyPair != null) {
return (RSAPublicKey) keyPair.getPublic();
}
return null;
}
/**
* 使用指定的私钥解密数据。
*
* @param privateKey 给定的私钥。
* @param data 要解密的数据。
* @return 原数据。
*/
public static byte[] decrypt(PrivateKey privateKey, byte[] data) throws Exception {
Cipher ci = Cipher.getInstance(ALGORITHOM, DEFAULT_PROVIDER);
ci.init(Cipher.DECRYPT_MODE, privateKey);
return ci.doFinal(data);
}
/**
* 使用默认的私钥解密给定的字符串。
*
* @param encryptText 密文。
* @return 原文字符串。
*/
public static String decryptString(String encryptText) {
if (StringUtils.isBlank(encryptText)) {
return null;
}
KeyPair keyPair = generateKeyPair();
try {
byte[] en_data = Hex.decode(encryptText);
byte[] data = decrypt((RSAPrivateKey) keyPair.getPrivate(), en_data);
return new String(data);
} catch (NullPointerException ex) {
ex.printStackTrace();
} catch (Exception ex) {
ex.printStackTrace();
}
return null;
}
/**
* 使用秘钥 - 对js端传递过来密文进行解密
*
* @param encryptText 密文。
* @return {@code encryptText} 的原文字符串。
*/
public static String decryptStringByJs(String encryptText) {
String text = decryptString(encryptText);
if (text == null) {
return null;
}
String reverse = StringUtils.reverse(text);
String decode = null;
try {
//这里需要进行编码转换.注:在前端js对明文加密前需要先进行转码-可自行百度"编码转换"
decode = URLDecoder.decode(reverse, "UTF-8");
//System.out.println("解密后文字:" + decode);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return decode;
}
//java端 - 使用公钥进行加密
public static byte[] encrypt(String plaintext) throws Exception {
// 获取公钥及参数e,n
RSAPublicKey publicKey = RSAUtils.getDefaultPublicKey();
//获取公钥指数 e
BigInteger e = publicKey.getPublicExponent();
//获取公钥系数 n
BigInteger n = publicKey.getModulus();
//先将明文进行编码
String encode = URLEncoder.encode(plaintext);
// 获取明文字节数组 m
BigInteger m = new BigInteger(encode.getBytes());
// 进行明文加密 c
BigInteger c = m.modPow(e, n);
//返回密文字节数组
return c.toByteArray();
}
//java端 - 使用私钥进行解密
public static String decrypt(byte[] cipherText) throws Exception {
// 读取私钥
KeyPair keyPair = generateKeyPair();
RSAPrivateKey prk = (RSAPrivateKey) keyPair.getPrivate();
// 获取私钥参数-指数/系数
BigInteger d = prk.getPrivateExponent();
BigInteger n = prk.getModulus();
// 读取密文
BigInteger c = new BigInteger(cipherText);
// 进行解密
BigInteger m = c.modPow(d, n);
// 解密结果-字节数组
byte[] mt = m.toByteArray();
//转成String,此时是乱码
String en = new String(mt);
//再进行编码
String result = URLDecoder.decode(en, "UTF-8");
//最后返回解密后得到的明文
return result;
}
// public static void main(String[] args) {
// /*解密js端传递过来的密文*/
// //获取公钥对象--注意:前端那边需要用到公钥系数和指数
// RSAPublicKey publicKey = RSAUtils.getDefaultPublicKey();
// //公钥-系数(n)
// System.out.println("public key modulus:" + new String(Hex.encode(publicKey.getModulus().toByteArray())));
// //公钥-指数(e1)
// System.out.println("public key exponent:" + new String(Hex.encode(publicKey.getPublicExponent().toByteArray())));
// //JS加密后的字符串
// String param = "abd87309c1c01f8eb20e46008e7260d792b336505cccf6e0328a3b35f72ba6cec6f4913aa80e150f3f78529ef8259d04f8fb0cda049e1426b89e2122fae2470039556364cdde128bd1d9068ade1c828172086bc316907b77fe9551edfd0a7e427ecf310f720ee558bc1fee07714401554b0887672053ed9879f6aa895816f368";
// //解密后的字符串
// String param1 = RSAUtils.decryptStringByJs(param);
//
// System.out.println(param1);
//
// }
}
本文仅做为一个记录, 有疑问欢迎评论留言交流~