java中前端JS公钥加密,后台私钥解密
2019-11-27 16:08:02来源:博客园 阅读 ()
java中前端JS公钥加密,后台私钥解密
思路:前端利用 jsencrypt.js 将用户名密码加密. 后台解密账户密码.
提供一个js连接:https://passport.cnblogs.com/scripts/jsencrypt.min.js
提供一个密钥生成连接:http://web.chacuo.net/netrsakeypair
这里只对密码加密
效果图
2.
3.
----------------------------------------------------------------html---------------------------------------------------------------
<form method="post" action="/home/testForm" onsubmit="check()">
<table>
<tr>
<td>账号</td>
<td>
<input type="text" name="username" ></input>
</td>
</tr>
</tr>
<td>密码</td>
<td>
<input type="password" id="t_password"></input>
<input style="display:none;" type="password" id="password" name="password"></input>
</td>
</tr>
<tr>
<td>
<input type="submit" value="登陆">
</td>
</tr>
</table>
</form>
<script type="text/javascript">
//公钥 这里不建议写死, 可以放在配置文件中 有后台传递过来
var publicKey ="MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDNmxeD+6WB6TfUqG9xvOPNJOM/1caP6T9JQ9AJDKErRDkYNKvNm0f+e+GzHKLblZ5G2d7OzZz4Zxk5TlwyWrneoPRaJJ4ycixWp5t4DYdc8zu5ra7lnMbZK7t54p1WygPwdMZJi5rhQCA1ATnVT6ho/C4wbNEP0xvR20vzgdH8nQIDAQAB";
function encryptPwd(val){
var encrypt = new JSEncrypt();
encrypt.setPublicKey(publicKey);
// 加密
return encrypt.encrypt(val);
}
function check(){
var userName = $("#t_username").val();
var passWord = $("#t_password").val();
if($.trim(userName).length > 0 && $.trim(userName).length < 100){
$("#username").val($.trim(userName));
}
if($.trim(passWord).length > 0 && $.trim(passWord).length < 100){
$("#password").val(encryptPwd($.trim(passWord)));
}
return true;
}
</script>
------------------------------------------------------------------------------------java--------------------------------------------------------------------------------------------
/**
* 登陆加密测试
* @param model
* @return
*/
@RequestMapping("testForm")
public String testform(Model model, HttpServletRequest request){
String password = request.getParameter("password");
String privateKey ="MIICdQIBADANBgkqhkiG9w0BAQEFAASCAl8wggJbAgEAAoGBAM2bF4P7pYHpN9Sob3G8480k4z/Vxo/pP0lD0AkMoStEORg0q82bR/574bMcotuVnkbZ3s7NnPhnGTlOXDJaud6g9FoknjJyLFanm3gNh1zzO7mtruWcxtkru3ninVbKA/B0xkmLmuFAIDUBOdVPqGj8LjBs0Q/TG9HbS/OB0fydAgMBAAECgYB7Z1XS4qww7/CRk9Ln2i6EB1raCo4V/DH+4FOxysHFPTpje+GOE2A/rs0Feu+IiiGodsXTK/fF4+Nw0MZndqrNj4N0zscOuXk/8BF9qwltGf6/p/qUia9P+qGAaN5TtYvflbnlNGePaZ6unD2deQSbl6vxIWBWHwBFNPHtgjUigQJBAPZ4FL1QkuHI23iKhSnEy5aHfvk2dBiv+YWjisSqr/3RpOgD8De+dzVJOx0XJZiRdCRvbpIueJRqHZaKEgOf7X0CQQDVjnxHdaA8xybNkGg1pURauFGYmCXjlCBIN1Kk+09pspV4+kY7Bvj3vNF0yrDembVrJVc8EqVOklVTWQzh2fWhAkAHPFc/h5IIVuE6lLZ8F27yqF+t6U9XOjNVHQwB4hDwnqr8tMDkog7V3aSCoh9Ub1C9kRfp6rtXgBYGSV9mA9fxAkBJFHBtF9CU2+XodKFkskCY9vhdSru0jG0bqWrrsGB1oDpMYwEDlBhA1umqmO47zsfpeabHlO3i3Gq8kf25kBfhAkBd0KCdyLjevomntZ8kOSiCbAdAJB30K5AKAxBCUrbT8HwySGbC8YiGewlUryvkood5k5YvU5VjVdUYR2j82Rtm";
try {
if (!password.equals("")) {
password = com.jesims.common.utils.RSAUtils.decryptByPrivateKey(password, privateKey);
}
} catch (Exception e) {
}
return "home/homeList";
}
-----------------------------------------------------utils------------------------------------------
import java.io.ByteArrayOutputStream;
import java.security.Key;
import java.security.KeyFactory;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.HashMap;
import java.util.Map;
import javax.crypto.Cipher;
import com.email.home.utils.Base64Utils;
import org.apache.commons.lang.StringUtils;
/** */
/**
* <p>
* RSA公钥/私钥/签名工具包
* </p>
* <p>
* 罗纳德·李维斯特(Ron [R]ivest)、阿迪·萨莫尔(Adi [S]hamir)和伦纳德·阿德曼(Leonard [A]dleman)
* </p>
* <p>
* 字符串格式的密钥在未在特殊说明情况下都为BASE64编码格式<br/>
* 由于非对称加密速度极其缓慢,一般文件不使用它来加密而是使用对称加密,<br/>
* 非对称加密算法可以用来对对称加密的密钥加密,这样保证密钥的安全也就保证了数据的安全
* </p>
*
* @author IceWee, Max.Lee
* @date 2012-4-26
* @version 1.0
*/
public class RSAUtils {
/**
* 加密算法RSA
*/
// public static final String KEY_ALGORITHM = "RSA/ECB/PKCS1Padding";
public static final String KEY_ALGORITHM = "RSA";
/**
* 签名算法
*/
public static final String SIGNATURE_ALGORITHM = "MD5withRSA";
/**
* 获取公钥的key
*/
private static final String PUBLIC_KEY = "RSAPublicKey";
/**
* 获取私钥的key
*/
private static final String PRIVATE_KEY = "RSAPrivateKey";
/**
* RSA最大加密明文大小
*/
private static final int MAX_ENCRYPT_BLOCK = 117;
/**
* RSA最大解密密文大小
*/
private static final int MAX_DECRYPT_BLOCK = 128;
/**
* <p>
* 生成密钥对(公钥和私钥)
* </p>
*
* @return
* @throws Exception
*/
public static Map<String, Object> genKeyPair() throws Exception {
KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance(KEY_ALGORITHM);
keyPairGen.initialize(512);
KeyPair keyPair = keyPairGen.generateKeyPair();
RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();
RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();
Map<String, Object> keyMap = new HashMap<String, Object>(2);
keyMap.put(PUBLIC_KEY, publicKey);
keyMap.put(PRIVATE_KEY, privateKey);
return keyMap;
}
/**
* <p>
* 用私钥对信息生成数字签名
* </p>
*
* @param data
* 已加密数据
* @param privateKey
* 私钥(BASE64编码)
*
* @return
* @throws Exception
*/
// public static String sign(byte[] data, String privateKey) throws Exception {
// byte[] keyBytes = Base64Utils.decode(privateKey);
// PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(keyBytes);
// KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
// PrivateKey privateK = keyFactory.generatePrivate(pkcs8KeySpec);
// Signature signature = Signature.getInstance(SIGNATURE_ALGORITHM);
// signature.initSign(privateK);
// signature.update(data);
// return Base64Utils.encode(signature.sign());
// }
/**
* <p>
* 校验数字签名
* </p>
*
* @param data
* 已加密数据
* @param publicKey
* 公钥(BASE64编码)
* @param sign
* 数字签名
*
* @return
* @throws Exception
*
*/
// public static boolean verify(byte[] data, String publicKey, String sign) throws Exception {
// byte[] keyBytes = Base64Utils.decode(publicKey);
// X509EncodedKeySpec keySpec = new X509EncodedKeySpec(keyBytes);
// KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
// PublicKey publicK = keyFactory.generatePublic(keySpec);
// Signature signature = Signature.getInstance(SIGNATURE_ALGORITHM);
// signature.initVerify(publicK);
// signature.update(data);
// return signature.verify(Base64Utils.decode(sign));
// }
/**
* <P>
* 私钥解密
* </p>
*
* @param encryptedData
* 已加密数据
* @param privateKey
* 私钥(BASE64编码)
* @return 解密数据
* @throws Exception
*/
public static String decryptByPrivateKey(String encryptedDataStr, String privateKey) throws Exception {
byte[] encryptedData = Base64Utils.decode(encryptedDataStr);
byte[] decodedData = decryptByPrivateKey(encryptedData, privateKey);
return new String(decodedData, "utf-8");
}
/**
* <P>
* 私钥解密
* </p>
*
* @param encryptedData
* 已加密数据
* @param privateKey
* 私钥(BASE64编码)
* @return
* @throws Exception
*/
public static byte[] decryptByPrivateKey(byte[] encryptedData, String privateKey) throws Exception {
byte[] keyBytes = Base64Utils.decode(privateKey);
PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(keyBytes);
KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
Key privateK = keyFactory.generatePrivate(pkcs8KeySpec);
Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
cipher.init(Cipher.DECRYPT_MODE, privateK);
int inputLen = encryptedData.length;
ByteArrayOutputStream out = new ByteArrayOutputStream();
int offSet = 0;
byte[] cache;
int i = 0;
// 对数据分段解密
while (inputLen - offSet > 0) {
if (inputLen - offSet > MAX_DECRYPT_BLOCK) {
cache = cipher.doFinal(encryptedData, offSet, MAX_DECRYPT_BLOCK);
} else {
cache = cipher.doFinal(encryptedData, offSet, inputLen - offSet);
}
out.write(cache, 0, cache.length);
i++;
offSet = i * MAX_DECRYPT_BLOCK;
}
byte[] decryptedData = out.toByteArray();
out.close();
return decryptedData;
}
/**
* <p>
* 公钥解密
* </p>
*
* @param encryptedData
* 已加密数据
* @param publicKey
* 公钥(BASE64编码)
* @return
* @throws Exception
*/
public static byte[] decryptByPublicKey(byte[] encryptedData, String publicKey) throws Exception {
byte[] keyBytes = Base64Utils.decode(publicKey);
X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(keyBytes);
KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
Key publicK = keyFactory.generatePublic(x509KeySpec);
Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
cipher.init(Cipher.DECRYPT_MODE, publicK);
int inputLen = encryptedData.length;
ByteArrayOutputStream out = new ByteArrayOutputStream();
int offSet = 0;
byte[] cache;
int i = 0;
// 对数据分段解密
while (inputLen - offSet > 0) {
if (inputLen - offSet > MAX_DECRYPT_BLOCK) {
cache = cipher.doFinal(encryptedData, offSet, MAX_DECRYPT_BLOCK);
} else {
cache = cipher.doFinal(encryptedData, offSet, inputLen - offSet);
}
out.write(cache, 0, cache.length);
i++;
offSet = i * MAX_DECRYPT_BLOCK;
}
byte[] decryptedData = out.toByteArray();
out.close();
return decryptedData;
}
/**
* <p>
* 公钥解密
* </p>
*
* @param encryptedDataStr
* 已加密数据
* @param publicKey
* 公钥(BASE64编码)
* @return
* @throws Exception
*/
public static String decryptByPublicKey(String encryptedDataStr, String publicKey) throws Exception {
if(StringUtils.isBlank(encryptedDataStr)){
return new String("");
}
byte[] encryptedData = Base64Utils.decode(encryptedDataStr);
byte[] decodedData = decryptByPublicKey(encryptedData, publicKey);
return new String(decodedData, "utf-8");
}
/**
* <p>
* 公钥加密
* </p>
*
* @param source
* 源数据
* @param publicKey
* 公钥(BASE64编码)
* @return 加密数据
* @throws Exception
*/
public static String encryptByPublicKey(String source, String publicKey) throws Exception {
byte[] data = source.getBytes("UTF-8");
byte[] encryptData = encryptByPublicKey(data, publicKey);
return Base64Utils.encode(encryptData);
}
/**
* <p>
* 公钥加密
* </p>
*
* @param data
* 源数据
* @param publicKey
* 公钥(BASE64编码)
* @return
* @throws Exception
*/
public static byte[] encryptByPublicKey(byte[] data, String publicKey) throws Exception {
byte[] keyBytes = Base64Utils.decode(publicKey);
X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(keyBytes);
KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
Key publicK = keyFactory.generatePublic(x509KeySpec);
// 对数据加密
Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
cipher.init(Cipher.ENCRYPT_MODE, publicK);
int inputLen = data.length;
ByteArrayOutputStream out = new ByteArrayOutputStream();
int offSet = 0;
byte[] cache;
int i = 0;
// 对数据分段加密
while (inputLen - offSet > 0) {
if (inputLen - offSet > MAX_ENCRYPT_BLOCK) {
cache = cipher.doFinal(data, offSet, MAX_ENCRYPT_BLOCK);
} else {
cache = cipher.doFinal(data, offSet, inputLen - offSet);
}
out.write(cache, 0, cache.length);
i++;
offSet = i * MAX_ENCRYPT_BLOCK;
}
byte[] encryptedData = out.toByteArray();
out.close();
return encryptedData;
}
/**
* <p>
* 私钥加密
* </p>
*
* @param data
* 源数据
* @param privateKey
* 私钥(BASE64编码)
* @return
* @throws Exception
*/
public static byte[] encryptByPrivateKey(byte[] data, String privateKey) throws Exception {
byte[] keyBytes = Base64Utils.decode(privateKey);
PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(keyBytes);
KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
Key privateK = keyFactory.generatePrivate(pkcs8KeySpec);
Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
cipher.init(Cipher.ENCRYPT_MODE, privateK);
int inputLen = data.length;
ByteArrayOutputStream out = new ByteArrayOutputStream();
int offSet = 0;
byte[] cache;
int i = 0;
// 对数据分段加密
while (inputLen - offSet > 0) {
if (inputLen - offSet > MAX_ENCRYPT_BLOCK) {
cache = cipher.doFinal(data, offSet, MAX_ENCRYPT_BLOCK);
} else {
cache = cipher.doFinal(data, offSet, inputLen - offSet);
}
out.write(cache, 0, cache.length);
i++;
offSet = i * MAX_ENCRYPT_BLOCK;
}
byte[] encryptedData = out.toByteArray();
out.close();
return encryptedData;
}
/**
* <p>
* 私钥加密
* </p>
*
* @param source
* 源数据
* @param privateKey
* 私钥(BASE64编码)
* @return 加密数据
* @throws Exception
*/
public static String encryptByPrivateKey(String source, String privateKey) throws Exception {
byte[] data = source.getBytes("UTF-8");
byte[] encryptData = encryptByPrivateKey(data, privateKey);
return Base64Utils.encode(encryptData);
}
/**
* <p>
* 获取私钥
* </p>
*
* @param keyMap
* 密钥对
* @return
* @throws Exception
*/
public static String getPrivateKey(Map<String, Object> keyMap) throws Exception {
Key key = (Key) keyMap.get(PRIVATE_KEY);
return Base64Utils.encode(key.getEncoded());
}
/**
* <p>
* 获取公钥
* </p>
*
* @param keyMap
* 密钥对
* @return
* @throws Exception
*/
public static String getPublicKey(Map<String, Object> keyMap) throws Exception {
Key key = (Key) keyMap.get(PUBLIC_KEY);
return Base64Utils.encode(key.getEncoded());
}
public static void main(String[] args) throws Exception {
Map<String, Object> stringObjectMap = genKeyPair();
// keyMap.put(PUBLIC_KEY, publicKey);
// keyMap.put(PRIVATE_KEY, privateKey);
try {
//Map<String, Object> v = genKeyPair();
String publicKey = "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dTjEOr8frm3n3XFwYASyvMvlO1nxuA7yz6uI" +
"3jb38PDVWq5ncXA=";
System.out.println(publicKey);
System.out.println(privateKey);
String s = RSAUtils.encryptByPublicKey("{\"time\":,\"userId\":\"3a02ec335000433cadb216cb8f495b14\"}",publicKey);
System.out.println(s);
String data=RSAUtils.decryptByPrivateKey(s, privateKey);
System.out.println(data);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
原文链接:https://www.cnblogs.com/skysx/p/11945349.html
如有疑问请与原作者联系
标签:
版权申明:本站文章部分自网络,如有侵权,请联系:west999com@outlook.com
特别注意:本站所有转载文章言论不代表本站观点,本站所提供的摄影照片,插画,设计作品,如需使用,请与原作者联系,版权归原作者所有
上一篇:JavaBean动态添加删除属性
下一篇:面向对象的七大设计原则
- 国外程序员整理的Java资源大全(全部是干货) 2020-06-12
- 2020年深圳中国平安各部门Java中级面试真题合集(附答案) 2020-06-11
- 2020年java就业前景 2020-06-11
- 04.Java基础语法 2020-06-11
- Java--反射(框架设计的灵魂)案例 2020-06-11
IDC资讯: 主机资讯 注册资讯 托管资讯 vps资讯 网站建设
网站运营: 建站经验 策划盈利 搜索优化 网站推广 免费资源
网络编程: Asp.Net编程 Asp编程 Php编程 Xml编程 Access Mssql Mysql 其它
服务器技术: Web服务器 Ftp服务器 Mail服务器 Dns服务器 安全防护
软件技巧: 其它软件 Word Excel Powerpoint Ghost Vista QQ空间 QQ FlashGet 迅雷
网页制作: FrontPages Dreamweaver Javascript css photoshop fireworks Flash