前台使用RSA非对称安全加密用户信息

首先简单明确一下对称加密和非对称加密之间的区别:
对称加密:即加密解密使用的是同一个密钥;
非对称加密:即生成两个密钥,加密时使用公钥,解密是使用的私钥;

说明:本次实践的加密操作主要生成以下三个关键对象
1.加密模块
2.加密公钥
3.加密私钥

思路:公钥的作用是加密指定字符串;私钥则是解密指定字符串;每次前台发送http请求至后台都将新生成加密模块、加密公钥、加密私钥,而公钥和加密模块则会送到前台对数据进行加密;私钥则保留在后台等待。当前台使用公钥加密过后,将数据传输到后台,再使用保留的私钥进行解密。
注意: 每次生成的 加密模块、加密公钥、加密私钥 都是组合产生的,非同一次产生的,将会包解密失败的错误!

下面我对于前台后台所有的加解密的情况做汇总,根据实际开发情况做灵活变通:

工具类:新建工具类,用于数据转换

public class HexUtil {
    
    
	 
    /**
     * 二进制byte数组转十六进制byte数组
     * byte array to hex
     *
     * @param b byte array
     * @return hex string
     */
    public static String byte2hex(byte[] b) {
    
    
        StringBuilder hs = new StringBuilder();
        String stmp;
        for (int i = 0; i < b.length; i++) {
    
    
            stmp = Integer.toHexString(b[i] & 0xFF).toUpperCase();
            if (stmp.length() == 1) {
    
    
                hs.append("0").append(stmp);
            } else {
    
    
                hs.append(stmp);
            }
        }
        return hs.toString();
    }
 
    /**
     * 十六进制byte数组转二进制byte数组
     * hex to byte array
     *
     * @param hex hex string
     * @return byte array
     */
    public static byte[] hex2byte(String hex)
             throws IllegalArgumentException{
    
    
        if (hex.length() % 2 != 0) {
    
    
            throw new IllegalArgumentException ("invalid hex string");
        }
        char[] arr = hex.toCharArray();
        byte[] b = new byte[hex.length() / 2];
        for (int i = 0, j = 0, l = hex.length(); i < l; i++, j++) {
    
    
            String swap = "" + arr[i++] + arr[i];
            int byteint = Integer.parseInt(swap, 16) & 0xFF;
            b[j] = new Integer(byteint).byteValue();
        }
        return b;
    }
    
 
	 public static String bytesToHexString(byte[] src){
    
    
	        StringBuilder stringBuilder = new StringBuilder("");
	        if (src == null || src.length <= 0) {
    
    
	            return null;
	        }
	        for (int i = 0; i < src.length; i++) {
    
    
	            int v = src[i] & 0xFF;
	            String hv = Integer.toHexString(v);
	            if (hv.length() < 2) {
    
    
	                stringBuilder.append(0);
	            }
	            stringBuilder.append(hv);
	        }
	        return stringBuilder.toString();
	    }
	 private static byte charToByte(char c) {
    
      
		    return (byte) "0123456789ABCDEF".indexOf(c);  
		}
	 public static byte[] hexStringToBytes(String hexString) {
    
      
		    if (hexString == null || hexString.equals("")) {
    
      
		        return null;  
		    }  
		    hexString = hexString.toUpperCase();  
		    int length = hexString.length() / 2;  
		    char[] hexChars = hexString.toCharArray();  
		    byte[] d = new byte[length];  
		    for (int i = 0; i < length; i++) {
    
      
		        int pos = i * 2;  
		        d[i] = (byte) (charToByte(hexChars[pos]) << 4 | charToByte(hexChars[pos + 1]));  
		    }  
		    return d;  
		}  
	   
}

核心:RSA加密类

