RSA加解密——前端js加密,后台解密

一、前端js

    1、前端js

          先引入 jsencrypt.js

           

          页面放置一个隐藏的input标签,用于存放公钥

          js进行加密,$("#pwd").val()为加密前的密码,ps为加密后的密码

var encrypt = new JSEncrypt();
encrypt.setPublicKey($("#publicKeyString").val());
var d=encrypt.encrypt($("#pwd").val());
var ps= encodeURI(d).replace(/\+/g, '%2B');

二、后台

         后台进行解密(我的公钥秘钥用了固定的一组,存放在文件中,可以用不同的公钥秘钥)

//对密码进行解密
password = password.replaceAll("%2B","+");
//获取私钥
String path = this.getClass().getResource("/LoginRsaKey/privateKey.txt").getFile();
		
String privateKey = ToStringUtils.readTxt(path);
byte[] decryptByPrivateKey = RSAUtils_user.decryptByPrivateKey(Base64Utils.decode(password), privateKey);
		
//解密后的密码
String decodePassword = new String(decryptByPrivateKey);

公钥秘钥存放位置:

RSA加解密——前端js加密,后台解密_第1张图片

三、公钥秘钥生成:

Map keyMap=RSAUtils.genKeyPair();
    	
String publicKey = RSAUtils.getPublicKey(keyMap);  
String privateKey = RSAUtils.getPrivateKey(keyMap);

 

四、相关的工具类:

ToStringUtils.java

package com.synjones.gatewayManage.utils;

import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.ObjectOutputStream;
import java.util.Calendar;
import java.util.Random;

public class ToStringUtils {
	
	
	
	
	
	
	
	
	public static String getDateFilePrefix() { 
		  
		Calendar calendar = Calendar.getInstance();
        String now_y = String.valueOf(calendar.get(Calendar.YEAR));//得到年份
        String now_m = String.valueOf(calendar.get(Calendar.MONTH)+1);//得到月份
        String now_d = String.valueOf(calendar.get(Calendar.DATE));//得到月份中今天的号数
        String now_h = String.valueOf(calendar.get(Calendar.HOUR_OF_DAY));//得到一天中现在的时间,24小时制
        String now_mm = String.valueOf(calendar.get(Calendar.MINUTE));//得到分钟数
        String now_s = String.valueOf(calendar.get(Calendar.SECOND));//得到秒数
        //String now_ms =String.valueOf( calendar.get(Calendar.MILLISECOND));//得到秒数
        
        
        return now_y + "-" + now_m + "-" + now_d + "-" + now_h + "-" + now_mm + "-" + now_s + "-" ;
        //+ now_ms + "-";
		

	}
	
	   /**
     * 数组转成十六进制字符串
     * @param byte[]
     * @return HexString
     */
    public static String toHexString1(byte[] b){
        StringBuffer buffer = new StringBuffer();
        for (int i = 0; i < b.length; ++i){
            buffer.append(toHexString1(b[i]));
        }
        return buffer.toString();
    }
    public static String toHexString1(byte b){
        String s = Integer.toHexString(b & 0xFF);
        if (s.length() == 1){
            return "0" + s;
        }else{
            return s;
        }
    }
    
    
    
    /**
     * 反转
     * @param s
     * @return
     */
    public static String stringRevToStr(String s) {
		
		String revS = new StringBuffer(s).reverse().toString();
		char[] charArray = revS.toCharArray();
		String val = "";
		for (int i = 0; i < charArray.length; i += 2) {
			char b = charArray[i];
			char c = charArray[i + 1];
			val += c;
			val += b;
		}
		//Integer revStoInt = Integer.valueOf(val);
		
		return val;
	}
    
    
    
    
    /**
	 * 16进制转换成为string类型字符串
	 * @param s
	 * @return
	 */
	public static String hexStringToString(String s) {
	    if (s == null || s.equals("")) {
	        return null;
	    }
	    s = s.replace(" ", "");
	    byte[] baKeyword = new byte[s.length() / 2];
	    for (int i = 0; i < baKeyword.length; i++) {
	        try {
	            baKeyword[i] = (byte) (0xff & Integer.parseInt(s.substring(i * 2, i * 2 + 2), 16));
	        } catch (Exception e) {
	            e.printStackTrace();
	        }
	    }
	    try {
	        s = new String(baKeyword, "UTF-8");
	        new String();
	    } catch (Exception e1) {
	        e1.printStackTrace();
	    }
	    return s;
	}
    
	
	
