1 importorg.apache.commons.codec.binary.Base64;2 importsun.misc.BASE64Decoder;3
4 importjavax.crypto.BadPaddingException;5 importjavax.crypto.Cipher;6 importjavax.crypto.IllegalBlockSizeException;7 importjavax.crypto.NoSuchPaddingException;8 import java.io.*;9 import java.security.*;10 importjava.security.interfaces.RSAPrivateKey;11 importjava.security.interfaces.RSAPublicKey;12 importjava.security.spec.InvalidKeySpecException;13 importjava.security.spec.PKCS8EncodedKeySpec;14 importjava.security.spec.X509EncodedKeySpec;15
16 /**
17 *
18 * 1.19 *
20 *21 *@authorPollyLuo22 *@version1.0.023 */24 public classRSAEncrypt {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 voidgenKeyPair(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, newSecureRandom());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 = newBase64();58 String publicKeyString = newString(base64.encode(publicKey.getEncoded()));59 //得到私钥字符串
60 String privateKeyString = newString(base64.encode(privateKey.getEncoded()));61 //将密钥对写入到文件
62 FileWriter pubfw = new FileWriter(filePath +PUBLIC_KEY);63 FileWriter prifw = new FileWriter(filePath +PRIVATE_KEY);64 BufferedWriter pubbw = newBufferedWriter(pubfw);65 BufferedWriter pribw = newBufferedWriter(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 *@parampath 公钥输入流83 *@throwsException 加载公钥时产生的异常84 */
85 public static String loadPublicKeyByFile(String path) throwsException {86 try{87 BufferedReader br = new BufferedReader(newFileReader(path88 +PUBLIC_KEY));89 String readLine = null;90 StringBuilder sb = newStringBuilder();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 returnsb.toString();101 } catch(IOException e) {102 throw new Exception("公钥数据流读取错误");103 } catch(NullPointerException e) {104 throw new Exception("公钥输入流为空");105 }106 }107
108 /**
109 * 从字符串中加载公钥110 *111 *@parampublicKeyStr 公钥数据字符串112 *@throwsException 加载公钥时产生的异常113 */
114 public staticRSAPublicKey loadPublicKeyByStr(String publicKeyStr)115 throwsException {116 try{117 BASE64Decoder base64 = newBASE64Decoder();118 byte[] buffer =base64.decodeBuffer(publicKeyStr);119 KeyFactory keyFactory = KeyFactory.getInstance("RSA");120 X509EncodedKeySpec keySpec = newX509EncodedKeySpec(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 *@parampath 私钥文件名135 *@return是否成功136 *@throwsException137 */
138 public static String loadPrivateKeyByFile(String path) throwsException {139 try{140 BufferedReader br = new BufferedReader(newFileReader(path141 +PRIVATE_KEY));142 String readLine = null;143 StringBuilder sb = newStringBuilder();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 returnsb.toString();154 } catch(IOException e) {155 throw new Exception("私钥数据读取错误");156 } catch(NullPointerException e) {157 throw new Exception("私钥输入流为空");158 }159 }160
161 public staticRSAPrivateKey loadPrivateKeyByStr(String privateKeyStr)162 throwsException {163 try{164 BASE64Decoder base64Decoder = newBASE64Decoder();165 byte[] buffer =base64Decoder.decodeBuffer(privateKeyStr);166 PKCS8EncodedKeySpec keySpec = newPKCS8EncodedKeySpec(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 *@parampublicKey 公钥182 *@paramplainTextData 明文数据183 *@return
184 *@throwsException 加密过程中的异常信息185 */
186 public static byte[] encrypt(RSAPublicKey publicKey, byte[] plainTextData)187 throwsException {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 returnoutput;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 *@paramprivateKey 私钥217 *@paramplainTextData 明文数据218 *@return
219 *@throwsException 加密过程中的异常信息220 */
221 public static byte[] encrypt(RSAPrivateKey privateKey, byte[] plainTextData)222 throwsException {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 returnoutput;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 *@paramprivateKey 私钥251 *@paramcipherData 密文数据252 *@return明文253 *@throwsException 解密过程中的异常信息254 */
255 public static byte[] decrypt(RSAPrivateKey privateKey, byte[] cipherData)256 throwsException {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 returnoutput;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 *@parampublicKey 公钥286 *@paramcipherData 密文数据287 *@return明文288 *@throwsException 解密过程中的异常信息289 */
290 public static byte[] decrypt(RSAPublicKey publicKey, byte[] cipherData)291 throwsException {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 returnoutput;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 *@paramdata 输入数据321 *@return十六进制内容322 */
323 public static String byteArrayToString(byte[] data) {324 StringBuilder stringBuilder = newStringBuilder();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 returnstringBuilder.toString();335 }336 }