import java.io.ByteArrayOutputStream;  
import java.io.FileInputStream;  
import java.io.FileOutputStream;  
import java.io.ObjectInputStream;  
import java.io.ObjectOutputStream;  
import java.math.BigInteger;  
import java.security.KeyFactory;  
import java.security.KeyPair;  
import java.security.KeyPairGenerator;  
import java.security.NoSuchAlgorithmException;  
import java.security.PrivateKey;  
import java.security.PublicKey;  
import java.security.SecureRandom;  
import java.security.interfaces.RSAPrivateKey;  
import java.security.interfaces.RSAPublicKey;  
import java.security.spec.InvalidKeySpecException;  
import java.security.spec.RSAPrivateKeySpec;  
import java.security.spec.RSAPublicKeySpec;
import java.util.HashMap;
import java.util.Map;

import javax.crypto.Cipher;  
  
/** 
 * RSA 工具类。提供加密,解密,生成密钥对等方法。 
 * 需要到	下载bcprov-jdk14-123.jar。 
 *  
 */  
 
 
 
public class RSAUtils {
    
    
    private static final int MAX_ENCRYPT_BLOCK = 117; // RSA最大加密明文大小
    private static final int MAX_DECRYPT_BLOCK = 128; // RSA最大解密密文大小
 
    /**
     * 生成公钥和私钥
     *
     * @throws NoSuchAlgorithmException
     */
    public static KeyPair genRSAKeyPair() throws NoSuchAlgorithmException {
    
    
        KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance("RSA");
        keyPairGen.initialize(1024);
        return keyPairGen.generateKeyPair();
    }
 
    /**
     * 使用模和指数生成RSA公钥
     * 注意:【此代码用了默认补位方式,为RSA/None/PKCS1Padding,不同JDK默认的补位方式可能不同,如Android默认是RSA
     * /None/NoPadding】
     *
     * @param modulus  模
     * @param exponent 指数
     * @return
     */
    public static RSAPublicKey getPublicKey(String modulus, String exponent) {
    
    
        try {
    
    
            BigInteger b1 = new BigInteger(modulus, 16);
            BigInteger b2 = new BigInteger(exponent, 16);
            KeyFactory keyFactory = KeyFactory.getInstance("RSA");
            RSAPublicKeySpec keySpec = new RSAPublicKeySpec(b1, b2);
            return (RSAPublicKey) keyFactory.generatePublic(keySpec);
        } catch (Exception e) {
    
    
            e.printStackTrace();
            return null;
        }
    }
 
    /**
     * 使用模和指数生成RSA私钥
     * 注意:【此代码用了默认补位方式,为RSA/None/PKCS1Padding,不同JDK默认的补位方式可能不同,如Android默认是RSA
     * /None/NoPadding】
     *
     * @param modulus  模
     * @param exponent 指数
     * @return
     */
    public static RSAPrivateKey getPrivateKey(String modulus, String exponent) {
    
    
        try {
    
    
            BigInteger b1 = new BigInteger(modulus, 16);
            BigInteger b2 = new BigInteger(exponent, 16);
            KeyFactory keyFactory = KeyFactory.getInstance("RSA");
            RSAPrivateKeySpec keySpec = new RSAPrivateKeySpec(b1, b2);
            return (RSAPrivateKey) keyFactory.generatePrivate(keySpec);
        } catch (Exception e) {
    
    
            e.printStackTrace();
            return null;
        }
    }
 
