赞
踩
当前使用的是Linux系统,已经按装使用OpenSSL软件包,
一、使用OpenSSL来生成私钥和公钥
1、执行命令openssl version -a 验证机器上已经安装openssl
1 |
|
运行结果:
2、生成私钥:这条命令让openssl随机生成了一份私钥,加密长度是1024位。加密长度是指理论上最大允许”被加密的信息“长度的限制,也就是明文的长度限制。随着这个参数的增大(比方说2048),允许的明文长度也会增加,但同时也会造成计算复杂度的极速增长。一般推荐的长度就是2048位
1 |
|
运行结果:
生产私钥文件:rsa_private_key.pem,内容都是标准的ASCII字符,开头一行和结尾一行有明显的标记,真正的私钥数据是中间的不规则字符
3、根据私钥生产公钥:rsa_public_key.pem or private_key.der
1 |
|
运行结果:
公钥内容:
注意:此时的私钥还不能直接被使用,需要进行PKCS#8编码:
4、PKCS#8编码:指明输入私钥文件为rsa_private_key.pem,输出私钥文件为pkcs8_rsa_private_key.pem,不采用任何二次加密(-nocrypt)
1 |
|
openssl rsa -in private_key.pem -pubout -outform DER -out public_key.der
至此:可用的密钥对已经生成好了,私钥使用pkcs8_rsa_private_key.pem,公钥采用rsa_public_key.pem
二、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 }
读取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 }
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 }
测试方法:
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 }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。