欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

用户名密码加密传输

程序员文章站 2024-01-09 19:08:34
...

前言

最近修改一个项目,需要将用户名密码加密传输,记录一下做法,用到js的JSEncrypt,Java的bcprov-jdk15on。

具体步骤

  1. 添加maven依赖,下载jsencrypt.min.js文件并在登录页添加该js文件
	<dependency>
	    <groupId>org.bouncycastle</groupId>
	    <artifactId>bcprov-jdk15on</artifactId>
	    <version>1.60</version>
	</dependency>
<script src="plugins/jsencrypt/jsencrypt.min.js"></script>
  1. 点击登录按钮js方法
function login() {
	$.ajax({
		url: ctx+"sys/beforeLogin",
       	type: "post",
       	dataType: "text",
       	success: function(data) {
       		var publicKey = '';
       		if(data) {
       			publicKey = data;
       		}
  			if(publicKey==null){
   				$("#msg").html("获取publicKey失败,请联系管理员!");
   			}else{
            	var encrypt = new JSEncrypt();
	            encrypt.setPublicKey(publicKey);
   	                	
   				$.ajax({
   	                url: ctx+"sys/login",
   	                type: "post",
   	                data: {
   	                	username:encrypt.encrypt($.trim($("#username").val())),     	 
   	                	password:encrypt.encrypt($.trim($("#password").val())),      	                	
   	                	code:encrypt.encrypt($.trim($("#code").val()))
   	                },
   	                success: function (item) {
   	                    if (item.code == 200) {
   	                        window.location = ctx;
   	                    } else {
   	                    	...
   	                    }
   	                }
   	            });
   			}
    	}
	});
}
  1. 登录前获取加密字符串的java代码
  	/**
     * 登录前生成公钥,用于加密
     * @return  
     * @throws Exception
     */
    @PostMapping("sys/beforeLogin")
    @ResponseBody
    public String Rdspwd(HttpServletRequest req, HttpServletResponse resp) throws Exception{
        String publicKey = RSAUtils.generateBase64PublicKey();
        return publicKey;
    }
  1. 加密工具类RSAUtils
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.PrivateKey;
import java.security.Provider;
import java.security.PublicKey;
import java.security.SecureRandom;
import java.security.Security;
import java.security.interfaces.RSAPublicKey;

import javax.crypto.Cipher;

import org.apache.commons.codec.binary.Base64;

public class RSAUtils {
	
	
	 //KeyPair is a simple holder for a key pair.
   private static final KeyPair keyPair = initKey();
   /**
    * 初始化方法,产生key pair,提供provider和random
    * @return KeyPair instance
    */
   private static KeyPair initKey() {

       try {
           //添加provider
           Provider provider = new org.bouncycastle.jce.provider.BouncyCastleProvider();
           Security.addProvider(provider);
           //产生用于安全加密的随机数
           SecureRandom random = new SecureRandom();

           KeyPairGenerator generator = KeyPairGenerator.getInstance("RSA", provider);
           generator.initialize(1024, random); 
           return generator.generateKeyPair();
       } catch(Exception e) {
           throw new RuntimeException(e);
       }
   }
   /**
    * 产生public key
    * @return public key字符串
    */
   public static String generateBase64PublicKey() {
       PublicKey publicKey = (RSAPublicKey)keyPair.getPublic();

       //encodeBase64(): Encodes binary data using the base64 
       //algorithm but does not chunk the output.
       //getEncoded():返回key的原始编码形式
       return new String(Base64.encodeBase64(publicKey.getEncoded()));
   }
   /**
    * 解密数据
    * @param string 需要解密的字符串
    * @return  **之后的字符串
    */
   public static String decryptBase64(String string) {
       //decodeBase64():将Base64数据解码为"八位字节”数据
       return new String(decrypt(Base64.decodeBase64(string.getBytes())));
   }

   private static byte[] decrypt(byte[] byteArray) {
       try {
           Provider provider = new org.bouncycastle.jce.provider.BouncyCastleProvider();
           Security.addProvider(provider);
           //Cipher: 提供加密和解密功能的实例
           //transformation: "algorithm/mode/padding"
           Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding", provider);
           PrivateKey privateKey = keyPair.getPrivate();
           //初始化
           cipher.init(Cipher.DECRYPT_MODE, privateKey);
           //doFinal(): 加密或者解密数据
           byte[] plainText = cipher.doFinal(byteArray);
           return plainText;
       } catch(Exception e) {
           throw new RuntimeException(e);
       }
   }

}
  1. 登录解密用户名密码Java代码
	//解密帐号
   	username = RSAUtils.decryptBase64(username);
   	//解密密码
   	password = RSAUtils.decryptBase64(password);
   	//解密验证码
   	code = RSAUtils.decryptBase64(code);

后记

整个流程就是,登录前先去后端取一个用来加密的字符串,js用这个字符串加密用户名密码,然后走登录方法传递用户名密码,后端获取用户名密码后解密和数据库对比。