    /**
     * 公钥加密
     */
    public static byte[] encryptByPublicKey(byte[] data, RSAPublicKey publicKey) throws Exception {
    
    
        Cipher cipher = Cipher.getInstance("RSA");
        cipher.init(Cipher.ENCRYPT_MODE, publicKey);
        int inputLen = data.length;
 
        try (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;
            }
            return out.toByteArray();
        }
    }
 
    /**
     * 私钥解密
     */
    public static String decryptByPrivateKey(byte[] encryptedData, RSAPrivateKey privateKey) throws Exception {
    
    
        Cipher cipher = Cipher.getInstance("RSA");
        cipher.init(Cipher.DECRYPT_MODE, privateKey);
        int inputLen = encryptedData.length;
 
        try (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;
            }
            
            return new String(out.toByteArray(), "utf-8");
        }
    }
 
    /**
     * ASCII码转BCD码
     */
    public static byte[] ASCII_To_BCD(byte[] ascii, int asc_len) {
    
    
        byte[] bcd = new byte[asc_len / 2];
        int j = 0;
        for (int i = 0; i < (asc_len + 1) / 2; i++) {
    
    
            bcd[i] = asc_to_bcd(ascii[j++]);
            bcd[i] = (byte) (((j >= asc_len) ? 0x00 : asc_to_bcd(ascii[j++])) + (bcd[i] << 4));
        }
        return bcd;
    }
 
    public static byte asc_to_bcd(byte asc) {
    
    
        byte bcd;
 
        if ((asc >= '0') && (asc <= '9'))
            bcd = (byte) (asc - '0');
        else if ((asc >= 'A') && (asc <= 'F'))
            bcd = (byte) (asc - 'A' + 10);
        else if ((asc >= 'a') && (asc <= 'f'))
            bcd = (byte) (asc - 'a' + 10);
        else
            bcd = (byte) (asc - 48);
        return bcd;
    }
 
    /**
     * BCD转字符串
     */
    public static String bcd2Str(byte[] bytes) {
    
    
        char temp[] = new char[bytes.length * 2], val;
 
        for (int i = 0; i < bytes.length; i++) {
    
    
            val = (char) (((bytes[i] & 0xf0) >> 4) & 0x0f);
            temp[i * 2] = (char) (val > 9 ? val + 'A' - 10 : val + '0');
 
            val = (char) (bytes[i] & 0x0f);
            temp[i * 2 + 1] = (char) (val > 9 ? val + 'A' - 10 : val + '0');
        }
        return new String(temp);
    }
 
    /**
     * 拆分字符串
     */
    public static String[] splitString(String string, int len) {
    
    
        int x = string.length() / len;
        int y = string.length() % len;
        int z = 0;
        if (y != 0) {
    
    
            z = 1;
        }
        String[] strings = new String[x + z];
        String str = "";
        for (int i = 0; i < x + z; i++) {
    
    
            if (i == x + z - 1 && y != 0) {
    
    
                str = string.substring(i * len, i * len + y);
            } else {
    
    
                str = string.substring(i * len, i * len + len);
            }
            strings[i] = str;
        }
        return strings;
    }
 
    /**
     * 拆分数组
     */
    public static byte[][] splitArray(byte[] data, int len) {
    
    
        int x = data.length / len;
        int y = data.length % len;
        int z = 0;
        if (y != 0) {
    
    
            z = 1;
        }
        byte[][] arrays = new byte[x + z][];
        byte[] arr;
        for (int i = 0; i < x + z; i++) {
    
    
            arr = new byte[len];
            if (i == x + z - 1 && y != 0) {
    
    
                System.arraycopy(data, i * len, arr, 0, y);
            } else {
    
    
                System.arraycopy(data, i * len, arr, 0, len);
            }
            arrays[i] = arr;
        }
        return arrays;
    }
    //String 解密
 public static String Decrypt(String str,String mou,String m) throws Exception{
    
    
     //模hex
     String modulus =mou;
     //私钥指数hex
     String private_exponent = m;

     RSAPrivateKey priKey = getPrivateKey(modulus, private_exponent);
     
     return decryptByPrivateKey(HexUtil.hexStringToBytes(str), priKey);
 }
 //获取模块信息
 public static Map getModulus () throws NoSuchAlgorithmException{
    
    
	 KeyPair keyPair = genRSAKeyPair();
	 Map map = new HashMap();
     //生成公钥和私钥
     RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();
     RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();
     //模hex
     String modulus = publicKey.getModulus().toString(16);
     //公钥指数hex
     String public_exponent = publicKey.getPublicExponent().toString(16);
     //私钥指数hex
     String private_exponent = privateKey.getPrivateExponent().toString(16);
     map.put("g", public_exponent);
     map.put("m", private_exponent);
     map.put("modu", modulus);
    return map;
 }
    public static void main(String[] args) throws Exception {
    
    
        KeyPair keyPair = genRSAKeyPair();

        //生成公钥和私钥
        RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();
        RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();
 
 
        //模hex
        String modulus = publicKey.getModulus().toString(16);
        //公钥指数hex
        String public_exponent = publicKey.getPublicExponent().toString(16);
        //私钥指数hex
        String private_exponent = privateKey.getPrivateExponent().toString(16);
 
        System.out.println("public_modulus: " + modulus);
        System.out.println("public_exponent: " + public_exponent);
        System.out.println("private_exponent: " + private_exponent);
 
        //明文
        String plaintStr = "123456";
        System.out.println("plaintStr: " + plaintStr);
 
        //使用模和指数生成公钥和私钥
        RSAPublicKey pubKey = getPublicKey(modulus, public_exponent);
        RSAPrivateKey priKey = getPrivateKey(modulus, private_exponent);
        //公钥加密后的密文
        byte[] encryptStr = encryptByPublicKey(plaintStr.getBytes("utf-8"), pubKey);
        System.out.println("encryptStr: " + HexUtil.bytesToHexString(encryptStr));
        String jmh = HexUtil.bytesToHexString(encryptStr);
        System.out.println("start");
        //私钥解密后的明文
        System.out.println("decryptStr: " + decryptByPrivateKey(HexUtil.hexStringToBytes(jmh), priKey));
    }
 
} 

