Java中使用OpenSSL生成的RSA公私鑰進行數據加解密

當前使用的是Linux系統,已經按裝使用OpenSSL軟件包,java

1、使用OpenSSL來生成私鑰和公鑰算法

一、執行命令openssl version -a 驗證機器上已經安裝openssl apache

openssl version -a

運行結果:app

二、生成私鑰:這條命令讓openssl隨機生成了一份私鑰,加密長度是1024位。加密長度是指理論上最大容許」被加密的信息「長度的限制,也就是明文的長度限制。隨着這個參數的增大(比方說2048),容許的明文長度也會增長,但同時也會形成計算複雜度的極速增加。通常推薦的長度就是2048位dom

openssl genrsa -out rsa_private_key.pem 2048

 運行結果:ide

生產私鑰文件:rsa_private_key.pem,內容都是標準的ASCII字符,開頭一行和結尾一行有明顯的標記,真正的私鑰數據是中間的不規則字符測試

  

三、根據私鑰生產公鑰:rsa_public_key.pem or private_key.derui

openssl rsa -in rsa_private_key.pem -out rsa_public_key.pem -pubout

openssl pkcs8 -topk8 -inform PEM -outform DER -in private_key.pem -out private_key.der -nocrypt

運行結果:編碼

公鑰內容:加密

注意:此時的私鑰還不能直接被使用,須要進行PKCS#8編碼:

 四、PKCS#8編碼:指明輸入私鑰文件爲rsa_private_key.pem,輸出私鑰文件爲pkcs8_rsa_private_key.pem,不採用任何二次加密(-nocrypt)

openssl pkcs8 -topk8 -in rsa_private_key.pem -out pkcs8_rsa_private_key.pem -nocrypt

  openssl rsa -in private_key.pem -pubout -outform DER -out public_key.der

至此:可用的密鑰對已經生成好了,私鑰使用pkcs8_rsa_private_key.pem,公鑰採用rsa_public_key.pem

 

2、java使用:

讀取pem文件格式:

  1 import org.apache.commons.codec.binary.Base64;
  2 import sun.misc.BASE64Decoder;
  3 
  4 import javax.crypto.BadPaddingException;
  5 import javax.crypto.Cipher;
  6 import javax.crypto.IllegalBlockSizeException;
  7 import javax.crypto.NoSuchPaddingException;
  8 import java.io.*;
  9 import java.security.*;
 10 import java.security.interfaces.RSAPrivateKey;
 11 import java.security.interfaces.RSAPublicKey;
 12 import java.security.spec.InvalidKeySpecException;
 13 import java.security.spec.PKCS8EncodedKeySpec;
 14 import java.security.spec.X509EncodedKeySpec;
 15 
 16 /**
 17  * <p>
 18  * 1.
 19  * </p>
 20  *
 21  * @author PollyLuo
 22  * @version 1.0.0
 23  */
 24 public class RSAEncrypt {
 25     /**
 26      * 字節數據轉字符串專用集合
 27      */
 28     private static final char[] HEX_CHAR = {'0', '1', '2', '3', '4', '5', '6',
 29             '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};
 30 
 31 
 32     private static final String PRIVATE_KEY = "/pkcs8_rsa_private_key.pem";
 33 
 34     private static final String PUBLIC_KEY = "/rsa_public_key.pem";
 35 
 36     /**
 37      * 隨機生成密鑰對
 38      */
 39     public static void genKeyPair(String filePath) {
 40         // KeyPairGenerator類用於生成公鑰和私鑰對,基於RSA算法生成對象
 41         KeyPairGenerator keyPairGen = null;
 42         try {
 43             keyPairGen = KeyPairGenerator.getInstance("RSA");
 44         } catch (NoSuchAlgorithmException e) {
 45             e.printStackTrace();
 46         }
 47         // 初始化密鑰對生成器,密鑰大小爲96-1024位
 48         keyPairGen.initialize(1024, new SecureRandom());
 49         // 生成一個密鑰對,保存在keyPair中
 50         KeyPair keyPair = keyPairGen.generateKeyPair();
 51         // 獲得私鑰
 52         RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();
 53         // 獲得公鑰
 54         RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();
 55         try {
 56             // 獲得公鑰字符串
 57             Base64 base64 = new Base64();
 58             String publicKeyString = new String(base64.encode(publicKey.getEncoded()));
 59             // 獲得私鑰字符串
 60             String privateKeyString = new String(base64.encode(privateKey.getEncoded()));
 61             // 將密鑰對寫入到文件
 62             FileWriter pubfw = new FileWriter(filePath + PUBLIC_KEY);
 63             FileWriter prifw = new FileWriter(filePath + PRIVATE_KEY);
 64             BufferedWriter pubbw = new BufferedWriter(pubfw);
 65             BufferedWriter pribw = new BufferedWriter(prifw);
 66             pubbw.write(publicKeyString);
 67             pribw.write(privateKeyString);
 68             pubbw.flush();
 69             pubbw.close();
 70             pubfw.close();
 71             pribw.flush();
 72             pribw.close();
 73             prifw.close();
 74         } catch (Exception e) {
 75             e.printStackTrace();
 76         }
 77     }
 78 
 79     /**
 80      * 從文件中輸入流中加載公鑰
 81      *
 82      * @param path 公鑰輸入流
 83      * @throws Exception 加載公鑰時產生的異常
 84      */
 85     public static String loadPublicKeyByFile(String path) throws Exception {
 86         try {
 87             BufferedReader br = new BufferedReader(new FileReader(path
 88                     + PUBLIC_KEY));
 89             String readLine = null;
 90             StringBuilder sb = new StringBuilder();
 91             while ((readLine = br.readLine()) != null) {
 92                 if (readLine.charAt(0) == '-') {
 93                     continue;
 94                 } else {
 95                     sb.append(readLine);
 96                     sb.append('\r');
 97                 }
 98             }
 99             br.close();
100             return sb.toString();
101         } catch (IOException e) {
102             throw new Exception("公鑰數據流讀取錯誤");
103         } catch (NullPointerException e) {
104             throw new Exception("公鑰輸入流爲空");
105         }
106     }
107 
108     /**
109      * 從字符串中加載公鑰
110      *
111      * @param publicKeyStr 公鑰數據字符串
112      * @throws Exception 加載公鑰時產生的異常
113      */
114     public static RSAPublicKey loadPublicKeyByStr(String publicKeyStr)
115             throws Exception {
116         try {
117             BASE64Decoder base64 = new BASE64Decoder();
118             byte[] buffer = base64.decodeBuffer(publicKeyStr);
119             KeyFactory keyFactory = KeyFactory.getInstance("RSA");
120             X509EncodedKeySpec keySpec = new X509EncodedKeySpec(buffer);
121             return (RSAPublicKey) keyFactory.generatePublic(keySpec);
122         } catch (NoSuchAlgorithmException e) {
123             throw new Exception("無此算法");
124         } catch (InvalidKeySpecException e) {
125             throw new Exception("公鑰非法");
126         } catch (NullPointerException e) {
127             throw new Exception("公鑰數據爲空");
128         }
129     }
130 
131     /**
132      * 從文件中加載私鑰
133      *
134      * @param path 私鑰文件名
135      * @return 是否成功
136      * @throws Exception
137      */
138     public static String loadPrivateKeyByFile(String path) throws Exception {
139         try {
140             BufferedReader br = new BufferedReader(new FileReader(path
141                     + PRIVATE_KEY));
142             String readLine = null;
143             StringBuilder sb = new StringBuilder();
144             while ((readLine = br.readLine()) != null) {
145                 if (readLine.charAt(0) == '-') {
146                     continue;
147                 } else {
148                     sb.append(readLine);
149                     sb.append('\r');
150                 }
151             }
152             br.close();
153             return sb.toString();
154         } catch (IOException e) {
155             throw new Exception("私鑰數據讀取錯誤");
156         } catch (NullPointerException e) {
157             throw new Exception("私鑰輸入流爲空");
158         }
159     }
160 
161     public static RSAPrivateKey loadPrivateKeyByStr(String privateKeyStr)
162             throws Exception {
163         try {
164             BASE64Decoder base64Decoder = new BASE64Decoder();
165             byte[] buffer = base64Decoder.decodeBuffer(privateKeyStr);
166             PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(buffer);
167             KeyFactory keyFactory = KeyFactory.getInstance("RSA");
168             return (RSAPrivateKey) keyFactory.generatePrivate(keySpec);
169         } catch (NoSuchAlgorithmException e) {
170             throw new Exception("無此算法");
171         } catch (InvalidKeySpecException e) {
172             throw new Exception("私鑰非法");
173         } catch (NullPointerException e) {
174             throw new Exception("私鑰數據爲空");
175         }
176     }
177 
178     /**
179      * 公鑰加密過程
180      *
181      * @param publicKey     公鑰
182      * @param plainTextData 明文數據
183      * @return
184      * @throws Exception 加密過程當中的異常信息
185      */
186     public static byte[] encrypt(RSAPublicKey publicKey, byte[] plainTextData)
187             throws Exception {
188         if (publicKey == null) {
189             throw new Exception("加密公鑰爲空, 請設置");
190         }
191         Cipher cipher = null;
192         try {
193             // 使用默認RSA
194             cipher = Cipher.getInstance("RSA");
195             // cipher= Cipher.getInstance("RSA", new BouncyCastleProvider());
196             cipher.init(Cipher.ENCRYPT_MODE, publicKey);
197             byte[] output = cipher.doFinal(plainTextData);
198             return output;
199         } catch (NoSuchAlgorithmException e) {
200             throw new Exception("無此加密算法");
201         } catch (NoSuchPaddingException e) {
202             e.printStackTrace();
203             return null;
204         } catch (InvalidKeyException e) {
205             throw new Exception("加密公鑰非法,請檢查");
206         } catch (IllegalBlockSizeException e) {
207             throw new Exception("明文長度非法");
208         } catch (BadPaddingException e) {
209             throw new Exception("明文數據已損壞");
210         }
211     }
212 
213     /**
214      * 私鑰加密過程
215      *
216      * @param privateKey    私鑰
217      * @param plainTextData 明文數據
218      * @return
219      * @throws Exception 加密過程當中的異常信息
220      */
221     public static byte[] encrypt(RSAPrivateKey privateKey, byte[] plainTextData)
222             throws Exception {
223         if (privateKey == null) {
224             throw new Exception("加密私鑰爲空, 請設置");
225         }
226         Cipher cipher = null;
227         try {
228             // 使用默認RSA
229             cipher = Cipher.getInstance("RSA");
230             cipher.init(Cipher.ENCRYPT_MODE, privateKey);
231             byte[] output = cipher.doFinal(plainTextData);
232             return output;
233         } catch (NoSuchAlgorithmException e) {
234             throw new Exception("無此加密算法");
235         } catch (NoSuchPaddingException e) {
236             e.printStackTrace();
237             return null;
238         } catch (InvalidKeyException e) {
239             throw new Exception("加密私鑰非法,請檢查");
240         } catch (IllegalBlockSizeException e) {
241             throw new Exception("明文長度非法");
242         } catch (BadPaddingException e) {
243             throw new Exception("明文數據已損壞");
244         }
245     }
246 
247     /**
248      * 私鑰解密過程
249      *
250      * @param privateKey 私鑰
251      * @param cipherData 密文數據
252      * @return 明文
253      * @throws Exception 解密過程當中的異常信息
254      */
255     public static byte[] decrypt(RSAPrivateKey privateKey, byte[] cipherData)
256             throws Exception {
257         if (privateKey == null) {
258             throw new Exception("解密私鑰爲空, 請設置");
259         }
260         Cipher cipher = null;
261         try {
262             // 使用默認RSA
263             cipher = Cipher.getInstance("RSA");
264             // cipher= Cipher.getInstance("RSA", new BouncyCastleProvider());
265             cipher.init(Cipher.DECRYPT_MODE, privateKey);
266             byte[] output = cipher.doFinal(cipherData);
267             return output;
268         } catch (NoSuchAlgorithmException e) {
269             throw new Exception("無此解密算法");
270         } catch (NoSuchPaddingException e) {
271             e.printStackTrace();
272             return null;
273         } catch (InvalidKeyException e) {
274             throw new Exception("解密私鑰非法,請檢查");
275         } catch (IllegalBlockSizeException e) {
276             throw new Exception("密文長度非法");
277         } catch (BadPaddingException e) {
278             throw new Exception("密文數據已損壞");
279         }
280     }
281 
282     /**
283      * 公鑰解密過程
284      *
285      * @param publicKey  公鑰
286      * @param cipherData 密文數據
287      * @return 明文
288      * @throws Exception 解密過程當中的異常信息
289      */
290     public static byte[] decrypt(RSAPublicKey publicKey, byte[] cipherData)
291             throws Exception {
292         if (publicKey == null) {
293             throw new Exception("解密公鑰爲空, 請設置");
294         }
295         Cipher cipher = null;
296         try {
297             // 使用默認RSA
298             cipher = Cipher.getInstance("RSA");
299             // cipher= Cipher.getInstance("RSA", new BouncyCastleProvider());
300             cipher.init(Cipher.DECRYPT_MODE, publicKey);
301             byte[] output = cipher.doFinal(cipherData);
302             return output;
303         } catch (NoSuchAlgorithmException e) {
304             throw new Exception("無此解密算法");
305         } catch (NoSuchPaddingException e) {
306             e.printStackTrace();
307             return null;
308         } catch (InvalidKeyException e) {
309             throw new Exception("解密公鑰非法,請檢查");
310         } catch (IllegalBlockSizeException e) {
311             throw new Exception("密文長度非法");
312         } catch (BadPaddingException e) {
313             throw new Exception("密文數據已損壞");
314         }
315     }
316 
317     /**
318      * 字節數據轉十六進制字符串
319      *
320      * @param data 輸入數據
321      * @return 十六進制內容
322      */
323     public static String byteArrayToString(byte[] data) {
324         StringBuilder stringBuilder = new StringBuilder();
325         for (int i = 0; i < data.length; i++) {
326             // 取出字節的高四位 做爲索引獲得相應的十六進制標識符 注意無符號右移
327             stringBuilder.append(HEX_CHAR[(data[i] & 0xf0) >>> 4]);
328             // 取出字節的低四位 做爲索引獲得相應的十六進制標識符
329             stringBuilder.append(HEX_CHAR[(data[i] & 0x0f)]);
330             if (i < data.length - 1) {
331                 stringBuilder.append(' ');
332             }
333         }
334         return stringBuilder.toString();
335     }
336 }
View Code

 

讀取der文件格式:

  1 import lombok.extern.slf4j.Slf4j;
  2 
  3 import javax.crypto.BadPaddingException;
  4 import javax.crypto.Cipher;
  5 import javax.crypto.IllegalBlockSizeException;
  6 import javax.crypto.NoSuchPaddingException;
  7 import java.io.*;
  8 import java.nio.file.Files;
  9 import java.nio.file.Paths;
 10 import java.security.*;
 11 import java.security.spec.InvalidKeySpecException;
 12 import java.security.spec.KeySpec;
 13 import java.security.spec.PKCS8EncodedKeySpec;
 14 import java.security.spec.X509EncodedKeySpec;
 15 
 16 /**
 17  * <p>
 18  * 1.
 19  * </p>
 20  *
 21  * @author PollyLuo
 22  * @version 1.0.0
 23  */
 24 @Slf4j
 25 public class RSAEncrypt {
 26     /**
 27      * 字節數據轉字符串專用集合
 28      */
 29     private static final char[] HEX_CHAR = {'0', '1', '2', '3', '4', '5', '6',
 30             '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};
 31 
 32     /**
 33      * 獲取der公鑰
 34      *
 35      * @param key 公鑰內容
 36      * @return 公鑰對象
 37      * @throws Exception
 38      */
 39     public static PublicKey geneneratePublicKey(byte[] key) throws Exception {
 40         try {
 41             KeySpec keySpec = new X509EncodedKeySpec(key);
 42             KeyFactory keyFactory = KeyFactory.getInstance("RSA");
 43             return keyFactory.generatePublic(keySpec);
 44         } catch (NoSuchAlgorithmException e) {
 45             throw new Exception("無此算法");
 46         } catch (InvalidKeySpecException e) {
 47             throw new Exception("公鑰非法");
 48         } catch (NullPointerException e) {
 49             throw new Exception("公鑰數據爲空");
 50         }
 51     }
 52 
 53     /**
 54      * 獲取der私鑰
 55      *
 56      * @param key 私鑰內容
 57      * @return 公鑰對象
 58      * @throws Exception
 59      */
 60     public static PrivateKey geneneratePrivateKey(byte[] key) throws Exception {
 61         try {
 62             KeySpec keySpec = new PKCS8EncodedKeySpec(key);
 63             KeyFactory keyFactory = KeyFactory.getInstance("RSA");
 64             return keyFactory.generatePrivate(keySpec);
 65         } catch (NoSuchAlgorithmException e) {
 66             throw new Exception("無此算法");
 67         } catch (InvalidKeySpecException e) {
 68             throw new Exception("私鑰非法");
 69         } catch (NullPointerException e) {
 70             throw new Exception("私鑰數據爲空");
 71         }
 72     }
 73 
 74     /**
 75      * 根據Cer文件讀取密鑰內容
 76      *
 77      * @param pubCerPath 密鑰文件地址
 78      * @return
 79      */
 80     public static byte[] getKeyFromFile(String pubCerPath) {
 81         try (InputStream inputStream = Files.newInputStream(Paths.get(pubCerPath));) {
 82             byte[] reads = new byte[inputStream.available()];
 83             inputStream.read(reads);
 84             return reads;
 85         } catch (FileNotFoundException e) {
 86             log.error("密鑰文件不存在:", e);
 87         } catch (IOException e) {
 88             log.error("密鑰文件讀取失敗:", e);
 89         }
 90         return null;
 91     }
 92 
 93 
 94     /**
 95      * 公鑰加密過程
 96      *
 97      * @param publicKey     公鑰
 98      * @param plainTextData 明文數據
 99      * @return
100      * @throws Exception 加密過程當中的異常信息
101      */
102     public static byte[] encrypt(PublicKey publicKey, byte[] plainTextData)
103             throws Exception {
104         if (publicKey == null) {
105             throw new Exception("加密公鑰爲空, 請設置");
106         }
107         Cipher cipher = null;
108         try {
109             // 使用默認RSA
110             cipher = Cipher.getInstance("RSA");
111             cipher.init(Cipher.ENCRYPT_MODE, publicKey);
112             byte[] output = cipher.doFinal(plainTextData);
113             return output;
114         } catch (NoSuchAlgorithmException e) {
115             throw new Exception("無此加密算法");
116         } catch (NoSuchPaddingException e) {
117             e.printStackTrace();
118             return null;
119         } catch (InvalidKeyException e) {
120             throw new Exception("加密公鑰非法,請檢查");
121         } catch (IllegalBlockSizeException e) {
122             throw new Exception("明文長度非法");
123         } catch (BadPaddingException e) {
124             throw new Exception("明文數據已損壞");
125         }
126     }
127 
128     /**
129      * 私鑰加密過程
130      *
131      * @param privateKey    私鑰
132      * @param plainTextData 明文數據
133      * @return
134      * @throws Exception 加密過程當中的異常信息
135      */
136     public static byte[] encrypt(PrivateKey privateKey, byte[] plainTextData)
137             throws Exception {
138         if (privateKey == null) {
139             throw new Exception("加密私鑰爲空, 請設置");
140         }
141         Cipher cipher = null;
142         try {
143             // 使用默認RSA
144             cipher = Cipher.getInstance("RSA");
145             cipher.init(Cipher.ENCRYPT_MODE, privateKey);
146             byte[] output = cipher.doFinal(plainTextData);
147             return output;
148         } catch (NoSuchAlgorithmException e) {
149             throw new Exception("無此加密算法");
150         } catch (NoSuchPaddingException e) {
151             e.printStackTrace();
152             return null;
153         } catch (InvalidKeyException e) {
154             throw new Exception("加密私鑰非法,請檢查");
155         } catch (IllegalBlockSizeException e) {
156             throw new Exception("明文長度非法");
157         } catch (BadPaddingException e) {
158             throw new Exception("明文數據已損壞");
159         }
160     }
161 
162     /**
163      * 私鑰解密過程
164      *
165      * @param privateKey 私鑰
166      * @param cipherData 密文數據
167      * @return 明文
168      * @throws Exception 解密過程當中的異常信息
169      */
170     public static byte[] decrypt(PrivateKey privateKey, byte[] cipherData)
171             throws Exception {
172         if (privateKey == null) {
173             throw new Exception("解密私鑰爲空, 請設置");
174         }
175         Cipher cipher = null;
176         try {
177             // 使用默認RSA
178             cipher = Cipher.getInstance("RSA");
179             // cipher= Cipher.getInstance("RSA", new BouncyCastleProvider());
180             cipher.init(Cipher.DECRYPT_MODE, privateKey);
181             byte[] output = cipher.doFinal(cipherData);
182             return output;
183         } catch (NoSuchAlgorithmException e) {
184             throw new Exception("無此解密算法");
185         } catch (NoSuchPaddingException e) {
186             e.printStackTrace();
187             return null;
188         } catch (InvalidKeyException e) {
189             throw new Exception("解密私鑰非法,請檢查");
190         } catch (IllegalBlockSizeException e) {
191             throw new Exception("密文長度非法");
192         } catch (BadPaddingException e) {
193             throw new Exception("密文數據已損壞");
194         }
195     }
196 
197     /**
198      * 公鑰解密過程
199      *
200      * @param publicKey  公鑰
201      * @param cipherData 密文數據
202      * @return 明文
203      * @throws Exception 解密過程當中的異常信息
204      */
205     public static byte[] decrypt(PublicKey publicKey, byte[] cipherData)
206             throws Exception {
207         if (publicKey == null) {
208             throw new Exception("解密公鑰爲空, 請設置");
209         }
210         Cipher cipher = null;
211         try {
212             // 使用默認RSA
213             cipher = Cipher.getInstance("RSA");
214             // cipher= Cipher.getInstance("RSA", new BouncyCastleProvider());
215             cipher.init(Cipher.DECRYPT_MODE, publicKey);
216             byte[] output = cipher.doFinal(cipherData);
217             return output;
218         } catch (NoSuchAlgorithmException e) {
219             throw new Exception("無此解密算法");
220         } catch (NoSuchPaddingException e) {
221             e.printStackTrace();
222             return null;
223         } catch (InvalidKeyException e) {
224             throw new Exception("解密公鑰非法,請檢查");
225         } catch (IllegalBlockSizeException e) {
226             throw new Exception("密文長度非法");
227         } catch (BadPaddingException e) {
228             throw new Exception("密文數據已損壞");
229         }
230     }
231 
232     /**
233      * 字節數據轉十六進制字符串
234      *
235      * @param data 輸入數據
236      * @return 十六進制內容
237      */
238     public static String byteArrayToString(byte[] data) {
239         StringBuilder stringBuilder = new StringBuilder();
240         for (int i = 0; i < data.length; i++) {
241             // 取出字節的高四位 做爲索引獲得相應的十六進制標識符 注意無符號右移
242             stringBuilder.append(HEX_CHAR[(data[i] & 0xf0) >>> 4]);
243             // 取出字節的低四位 做爲索引獲得相應的十六進制標識符
244             stringBuilder.append(HEX_CHAR[(data[i] & 0x0f)]);
245             if (i < data.length - 1) {
246                 stringBuilder.append(' ');
247             }
248         }
249         return stringBuilder.toString();
250     }
251 }
View Code

 

SHA256withRSA簽名:

  1 import java.security.PrivateKey;
  2 import java.security.PublicKey;
  3 
  4 /**
  5  * <p>
  6  * 1.
  7  * </p>
  8  *
  9  * @author PollyLuo
 10  * @version 1.0.0
 11  */
 12 public class RSASignature {
 13 
 14     /**
 15      * 簽名算法
 16      */
 17     public static final String SIGN_ALGORITHMS = "SHA256withRSA";
 18 
 19     /**
 20      * RSA簽名
 21      *
 22      * @param content    待簽名數據
 23      * @param privateKey 商戶私鑰
 24      * @param encode     字符集編碼
 25      * @return 簽名值
 26      */
 27     public static String sign(String content, PrivateKey privateKey, String encode) {
 28         try {
 29             java.security.Signature signature = java.security.Signature.getInstance(SIGN_ALGORITHMS);
 30             signature.initSign(privateKey);
 31             signature.update(content.getBytes(encode));
 32             byte[] signed = signature.sign();
 33             return byte2Hex(signed);
 34         } catch (Exception e) {
 35             e.printStackTrace();
 36         }
 37 
 38         return null;
 39     }
 40 
 41     public static String sign(String content, PrivateKey privateKey) {
 42         try {
 43             java.security.Signature signature = java.security.Signature.getInstance(SIGN_ALGORITHMS);
 44             signature.initSign(privateKey);
 45             signature.update(content.getBytes());
 46             byte[] signed = signature.sign();
 47             return byte2Hex(signed);
 48         } catch (Exception e) {
 49             e.printStackTrace();
 50         }
 51         return null;
 52     }
 53 
 54 
 55     /**
 56      * 將byte[] 轉換成字符串
 57      */
 58     public static String byte2Hex(byte[] srcBytes) {
 59         StringBuilder hexRetSB = new StringBuilder();
 60         for (byte b : srcBytes) {
 61             String hexString = Integer.toHexString(0x00ff & b);
 62             hexRetSB.append(hexString.length() == 1 ? 0 : "").append(hexString);
 63         }
 64         return hexRetSB.toString();
 65     }
 66 
 67     /**
 68      * RSA驗簽名檢查
 69      *
 70      * @param content   待簽名數據
 71      * @param sign      簽名值
 72      * @param publicKey 分配給開發商公鑰
 73      * @param encode    字符集編碼
 74      * @return 布爾值
 75      */
 76     public static boolean doCheck(String content, String sign, PublicKey publicKey, String encode) {
 77         try {
 78             java.security.Signature signature = java.security.Signature.getInstance(SIGN_ALGORITHMS);
 79 
 80             signature.initVerify(publicKey);
 81             signature.update(content.getBytes(encode));
 82 
 83             boolean bverify = signature.verify(hex2Bytes(sign));
 84             return bverify;
 85 
 86         } catch (Exception e) {
 87             e.printStackTrace();
 88         }
 89 
 90         return false;
 91     }
 92 
 93     public static boolean doCheck(String content, String sign, PublicKey publicKey) {
 94         try {
 95             java.security.Signature signature = java.security.Signature.getInstance(SIGN_ALGORITHMS);
 96             signature.initVerify(publicKey);
 97             signature.update(content.getBytes());
 98             boolean bverify = signature.verify(hex2Bytes(sign));
 99             return bverify;
100         } catch (Exception e) {
101             e.printStackTrace();
102         }
103 
104         return false;
105     }
106 
107 
108     /**
109      * 將16進制字符串轉爲轉換成字符串
110      */
111     public static byte[] hex2Bytes(String source) {
112         byte[] sourceBytes = new byte[source.length() / 2];
113         for (int i = 0; i < sourceBytes.length; i++) {
114             sourceBytes[i] = (byte) Integer.parseInt(source.substring(i * 2, i * 2 + 2), 16);
115         }
116         return sourceBytes;
117     }
118 
119 
120 }
View Code

 

測試方法:

 1 import RSAEncrypt;
 2 import RSASignature;
 3 import org.apache.commons.codec.binary.Base64;
 4 
 5 public class ApplicationTests {
 6 
 7     public static void main(String[] args) throws Exception {
 8         String filepath = "D:\\key\\MDAQ\\";
 9         Base64 base64 = new Base64();
10 
11         System.out.println("--------------公鑰加密私鑰解密過程-------------------");
12         String signKey = "ihep_公鑰加密私鑰解密";
13         // 公鑰加密過程
14         byte[] cipherData = RSAEncrypt.encrypt(RSAEncrypt.loadPublicKeyByStr(RSAEncrypt.loadPublicKeyByFile(filepath)),
15                 signKey.getBytes());
16         String cipher = new String(base64.encode(cipherData));
17         // 私鑰解密過程
18         byte[] res = RSAEncrypt.decrypt(RSAEncrypt.loadPrivateKeyByStr(RSAEncrypt.loadPrivateKeyByFile(filepath)),
19                 base64.decode(cipher));
20         String restr = new String(res);
21         System.out.println("原文:" + signKey);
22         System.out.println("加密:" + cipher);
23         System.out.println("解密:" + restr);
24         System.out.println();
25 
26         System.out.println("--------------私鑰加密公鑰解密過程-------------------");
27 //        signKey = "ihep_私鑰加密公鑰解密";
28         // 私鑰加密過程
29         cipherData = RSAEncrypt.encrypt(RSAEncrypt.loadPrivateKeyByStr(RSAEncrypt.loadPrivateKeyByFile(filepath)),
30                 signKey.getBytes());
31         cipher = new String(base64.encode(cipherData));
32         // 公鑰解密過程
33         res = RSAEncrypt.decrypt(RSAEncrypt.loadPublicKeyByStr(RSAEncrypt.loadPublicKeyByFile(filepath)),
34                 base64.decode(cipher));
35         restr = new String(res);
36         System.out.println("原文:" + signKey);
37         System.out.println("加密:" + cipher);
38         System.out.println("解密:" + restr);
39         System.out.println();
40 
41 
42         System.out.println("---------------私鑰簽名過程------------------");
43 //        String content = "ihep_這是用於簽名的原始數據";
44         String content = signKey;
45         String signstr = RSASignature.sign(content, RSAEncrypt.loadPrivateKeyByFile(filepath));
46         System.out.println("簽名原串:" + content);
47         System.out.println("簽名串:" + signstr);
48         System.out.println();
49 
50         System.out.println("---------------公鑰校驗簽名------------------");
51         System.out.println("簽名原串:" + content);
52         System.out.println("簽名串:" + signstr);
53 
54         System.out.println("驗簽結果:" + RSASignature.doCheck(content, signstr, RSAEncrypt.loadPublicKeyByFile(filepath)));
55         System.out.println();
56     }
57 
58 }
View Code
相關文章
相關標籤/搜索