(java)RSA/ECB/PKCS1Padding算法加密和解密

来源:互联网 发布:西西里美丽的传说 知乎 编辑:程序博客网 时间:2024/06/15 22:31

直接上代码:(有许多调试信息)

[java] view plain copy
 print?
  1. import java.io.*;  
  2. import java.lang.reflect.Method;  
  3. import java.security.*;  
  4. import java.security.spec.*;  
  5. import java.util.Base64;  
  6.   
  7. import javax.crypto.Cipher;  
  8.   
  9. public class TestEncryp {  
  10.   
  11.     public static void main(String[] args) throws Exception {  
  12.         // TODO Auto-generated method stub  
  13.         PrivateKey pri=getPriKey("/Users/cqx/bh_pkcs8_rsa_private_key_2048.pem","RSA");  
  14.         PublicKey pub=getPubKey("/Users/cqx/rsa_public_key_2048.pem","RSA");  
  15.         System.out.println("hahhahah11");  
  16.         String str="我是需要传递的字符串";  
  17.         byte[] estr=encrypt(str.getBytes(),pub,204811,"RSA/ECB/PKCS1Padding");  
  18.         System.out.println(new String(estr));  
  19.         System.out.println("hahhahah12");  
  20.         byte[] dstr=decrypt(estr, pri, 204811"RSA/ECB/PKCS1Padding");  
  21.         System.out.println(new String(dstr));  
  22.           
  23.     }  
  24.     public static byte[] decrypt(byte[] encryptedBytes, PrivateKey privateKey, int keyLength, int reserveSize, String cipherAlgorithm) throws Exception {  
  25.         int keyByteSize = keyLength / 8;  
  26.         int decryptBlockSize = keyByteSize - reserveSize;  
  27.         int nBlock = encryptedBytes.length / keyByteSize;  
  28.         ByteArrayOutputStream outbuf = null;  
  29.         try {  
  30.             Cipher cipher = Cipher.getInstance(cipherAlgorithm);  
  31.             cipher.init(Cipher.DECRYPT_MODE, privateKey);  
  32.   
  33.             outbuf = new ByteArrayOutputStream(nBlock * decryptBlockSize);  
  34.             for (int offset = 0; offset < encryptedBytes.length; offset += keyByteSize) {  
  35.                 int inputLen = encryptedBytes.length - offset;  
  36.                 if (inputLen > keyByteSize) {  
  37.                     inputLen = keyByteSize;  
  38.                 }  
  39.                 byte[] decryptedBlock = cipher.doFinal(encryptedBytes, offset, inputLen);  
  40.                 outbuf.write(decryptedBlock);  
  41.             }  
  42.             outbuf.flush();  
  43.             return outbuf.toByteArray();  
  44.         } catch (Exception e) {  
  45.             throw new Exception("DEENCRYPT ERROR:", e);  
  46.         } finally {  
  47.             try{  
  48.                 if(outbuf != null){  
  49.                     outbuf.close();  
  50.                 }  
  51.             }catch (Exception e){  
  52.                 outbuf = null;  
  53.                 throw new Exception("CLOSE ByteArrayOutputStream ERROR:", e);  
  54.             }  
  55.         }  
  56.     }  
  57.     public static byte[] encrypt(byte[] plainBytes, PublicKey publicKey, int keyLength, int reserveSize, String cipherAlgorithm) throws Exception {  
  58.         int keyByteSize = keyLength / 8;  
  59.         int encryptBlockSize = keyByteSize - reserveSize;  
  60.         int nBlock = plainBytes.length / encryptBlockSize;  
  61.         if ((plainBytes.length % encryptBlockSize) != 0) {  
  62.             nBlock += 1;  
  63.         }  
  64.         ByteArrayOutputStream outbuf = null;  
  65.         try {  
  66.             Cipher cipher = Cipher.getInstance(cipherAlgorithm);  
  67.             cipher.init(Cipher.ENCRYPT_MODE, publicKey);  
  68.   
  69.             outbuf = new ByteArrayOutputStream(nBlock * keyByteSize);  
  70.             for (int offset = 0; offset < plainBytes.length; offset += encryptBlockSize) {  
  71.                 int inputLen = plainBytes.length - offset;  
  72.                 if (inputLen > encryptBlockSize) {  
  73.                     inputLen = encryptBlockSize;  
  74.                 }  
  75.                 byte[] encryptedBlock = cipher.doFinal(plainBytes, offset, inputLen);  
  76.                 outbuf.write(encryptedBlock);  
  77.             }  
  78.             outbuf.flush();  
  79.             return outbuf.toByteArray();  
  80.         } catch (Exception e) {  
  81.             throw new Exception("ENCRYPT ERROR:", e);  
  82.         } finally {  
  83.             try{  
  84.                 if(outbuf != null){  
  85.                     outbuf.close();  
  86.                 }  
  87.             }catch (Exception e){  
  88.                 outbuf = null;  
  89.                 throw new Exception("CLOSE ByteArrayOutputStream ERROR:", e);  
  90.             }  
  91.         }  
  92.     }  
  93.     public static PrivateKey getPriKey(String privateKeyPath,String keyAlgorithm){  
  94.         PrivateKey privateKey = null;  
  95.         InputStream inputStream = null;  
  96.         try {  
  97.             if(inputStream==null){  
  98.                 System.out.println("hahhah1!");  
  99.             }  
  100.   
  101.             inputStream = new FileInputStream(privateKeyPath);  
  102.             System.out.println("hahhah2!");  
  103.             privateKey = getPrivateKey(inputStream,keyAlgorithm);  
  104.             System.out.println("hahhah3!");  
  105.         } catch (Exception e) {  
  106.             System.out.println("加载私钥出错!");  
  107.         } finally {  
  108.             if (inputStream != null){  
  109.                 try {  
  110.                     inputStream.close();  
  111.                 }catch (Exception e){  
  112.                     System.out.println("加载私钥,关闭流时出错!");  
  113.                 }  
  114.             }  
  115.         }  
  116.         return privateKey;  
  117.     }  
  118.     public static PublicKey getPubKey(String publicKeyPath,String keyAlgorithm){  
  119.         PublicKey publicKey = null;  
  120.         InputStream inputStream = null;  
  121.         try {  
  122.             System.out.println("hahhahah8");  
  123.             inputStream = new FileInputStream(publicKeyPath);  
  124.             System.out.println("hahhahah9");  
  125.             publicKey = getPublicKey(inputStream,keyAlgorithm);  
  126.             System.out.println("hahhahah10");  
  127.         } catch (Exception e) {  
  128.             System.out.println("加载公钥出错!");  
  129.         } finally {  
  130.             if (inputStream != null){  
  131.                 try {  
  132.                     inputStream.close();  
  133.                 }catch (Exception e){  
  134.                     System.out.println("加载公钥,关闭流时出错!");  
  135.                 }  
  136.             }  
  137.         }  
  138.         return publicKey;  
  139.     }  
  140.     public static PublicKey getPublicKey(InputStream inputStream, String keyAlgorithm) throws Exception {  
  141.         try {  
  142.             BufferedReader br = new BufferedReader(new InputStreamReader(inputStream));  
  143.             StringBuilder sb = new StringBuilder();  
  144.             String readLine = null;  
  145.             while ((readLine = br.readLine()) != null) {  
  146.                 if (readLine.charAt(0) == '-') {  
  147.                     continue;  
  148.                 } else {  
  149.                     sb.append(readLine);  
  150.                     sb.append('\r');  
  151.                 }  
  152.             }  
  153.             X509EncodedKeySpec pubX509 = new X509EncodedKeySpec(decodeBase64(sb.toString()));  
  154.             KeyFactory keyFactory = KeyFactory.getInstance(keyAlgorithm);  
  155.             PublicKey publicKey = keyFactory.generatePublic(pubX509);  
  156.   
  157.             return publicKey;  
  158.         } catch (Exception e) {  
  159.             throw new Exception("READ PUBLIC KEY ERROR:", e);  
  160.         } finally {  
  161.             try {  
  162.                 if (inputStream != null) {  
  163.                     inputStream.close();  
  164.                 }  
  165.             } catch (IOException e) {  
  166.                 inputStream = null;  
  167.                 throw new Exception("INPUT STREAM CLOSE ERROR:", e);  
  168.             }  
  169.         }  
  170.     }  
  171.      public static PrivateKey getPrivateKey(InputStream inputStream, String keyAlgorithm) throws Exception {  
  172.             try {  
  173.                 BufferedReader br = new BufferedReader(new InputStreamReader(inputStream));  
  174.                 StringBuilder sb = new StringBuilder();  
  175.                 String readLine = null;  
  176.                 while ((readLine = br.readLine()) != null) {  
  177.                     if (readLine.charAt(0) == '-') {  
  178.                         continue;  
  179.                     } else {  
  180.                         sb.append(readLine);  
  181.                         sb.append('\r');  
  182.                     }  
  183.                 }  
  184.                 System.out.println("hahhah4!"+decodeBase64(sb.toString()));  
  185.                 PKCS8EncodedKeySpec priPKCS8 = new PKCS8EncodedKeySpec(decodeBase64(sb.toString()));  
  186.                 System.out.println("hahhah5!");  
  187.                 KeyFactory keyFactory = KeyFactory.getInstance(keyAlgorithm);  
  188.                 System.out.println("hahhah6!");  
  189.                 PrivateKey privateKey = keyFactory.generatePrivate(priPKCS8);  
  190.                 System.out.println("hahhah7!");  
  191.                 return privateKey;  
  192.             } catch (Exception e) {  
  193.                 throw new Exception("READ PRIVATE KEY ERROR:" ,e);  
  194.             }  finally {  
  195.                 try {  
  196.                     if (inputStream != null) {  
  197.                         inputStream.close();  
  198.                     }  
  199.                 } catch (IOException e) {  
  200.                     inputStream = null;  
  201.                     throw new Exception("INPUT STREAM CLOSE ERROR:", e);  
  202.                 }  
  203.             }  
  204.         }  
  205.      //一下面是base64的编码和解码  
  206.      public static String encodeBase64(byte[]input) throws Exception{    
  207.             Class clazz=Class.forName("com.sun.org.apache.xerces.internal.impl.dv.util.Base64");    
  208.             Method mainMethod= clazz.getMethod("encode"byte[].class);    
  209.             mainMethod.setAccessible(true);    
  210.              Object retObj=mainMethod.invoke(nullnew Object[]{input});    
  211.              return (String)retObj;    
  212.         }    
  213.         /***  
  214.          * decode by Base64  
  215.          */    
  216.         public static byte[] decodeBase64(String input) throws Exception{    
  217.             Class clazz=Class.forName("com.sun.org.apache.xerces.internal.impl.dv.util.Base64");    
  218.             Method mainMethod= clazz.getMethod("decode", String.class);    
  219.             mainMethod.setAccessible(true);    
  220.              Object retObj=mainMethod.invoke(null, input);    
  221.              return (byte[])retObj;    
  222.         }    
  223. }