业务逻辑类1

//声明加密秘钥
	private static String m;
//声明加密模块
	private static String mou;
//2
//调用RSA工具类的getModulus方法获取配套的公钥,秘钥,和加密模块信息,并将公钥和加密模块传送到前台,秘钥和加密模块
//保存到后台
	@ResponseBody
	@RequestMapping(value = "/getMoudle", method = RequestMethod.POST)
	public Object getMoudle() throws NoSuchAlgorithmException {
    
    
		Map jmInfo = RSAUtils.getModulus();
		String my = jmInfo.getString("m");
		m = my;
		mou = jmInfo.getString("modu");
		return jmInfo;
	}

JS页面发送请求

//1
//映入js包
   <script language="JavaScript" type="text/javascript" src="http://www-cs-students.stanford.edu/~tjw/jsbn/jsbn.js"></script>
    <script language="JavaScript" type="text/javascript" src="http://www-cs-students.stanford.edu/~tjw/jsbn/jsbn2.js"></script>
    <script language="JavaScript" type="text/javascript" src="http://www-cs-students.stanford.edu/~tjw/jsbn/prng4.js"></script>
    <script language="JavaScript" type="text/javascript" src="http://www-cs-students.stanford.edu/~tjw/jsbn/rng.js"></script>
    <script language="JavaScript" type="text/javascript" src="http://www-cs-students.stanford.edu/~tjw/jsbn/rsa.js"></script>
    <script language="JavaScript" type="text/javascript" src="http://www-cs-students.stanford.edu/~tjw/jsbn/rsa2.js"></script>
//2声明加密对象
	var RSADo = {
    
    
    "modulus":"",
    "publicExponent":""}