	/**
     * 对象转Byte数组
     * @param obj
     * @return
     */
    public static byte[] objectToByteArray(Object obj) {
        byte[] bytes = null;
        ByteArrayOutputStream byteArrayOutputStream = null;
        ObjectOutputStream objectOutputStream = null;
        try {
            byteArrayOutputStream = new ByteArrayOutputStream();
            objectOutputStream = new ObjectOutputStream(byteArrayOutputStream);
            objectOutputStream.writeObject(obj);
            objectOutputStream.flush();
            bytes = byteArrayOutputStream.toByteArray();

        } catch (IOException e) {
            System.out.println("objectToByteArray failed, " + e);
        } finally {
            if (objectOutputStream != null) {
                try {
                    objectOutputStream.close();
                } catch (IOException e) {
                    //LOGGER.error("close objectOutputStream failed, " + e);
                    System.out.println("close objectOutputStream failed, " + e);
                }
            }
            if (byteArrayOutputStream != null) {
                try {
                    byteArrayOutputStream.close();
                } catch (IOException e) {
                    //LOGGER.error("close byteArrayOutputStream failed, " + e);
                    System.out.println("close byteArrayOutputStream failed, " + e);
                }
            }

        }
        return bytes;
    }
    
    /**  
     * 对象转数组  
     * @param obj  
     * @return  
     */  
    public static byte[] toByteArray (Object obj) {      
        byte[] bytes = null;      
        ByteArrayOutputStream bos = new ByteArrayOutputStream();      
        try {        
            ObjectOutputStream oos = new ObjectOutputStream(bos);         
            oos.writeObject(obj);        
            oos.flush();         
            bytes = bos.toByteArray ();      
            oos.close();         
            bos.close();        
        } catch (IOException ex) {        
            ex.printStackTrace();   
        }      
        return bytes;    
    }  
    
    
    public static byte[] hexStringToByteArray(String s) {
        int len = s.length();
        byte[] data = new byte[len / 2];
        try {
            for (int i = 0; i < len; i += 2) {
                data[i / 2] = (byte) ((Character.digit(s.charAt(i), 16) << 4)
                        + Character.digit(s.charAt(i+1), 16));
            }
        } catch (Exception e) {
            //Log.d("", "Argument(s) for hexStringToByteArray(String s)"+ "was not a hex string");
        }
        return data;
    }
    
    
  //使用1字节就可以表示b
  	public static String numToHex8(int b) {
  	        return String.format("%02X", b);//2表示需要两个16进行数
  	}
  	//需要使用2字节表示b
  	public static String numToHex16(int b) {
  	        return String.format("%04X", b);
  	}
  	//需要使用4字节表示b
  	public static String numToHex32(int b) {
  	        return String.format("%08X", b);
  	}
  	
  	
  	
  	 public static byte[] toByteArray(short[] src) {

         int count = src.length;
         byte[] dest = new byte[count << 1];
         for (int i = 0; i < count; i++) {
                 dest[i * 2] = (byte) (src[i] >> 8);
                 dest[i * 2 + 1] = (byte) (src[i] >> 0);
         }

         return dest;
         
     }
  	 
  	public static byte[] shortToByteArray(short s) {  
        byte[] targets = new byte[2];  
        for (int i = 0; i < 2; i++) {  
            int offset = (targets.length - 1 - i) * 8;  
            targets[i] = (byte) ((s >>> offset) & 0xff);  
        }  
        return targets;  
    }  
  	
  	/**
  	 * int转byte
  	 * @param value
  	 * @return
  	 */
  	public static byte[] intToBytes( int value )   
	{   
	    byte[] src = new byte[4];  
	    src[3] =  (byte) ((value>>24) & 0xFF);  
	    src[2] =  (byte) ((value>>16) & 0xFF);  
	    src[1] =  (byte) ((value>>8) & 0xFF);    
	    src[0] =  (byte) (value & 0xFF);                  
	    return src;   
	}  
  	
