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

一、前端js

    1、前端js

          先引入 jsencrypt.js

<script src="${pageContext.request.contextPath}/static/scripts/jquery/dist/jsencrypt.js"></script>

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

<input type="hidden" value="${publicKeyString}" id="publicKeyString">

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

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

二、后台

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

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

公钥秘钥存放位置:

三、公钥秘钥生成:

1 Map<String, Object> keyMap=RSAUtils.genKeyPair();
2         
3 String publicKey = RSAUtils.getPublicKey(keyMap);  
4 String privateKey = RSAUtils.getPrivateKey(keyMap);

四、相关的工具类:

ToStringUtils.java

  1 package com.synjones.gatewayManage.utils;
  2  
  3 import java.io.BufferedReader;
  4 import java.io.ByteArrayOutputStream;
  5 import java.io.File;
  6 import java.io.FileInputStream;
  7 import java.io.IOException;
  8 import java.io.InputStreamReader;
  9 import java.io.ObjectOutputStream;
 10 import java.util.Calendar;
 11 import java.util.Random;
 12  
 13 public class ToStringUtils {
 14     
 15     
 16     
 17     
 18     
 19     
 20     
 21     
 22     public static String getDateFilePrefix() { 
 23           
 24         Calendar calendar = Calendar.getInstance();
 25         String now_y = String.valueOf(calendar.get(Calendar.YEAR));//得到年份
 26         String now_m = String.valueOf(calendar.get(Calendar.MONTH)+1);//得到月份
 27         String now_d = String.valueOf(calendar.get(Calendar.DATE));//得到月份中今天的号数
 28         String now_h = String.valueOf(calendar.get(Calendar.HOUR_OF_DAY));//得到一天中现在的时间,24小时制
 29         String now_mm = String.valueOf(calendar.get(Calendar.MINUTE));//得到分钟数
 30         String now_s = String.valueOf(calendar.get(Calendar.SECOND));//得到秒数
 31         //String now_ms =String.valueOf( calendar.get(Calendar.MILLISECOND));//得到秒数
 32         
 33         
 34         return now_y + "-" + now_m + "-" + now_d + "-" + now_h + "-" + now_mm + "-" + now_s + "-" ;
 35         //+ now_ms + "-";
 36         
 37  
 38     }
 39     
 40        /**
 41      * 数组转成十六进制字符串
 42      * @param byte[]
 43      * @return HexString
 44      */
 45     public static String toHexString1(byte[] b){
 46         StringBuffer buffer = new StringBuffer();
 47         for (int i = 0; i < b.length; ++i){
 48             buffer.append(toHexString1(b[i]));
 49         }
 50         return buffer.toString();
 51     }
 52     public static String toHexString1(byte b){
 53         String s = Integer.toHexString(b & 0xFF);
 54         if (s.length() == 1){
 55             return "0" + s;
 56         }else{
 57             return s;
 58         }
 59     }
 60     
 61     
 62     
 63     /**
 64      * 反转
 65      * @param s
 66      * @return
 67      */
 68     public static String stringRevToStr(String s) {
 69         
 70         String revS = new StringBuffer(s).reverse().toString();
 71         char[] charArray = revS.toCharArray();
 72         String val = "";
 73         for (int i = 0; i < charArray.length; i += 2) {
 74             char b = charArray[i];
 75             char c = charArray[i + 1];
 76             val += c;
 77             val += b;
 78         }
 79         //Integer revStoInt = Integer.valueOf(val);
 80         
 81         return val;
 82     }
 83     
 84     
 85     
 86     
 87     /**
 88      * 16进制转换成为string类型字符串
 89      * @param s
 90      * @return
 91      */
 92     public static String hexStringToString(String s) {
 93         if (s == null || s.equals("")) {
 94             return null;
 95         }
 96         s = s.replace(" ", "");
 97         byte[] baKeyword = new byte[s.length() / 2];
 98         for (int i = 0; i < baKeyword.length; i++) {
 99             try {
100                 baKeyword[i] = (byte) (0xff & Integer.parseInt(s.substring(i * 2, i * 2 + 2), 16));
101             } catch (Exception e) {
102                 e.printStackTrace();
103             }
104         }
105         try {
106             s = new String(baKeyword, "UTF-8");
107             new String();
108         } catch (Exception e1) {
109             e1.printStackTrace();
110         }
111         return s;
112     }
113     
114     
115     
116     /**
117      * 对象转Byte数组
118      * @param obj
119      * @return
120      */
121     public static byte[] objectToByteArray(Object obj) {
122         byte[] bytes = null;
123         ByteArrayOutputStream byteArrayOutputStream = null;
124         ObjectOutputStream objectOutputStream = null;
125         try {
126             byteArrayOutputStream = new ByteArrayOutputStream();
127             objectOutputStream = new ObjectOutputStream(byteArrayOutputStream);
128             objectOutputStream.writeObject(obj);
129             objectOutputStream.flush();
130             bytes = byteArrayOutputStream.toByteArray();
131  
132         } catch (IOException e) {
133             System.out.println("objectToByteArray failed, " + e);
134         } finally {
135             if (objectOutputStream != null) {
136                 try {
137                     objectOutputStream.close();
138                 } catch (IOException e) {
139                     //LOGGER.error("close objectOutputStream failed, " + e);
140                     System.out.println("close objectOutputStream failed, " + e);
141                 }
142             }
143             if (byteArrayOutputStream != null) {
144                 try {
145                     byteArrayOutputStream.close();
146                 } catch (IOException e) {
147                     //LOGGER.error("close byteArrayOutputStream failed, " + e);
148                     System.out.println("close byteArrayOutputStream failed, " + e);
149                 }
150             }
151  
152         }
153         return bytes;
154     }
155     
156     /**  
157      * 对象转数组  
158      * @param obj  
159      * @return  
160      */  
161     public static byte[] toByteArray (Object obj) {      
162         byte[] bytes = null;      
163         ByteArrayOutputStream bos = new ByteArrayOutputStream();      
164         try {        
165             ObjectOutputStream oos = new ObjectOutputStream(bos);         
166             oos.writeObject(obj);        
167             oos.flush();         
168             bytes = bos.toByteArray ();      
169             oos.close();         
170             bos.close();        
171         } catch (IOException ex) {        
172             ex.printStackTrace();   
173         }      
174         return bytes;    
175     }  
176     
177     
178     public static byte[] hexStringToByteArray(String s) {
179         int len = s.length();
180         byte[] data = new byte[len / 2];
181         try {
182             for (int i = 0; i < len; i += 2) {
183                 data[i / 2] = (byte) ((Character.digit(s.charAt(i), 16) << 4)
184                         + Character.digit(s.charAt(i+1), 16));
185             }
186         } catch (Exception e) {
187             //Log.d("", "Argument(s) for hexStringToByteArray(String s)"+ "was not a hex string");
188         }
189         return data;
190     }
191     
192     
193   //使用1字节就可以表示b
194       public static String numToHex8(int b) {
195               return String.format("%02X", b);//2表示需要两个16进行数
196       }
197       //需要使用2字节表示b
198       public static String numToHex16(int b) {
199               return String.format("%04X", b);
200       }
201       //需要使用4字节表示b
202       public static String numToHex32(int b) {
203               return String.format("%08X", b);
204       }
205       
206       
207       
208        public static byte[] toByteArray(short[] src) {
209  
210          int count = src.length;
211          byte[] dest = new byte[count << 1];
212          for (int i = 0; i < count; i++) {
213                  dest[i * 2] = (byte) (src[i] >> 8);
214                  dest[i * 2 + 1] = (byte) (src[i] >> 0);
215          }
216  
217          return dest;
218          
219      }
220        
221       public static byte[] shortToByteArray(short s) {  
222         byte[] targets = new byte[2];  
223         for (int i = 0; i < 2; i++) {  
224             int offset = (targets.length - 1 - i) * 8;  
225             targets[i] = (byte) ((s >>> offset) & 0xff);  
226         }  
227         return targets;  
228     }  
229       
230       /**
231        * int转byte
232        * @param value
233        * @return
234        */
235       public static byte[] intToBytes( int value )   
236     {   
237         byte[] src = new byte[4];  
238         src[3] =  (byte) ((value>>24) & 0xFF);  
239         src[2] =  (byte) ((value>>16) & 0xFF);  
240         src[1] =  (byte) ((value>>8) & 0xFF);    
241         src[0] =  (byte) (value & 0xFF);                  
242         return src;   
243     }  
244       
245         //byte 转 int
246         public static int ByteArrayToInt(byte[] bArr) {  
247                  if(bArr.length!=4){  
248                      return -1;  
249                  }  
250                  return (int) ((((bArr[3] & 0xff) << 24)    
251                             | ((bArr[2] & 0xff) << 16)    
252                             | ((bArr[1] & 0xff) << 8)
253         | ((bArr[0] & 0xff) << 0)));   
254         }
255            /**
256         * byte转long
257         * @param byteNum
258         * @return
259         */
260         public static long bytes2Long(byte[] byteNum) {
261             long num = 0;
262             for (int ix = 0; ix < 8; ++ix) {
263                 num <<= 8;
264                 num |= (byteNum[ix] & 0xff);
265             }
266             return num;
267         }
268         
269         
270         /** 
271          * 字节数组到long的转换. 
272          */  
273         public static long byteToLong(byte[] b) {  
274             long s = 0;  
275             long s0 = b[0] & 0xff;// 最低位  
276             long s1 = b[1] & 0xff;  
277             long s2 = b[2] & 0xff;  
278             long s3 = b[3] & 0xff;  
279             long s4 = b[4] & 0xff;// 最低位  
280             long s5 = b[5] & 0xff;  
281             long s6 = b[6] & 0xff;  
282             long s7 = b[7] & 0xff;  
283       
284             // s0不变  
285             s1 <<= 8;  
286             s2 <<= 16;  
287             s3 <<= 24;  
288             s4 <<= 8 * 4;  
289             s5 <<= 8 * 5;  
290             s6 <<= 8 * 6;  
291             s7 <<= 8 * 7;  
292             s = s0 | s1 | s2 | s3 | s4 | s5 | s6 | s7;  
293             return s;  
294         }  
295         /**
296          * 合并数组
297          * @param values
298          * @return
299          */
300         public static byte[] byteMergerAll(byte[]... values) {
301              int length_byte = 0;
302                  for (int i = 0; i < values.length; i++) {
303                      length_byte += values[i].length;
304                  }
305                  byte[] all_byte = new byte[length_byte];
306                  int countLength = 0;
307                  for (int i = 0; i < values.length; i++) {
308                      byte[] b = values[i];
309                      System.arraycopy(b, 0, all_byte, countLength, b.length);
310                      countLength += b.length;
311                  }
312                  return all_byte;
313              }
314  
315         
316         public static String checkByte(byte[] b) {  
317             String result = "value";
318             int leng = 0;
319             for(int i=0;i<b.length;i++){
320                 if(b[i]==0){
321                     leng++;
322                 }
323             }
324             if(leng==b.length){
325                 result = "notValue";
326             }
327             return result;
328         }
329         
330         
331         
332         /**
333          * 积压流水
334          * @param head
335          * @param tail
336          * @return
337          */
338         public static int getJy(int head, int tail)
339         {
340             int jy = 0;
341             if ((int)tail - (int)head >= 0)
342             {
343                 jy = tail - head;
344             }
345             else
346             {
347                 jy = tail - head + 100000;//总流水数100000
348             }
349  
350             return jy;
351         }
352         
353         public static byte[] shortToByte(short number) { 
354             int temp = number; 
355             byte[] b = new byte[2]; 
356             for (int i = 0; i < b.length; i++) { 
357                 b[i] = new Integer(temp & 0xff).byteValue();// 将最低位保存在最低位 
358                 temp = temp >> 8; // 向右移8位 
359             } 
360             return b; 
361         } 
362      
363      public static short byteToShort(byte[] b) { 
364             short s = 0; 
365             short s0 = (short) (b[0] & 0xff);// 最低位 
366             short s1 = (short) (b[1] & 0xff); 
367             s1 <<= 8; 
368             s = (short) (s0 | s1); 
369             return s; 
370         }
371         
372     //去读私钥
373     public static String readTxt(String filePath) {
374         String lineTxt = null;
375           try {
376             File file = new File(filePath);
377             if(file.isFile() && file.exists()) {
378               InputStreamReader isr = new InputStreamReader(new FileInputStream(file), "utf-8");
379               BufferedReader br = new BufferedReader(isr);
380               
381               while ((lineTxt = br.readLine()) != null) {
382                 System.out.println(lineTxt);
383                 return lineTxt;
384               }
385               br.close();
386             } else {
387               System.out.println("文件不存在!");
388             }
389           } catch (Exception e) {
390             System.out.println("文件读取错误!");
391           }
392         return lineTxt;
393          
394         } 
395  
396 }