//3获取加密信息
$(function() {
    
    
	$("#denglu").bind("click", function() {
    
    
			$.ajax("/..../....",{
    
    
				data :{
    
    
				},
				dataType: 'json', //服务器返回json格式数据
		        async: false,
		        type: 'post', //HTTP请求类型
		        timeout: 10000, //超时时间设置为10秒;
		        success: function (data) {
    
    
		            RSADo.modulus = data.modu;
		            RSADo.publicExponent = data.g;
		            //privateKey = data.m;
		            var userName = $("#userName").val();
					var possWord = $("#iptPwd").val();

					//使用获取到的公钥加密
					var rsa = new RSAKey();
					rsa.setPublic(RSADo.modulus, RSADo.publicExponent);
					var Name = rsa.encrypt(userName);
					var pwd = rsa.encrypt(possWord);
					console.log('加密后(name):', Name);
					console.log('加密后(pwd):', pwd);
					//私钥解密
					//通常不会在前台拿到私钥并解密,只是把这个情况罗列出来
				    //rsa.setPrivate(RSADo.modulus, RSADo.publicExponent, privateKey)
				    //var decryptStr = rsa.decrypt(encryptStr)
				    //console.log('解密私钥:', privateKey)
				    //console.log('解密后(decrypt)', decryptStr)
					
					//当前账号密码设置为RSA加密后的状态,否则依旧会将明文暴露出来
					$('#userName').val(Name);
					$('#iptPwd').val(pwd);
					//执行提交功能,再次进入后台
					$('#form').submit();
		            
		        },
		        error: function (xhr, type, errorThrown) {
    
    
		        }
			});
 });

//声明公钥加密方法
    function encryption(str){
    
    
        // 实例化js的RSA对象生成
        var rsa = new RSAKey()
        rsa.setPublic(RSADo.modulus, RSADo.publicExponent)
        var encryptStr = rsa.encrypt(str);
        return encryptStr;
    }

部分相对久远的框架,可能直接把业务逻辑类放在加密类中一并执行
注意这个声明的静态属性,用于存放密钥和加密模块
部分框架请求针对前台请求不能单纯的抛出异常而是捕获异常,以及返回类型需要封装成json串返回才不会出错,奇奇怪怪的问题不少

//声明加密秘钥
	private static String m;
//声明加密模块
	private static String mou;
 @Action
	 public String getModule() {
    
    
		
		Map jmInfo = new HashMap();
		try {
    
    
			jmInfo = MainPage.getModulus();
			String my = jmInfo.get("m").toString();
			m = my;
			mou = jmInfo.get("modu").toString();
		} catch (NoSuchAlgorithmException e) {
    
    
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		JSONObject json = new JSONObject();
		json.putAll(jmInfo);
		return json.toString();
	}

对应上面的main方法全部情况的汇总,再做一个简化

 public static void main(String[] args) throws Exception {
    
    
 HttpServletRequest req = ActionContext.getActionContext().getHttpServletRequest();
		HttpServletResponse resp = ActionContext.getActionContext().getHttpServletResponse();
		String userName = req.getParameter(System.getProperty(用户名));
		String possWord = req.getParameter(System.getProperty(密码));
		//做个账号、密码的非空判断
		if(!StringUtility.isNullOrEmpty(userName) && !StringUtility.isNullOrEmpty(possWord)) {
    
    
			
		 //通常情况下,我们已经不需要再进行二次getMoudles()方法来建立密钥了
		 //应该直接应用上面存储的静态属性(私钥--m,加密模块--mou)
		 //否则将会出现解密失败的错误,因为再次创建就是两套密钥了
		 	        
	      //使用模和指数生成私钥
          RSAPrivateKey priKey = getPrivateKey(mou, m);
	      System.out.println("开始解密");
	        //私钥解密后的明文
	        System.out.println("decryptName: " + decryptByPrivateKey(HexUtil.hexStringToBytes(Name), priKey));
	        System.out.println("decryptPwd: " + decryptByPrivateKey(HexUtil.hexStringToBytes(Pwd), priKey));
	        String decryptName = decryptByPrivateKey(HexUtil.hexStringToBytes(userName), priKey);
	        String decryptPwd = decryptByPrivateKey(HexUtil.hexStringToBytes(possWord), priKey);
	        
	        //之后拿着解密的账号密码,该验证验证,通过则登录就可以了
	        
	        }
 }

这篇总结的比较细,主要明确生产一套密钥,那就在这一套密钥内进行加解密操作就可以了,若在再懵懵叨叨的在主程序里面new一套密钥,那绝对无法匹配的。
当然大部分情况都是前台请求获取加密模块和公钥,而私钥和加密模块则保存在定义的静态属性中;在登录的时候将数据传到后台进行确认,直接调用该静态属性解密即可;文章总结了所有情况的加解密也是为了情况的多样性,以防不时之需~

猜你喜欢

转载自blog.csdn.net/chwensrong/article/details/119674347
今日推荐