		//byte 转 int
		public static int ByteArrayToInt(byte[] bArr) {  
		         if(bArr.length!=4){  
		             return -1;  
		         }  
		         return (int) ((((bArr[3] & 0xff) << 24)    
		                    | ((bArr[2] & 0xff) << 16)    
		                    | ((bArr[1] & 0xff) << 8)
		| ((bArr[0] & 0xff) << 0)));   
		}
		   /**
		* byte转long
		* @param byteNum
		* @return
		*/
		public static long bytes2Long(byte[] byteNum) {
			long num = 0;
			for (int ix = 0; ix < 8; ++ix) {
				num <<= 8;
				num |= (byteNum[ix] & 0xff);
			}
			return num;
		}
		
		
		/** 
	     * 字节数组到long的转换. 
	     */  
	    public static long byteToLong(byte[] b) {  
	        long s = 0;  
	        long s0 = b[0] & 0xff;// 最低位  
	        long s1 = b[1] & 0xff;  
	        long s2 = b[2] & 0xff;  
	        long s3 = b[3] & 0xff;  
	        long s4 = b[4] & 0xff;// 最低位  
	        long s5 = b[5] & 0xff;  
	        long s6 = b[6] & 0xff;  
	        long s7 = b[7] & 0xff;  
	  
	        // s0不变  
	        s1 <<= 8;  
	        s2 <<= 16;  
	        s3 <<= 24;  
	        s4 <<= 8 * 4;  
	        s5 <<= 8 * 5;  
	        s6 <<= 8 * 6;  
	        s7 <<= 8 * 7;  
	        s = s0 | s1 | s2 | s3 | s4 | s5 | s6 | s7;  
	        return s;  
	    }  
	    /**
	     * 合并数组
	     * @param values
	     * @return
	     */
	    public static byte[] byteMergerAll(byte[]... values) {
	 	    int length_byte = 0;
	 	        for (int i = 0; i < values.length; i++) {
	 	            length_byte += values[i].length;
	 	        }
	 	        byte[] all_byte = new byte[length_byte];
	 	        int countLength = 0;
	 	        for (int i = 0; i < values.length; i++) {
	 	            byte[] b = values[i];
	 	            System.arraycopy(b, 0, all_byte, countLength, b.length);
	 	            countLength += b.length;
	 	        }
	 	        return all_byte;
	 	    }

	    
	    public static String checkByte(byte[] b) {  
	    	String result = "value";
	    	int leng = 0;
			for(int i=0;i= 0)
            {
                jy = tail - head;
            }
            else
            {
                jy = tail - head + 100000;//总流水数100000
            }

            return jy;
        }
	    
	    public static byte[] shortToByte(short number) { 
	        int temp = number; 
	        byte[] b = new byte[2]; 
	        for (int i = 0; i < b.length; i++) { 
	            b[i] = new Integer(temp & 0xff).byteValue();// 将最低位保存在最低位 
	            temp = temp >> 8; // 向右移8位 
	        } 
	        return b; 
	    } 
	 
	 public static short byteToShort(byte[] b) { 
	        short s = 0; 
	        short s0 = (short) (b[0] & 0xff);// 最低位 
	        short s1 = (short) (b[1] & 0xff); 
	        s1 <<= 8; 
	        s = (short) (s0 | s1); 
	        return s; 
	    }
	    
	//去读私钥
    public static String readTxt(String filePath) {
    	String lineTxt = null;
    	  try {
    	    File file = new File(filePath);
    	    if(file.isFile() && file.exists()) {
    	      InputStreamReader isr = new InputStreamReader(new FileInputStream(file), "utf-8");
    	      BufferedReader br = new BufferedReader(isr);
    	      
    	      while ((lineTxt = br.readLine()) != null) {
    	        System.out.println(lineTxt);
    	        return lineTxt;
    	      }
    	      br.close();
    	    } else {
    	      System.out.println("文件不存在!");
    	    }
    	  } catch (Exception e) {
    	    System.out.println("文件读取错误!");
    	  }
		return lineTxt;
    	 
    	} 

}

Base64Utils.java

package com.synjones.gatewayManage.utils;



import java.io.ByteArrayInputStream;  
import java.io.ByteArrayOutputStream;  
import java.io.File;  
import java.io.FileInputStream;  
import java.io.FileOutputStream;  
import java.io.InputStream;  
import java.io.OutputStream;

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



public class Base64Utils {


    /** *//** 
     * 文件读取缓冲区大小 
     */  
    private static final int CACHE_SIZE = 1024;  
      
