网页前端JS与后台数据RSA加密传输


前段时间介绍了安卓与后台RSA加密传输,后来朋友给我send一份邮件,希望整合一套与网站数据加密传输方案,后来小哈跟那位热心朋友利用原有的RSA加密工具以及网上的资源进行调试,功夫不负有心人,终于做出点成绩。现在给大家一起分享。

1)导入JAR包

bcprov-jdk15-140.jar 提取码:4o1p 基于java1.5 的加密算法实现

2)添加工具类

后台导入RsaUtilJS.java工具类。网页前端引用RsaUtil.js插件。

下载工具类插件专机✈

3)生成秘钥对

接下来开始应用于网页前端与后台加密交互。首先后台生成秘钥接口提供前端获取

/**
* 生成密钥对保存在回话中,并返回公钥
*/
@RequestMapping(value = "/getPublicKey", method = RequestMethod.POST, produces = "text/html;charset=UTF-8")
public @ResponseBody String getPublicKey(HttpServletRequest request, HttpServletResponse response) {
    
    
	// 得到秘钥
	HashMap<String, Object> kp = RsaUtilJS.getDefaultPublicKey();
	if(kp == null){
    
    
		return "ERROR";
	}
	// 保存到session(或者保存数据库)
	request.getSession(true).setAttribute("myKeyPair", kp);
	// 返回前端Map对象
	Map<String, Object> rsaMap = new HashMap<String, Object>();
	// 得到公钥
	RSAPublicKey publicKey = (RSAPublicKey) kp.get("publicKey");
	// 模
	rsaMap.put("modulus", new String(Hex.encodeHex(publicKey.getModulus().toByteArray())));
	// 公钥指数
	rsaMap.put("publicExponent", new String(Hex.encodeHex(publicKey.getPublicExponent().toByteArray())));
	// 获取当前sessionID
	rsaMap.put("sessionID", request.getSession().getId());
	return JSON.toJSONString(rsaMap, SerializerFeature.WriteMapNullValue);
}
5)网页前端加密

网页获取到公钥指数后将数据进行加密,然后传输给后台。

// 获取公钥、模请求
var modulus = "模", exponent = "公钥指数", sessionId= "sessionId";
$.ajax({
    
    
    url: '/item/home/getPublicKey',
    type: 'post',
    dataType: 'json',
    async : false
})
.done(function(result) {
    
    
	// console.log(result)
    // 获取公钥、模
    modulus = result.modulus;
    exponent = result.publicExponent;
    sessionId = result.sessionId;
	
	// 提交数据到后台
	$("#btn_submit").on('click', function(event) {
    
    
		var map = {
    
    
               "userAccount": $("#loginNum").val(),
               "userPwd": $("#loginPwd").val()
           };
        // 加密得到密文传输给后台
        var ciphertext = RSAUtils.createCiphertext(map,exponent,modulus);
        $.ajax({
    
    
            url: '/item/home/login',
            data:{
    
    "ciphertext":ciphertext,"sessionId":sessionId},
            type:"post",
            async: false,
            success: function(result){
    
    
            	console.log($.parseJSON(result));
            }
         });
    });
});
6)后台解密
/**
* 后台登录
*/
@RequestMapping(value = "/login", method = RequestMethod.POST, produces = "text/html;charset=UTF-8")
public @ResponseBody String login(HttpServletRequest request, HttpServletResponse response) {
    
    
	String ciphertext = request.getParameter("ciphertext");		// 密文
	String sessionId = request.getParameter("sessionId");		
	// 获取密钥对
	HttpSession session = MySessionContext.getSession(sessionId);
	HashMap<String, Object> kp = (HashMap<String, Object>) session.getAttribute("myKeyPair");
	// 获取私钥
	RSAPrivateKey privateKey = (RSAPrivateKey) kp.get("privateKey");
	// 解密
	JSONObject data = RsaUtilJS.decrypt(privateKey, ciphertext);
	if(data.isNull("userAccount") || data.isNull("userPwd")){
    
    
		return "ERROR";
	}
	// 获取前端的参数
	String userAccount = data.getString("userAccount");
	String userPwd = data.getString("userPwd");
	/** 登录操作.... */
	// 销毁session
	session.invalidate();
}

此文介绍每次访问获取新的秘钥对保存到Session中。您也可以生成一对固定的秘钥对,把私钥、模保存到后台,公钥、模保存在前端,需要时直接取出使用。另外,做IOS的朋友可以嵌套JS插件进行RSA加密!

赠人玫瑰手留余香,若对您有帮助,来 点个赞呗!

猜你喜欢

转载自blog.csdn.net/ii950606/article/details/100577026