Base64Utils.java

  1 package com.synjones.gatewayManage.utils;
  2  
  3  
  4  
  5 import java.io.ByteArrayInputStream;  
  6 import java.io.ByteArrayOutputStream;  
  7 import java.io.File;  
  8 import java.io.FileInputStream;  
  9 import java.io.FileOutputStream;  
 10 import java.io.InputStream;  
 11 import java.io.OutputStream;
 12  
 13 import org.apache.commons.codec.binary.Base64;
 14  
 15  
 16  
 17 public class Base64Utils {
 18  
 19  
 20     /** *//** 
 21      * 文件读取缓冲区大小 
 22      */  
 23     private static final int CACHE_SIZE = 1024;  
 24       
 25     /** *//** 
 26      * <p> 
 27      * BASE64字符串解码为二进制数据 
 28      * </p> 
 29      *  
 30      * @param base64 
 31      * @return 
 32      * @throws Exception 
 33      */  
 34     public static byte[] decode(String base64) throws Exception {  
 35         return Base64.decodeBase64(base64.getBytes());  
 36     }  
 37       
 38     /** *//** 
 39      * <p> 
 40      * 二进制数据编码为BASE64字符串 
 41      * </p> 
 42      *  
 43      * @param bytes 
 44      * @return 
 45      * @throws Exception 
 46      */  
 47     public static String encode(byte[] bytes) throws Exception {  
 48         return new String(Base64.encodeBase64(bytes));  
 49     }  
 50       
 51     /** *//** 
 52      * <p> 
 53      * 将文件编码为BASE64字符串 
 54      * </p> 
 55      * <p> 
 56      * 大文件慎用,可能会导致内存溢出 
 57      * </p> 
 58      *  
 59      * @param filePath 文件绝对路径 
 60      * @return 
 61      * @throws Exception 
 62      */  
 63     public static String encodeFile(String filePath) throws Exception {  
 64         byte[] bytes = fileToByte(filePath);  
 65         return encode(bytes);  
 66     }  
 67       
 68     /** *//** 
 69      * <p> 
 70      * BASE64字符串转回文件 
 71      * </p> 
 72      *  
 73      * @param filePath 文件绝对路径 
 74      * @param base64 编码字符串 
 75      * @throws Exception 
 76      */  
 77     public static void decodeToFile(String filePath, String base64) throws Exception {  
 78         byte[] bytes = decode(base64);  
 79         byteArrayToFile(bytes, filePath);  
 80     }  
 81       
 82     /** *//** 
 83      * <p> 
 84      * 文件转换为二进制数组 
 85      * </p> 
 86      *  
 87      * @param filePath 文件路径 
 88      * @return 
 89      * @throws Exception 
 90      */  
 91     public static byte[] fileToByte(String filePath) throws Exception {  
 92         byte[] data = new byte[0];  
 93         File file = new File(filePath);  
 94         if (file.exists()) {  
 95             FileInputStream in = new FileInputStream(file);  
 96             ByteArrayOutputStream out = new ByteArrayOutputStream(2048);  
 97             byte[] cache = new byte[CACHE_SIZE];  
 98             int nRead = 0;  
 99             while ((nRead = in.read(cache)) != -1) {  
100                 out.write(cache, 0, nRead);  
101                 out.flush();  
102             }  
103             out.close();  
104             in.close();  
105             data = out.toByteArray();  
106          }  
107         return data;  
108     }  
109       
110     /** *//** 
111      * <p> 
112      * 二进制数据写文件 
113      * </p> 
114      *  
115      * @param bytes 二进制数据 
116      * @param filePath 文件生成目录 
117      */  
118     public static void byteArrayToFile(byte[] bytes, String filePath) throws Exception {  
119         InputStream in = new ByteArrayInputStream(bytes);     
120         File destFile = new File(filePath);  
121         if (!destFile.getParentFile().exists()) {  
122             destFile.getParentFile().mkdirs();  
123         }  
124         destFile.createNewFile();  
125         OutputStream out = new FileOutputStream(destFile);  
126         byte[] cache = new byte[CACHE_SIZE];  
127         int nRead = 0;  
128         while ((nRead = in.read(cache)) != -1) {     
129             out.write(cache, 0, nRead);  
130             out.flush();  
131         }  
132         out.close();  
133         in.close();  
134     }  
135     
136 }

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;  
  
    /** *//** 
     * <p> 
     * 生成密钥对(公钥和私钥) 
     * </p> 
     *  
     * @return 
     * @throws Exception 
     */  
    public static Map<String, Object> 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<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 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 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 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());  
    }  
  
    
}

  

原文地址:https://www.cnblogs.com/small-panda/p/13517158.html