    /** *//** 
     * 

* BASE64字符串解码为二进制数据 *

* * @param base64 * @return * @throws Exception */ public static byte[] decode(String base64) throws Exception { return Base64.decodeBase64(base64.getBytes()); } /** *//** *

* 二进制数据编码为BASE64字符串 *

* * @param bytes * @return * @throws Exception */ public static String encode(byte[] bytes) throws Exception { return new String(Base64.encodeBase64(bytes)); } /** *//** *

* 将文件编码为BASE64字符串 *

*

* 大文件慎用,可能会导致内存溢出 *

* * @param filePath 文件绝对路径 * @return * @throws Exception */ public static String encodeFile(String filePath) throws Exception { byte[] bytes = fileToByte(filePath); return encode(bytes); } /** *//** *

* BASE64字符串转回文件 *

* * @param filePath 文件绝对路径 * @param base64 编码字符串 * @throws Exception */ public static void decodeToFile(String filePath, String base64) throws Exception { byte[] bytes = decode(base64); byteArrayToFile(bytes, filePath); } /** *//** *

* 文件转换为二进制数组 *

* * @param filePath 文件路径 * @return * @throws Exception */ public static byte[] fileToByte(String filePath) throws Exception { byte[] data = new byte[0]; File file = new File(filePath); if (file.exists()) { FileInputStream in = new FileInputStream(file); ByteArrayOutputStream out = new ByteArrayOutputStream(2048); byte[] cache = new byte[CACHE_SIZE]; int nRead = 0; while ((nRead = in.read(cache)) != -1) { out.write(cache, 0, nRead); out.flush(); } out.close(); in.close(); data = out.toByteArray(); } return data; } /** *//** *

* 二进制数据写文件 *

* * @param bytes 二进制数据 * @param filePath 文件生成目录 */ public static void byteArrayToFile(byte[] bytes, String filePath) throws Exception { InputStream in = new ByteArrayInputStream(bytes); File destFile = new File(filePath); if (!destFile.getParentFile().exists()) { destFile.getParentFile().mkdirs(); } destFile.createNewFile(); OutputStream out = new FileOutputStream(destFile); byte[] cache = new byte[CACHE_SIZE]; int nRead = 0; while ((nRead = in.read(cache)) != -1) { out.write(cache, 0, nRead); out.flush(); } out.close(); in.close(); } }

RSAUtils_user.java

package com.synjones.gatewayManage.utils;

import java.io.ByteArrayOutputStream;  
import java.security.Key;  
import java.security.KeyFactory;  
import java.security.KeyPair;  
import java.security.KeyPairGenerator;  
import java.security.PrivateKey;  
import java.security.PublicKey;  
import java.security.Signature;  
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; 


public class RSAUtils_user {


    /** *//** 
     * 加密算法RSA 
     */      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;  
  
    /** *//** 
     * 

* 生成密钥对(公钥和私钥) *

* * @return * @throws Exception */ public static Map genKeyPair() throws Exception { KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance(KEY_ALGORITHM); keyPairGen.initialize(1024); KeyPair keyPair = keyPairGen.generateKeyPair(); RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic(); RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate(); Map keyMap = new HashMap(2); keyMap.put(PUBLIC_KEY, publicKey); keyMap.put(PRIVATE_KEY, privateKey); return keyMap; } /** *//** *

* 用私钥对信息生成数字签名 *

* * @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()); } /** *//** *

* 校验数字签名 *

* * @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)); } /** *//** *

* 私钥解密 *

* * @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; } /** *//** *

* 公钥解密 *

* * @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; } /** *//** *

* 公钥加密 *

* * @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; } /** *//** *

* 私钥加密 *

* * @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; } /** *//** *

* 获取私钥 *

* * @param keyMap 密钥对 * @return * @throws Exception */ public static String getPrivateKey(Map keyMap) throws Exception { Key key = (Key) keyMap.get(PRIVATE_KEY); return Base64Utils.encode(key.getEncoded()); } /** *//** *

* 获取公钥 *

* * @param keyMap 密钥对 * @return * @throws Exception */ public static String getPublicKey(Map keyMap) throws Exception { Key key = (Key) keyMap.get(PUBLIC_KEY); return Base64Utils.encode(key.getEncoded()); } }

 

你可能感兴趣的:(RSA加解密)