RSA是什麼:RSA公鑰加密算法是1977年由Ron Rivest、Adi Shamirh和LenAdleman在(美國麻省理工學院)開發的。RSA取名來自開發他們三者的名字。RSA是目前最有影響力的公鑰加密算法,它可以抵抗到目前爲止已知的全部密碼攻擊,已被ISO推薦爲公鑰數據加密標準。目前該加密方式普遍用於網上銀行、數字簽名等場合。RSA算法基於一個十分簡單的數論事實:將兩個大素數相乘十分容易,但那時想要對其乘積進行因式分解卻極其困難,所以能夠將乘積公開做爲加密密鑰。html
OpenSSL是什麼:衆多的密碼算法、公鑰基礎設施標準以及SSL協議,或許這些有趣的功能會讓你產生實現全部這些算法和標準的想法。果然如此,在對你表示敬佩的同時,仍是忍不住提醒你:這是一個使人望而生畏的過程。這個工做再也不是簡單的讀懂幾本密碼學專著和協議文檔那麼簡單,而是要理解全部這些算法、標準和協議文檔的每個細節,並用你可能很熟悉的C語言字符一個一個去實現這些定義和過程。咱們不知道你將須要多少時間來完成這項有趣而可怕的工做,但確定不是一年兩年的問題。OpenSSL就是由Eric A. Young和Tim J. Hudson兩位絕世大好人自1995年就開始編寫的集合衆多安全算法的算法集合。經過命令或者開發庫,咱們能夠輕鬆實現標準的公開算法應用。java
下面將介紹如何生成和使用祕鑰。算法
1、使用OpenSSL來生成私鑰和公鑰apache
先驗證系統上是否已經安裝OpenSSL工具,Linux系統默認安裝,但Windows默認沒安裝,需自行下載安裝。請參考:Windows安裝openssl安全
λ openssl.exe version -a OpenSSL 1.1.0e 16 Feb 2017 built on: reproducible build, date unspecified platform: compiler: cl " "VC-WIN64A OPENSSLDIR: "C:\Program Files\Common Files\SSL" ENGINESDIR: "C:\Program Files\OpenSSL\lib\engines-1_1"
先來生成私鑰:app
λ openssl genrsa -out rsa_private_key.pem 1024 Generating RSA private key, 1024 bit long modulus ....................................++++++ ........++++++ e is 65537 (0x010001)
這條命令讓openssl隨機生成了一份私鑰,加密長度是1024位。加密長度是指理論上最大容許」被加密的信息「長度的限制,也就是明文的長度限制。隨着這個參數的增大(比方說2048),容許的明文長度也會增長,但同時也會形成計算複雜度的極速增加。通常推薦的長度就是1024位(128字節)。dom
咱們來看一下私鑰的內容:ide
-----BEGIN RSA PRIVATE KEY----- MIICWwIBAAKBgQDKeYC1p4iE7koV4JOlr+doVwIyhcI3q+q/MkBtPPN/w4J/2h3U LqaKXb54Fs8ON9rDFEVLShtbxX6fYx3vBEArrd516KWYYcx5la1vr1KHFtJScN/p 3u0vwSj7ElE8U7aZwtkXL7iqGGLOyM1wQNqyIMi7nayPeOP2RzSYy2uUQQIDAQAB AoGAXWteJXJdHOhNKnbp6MKWhJ/Qlbr9d25M61amP0CmIMb2SUM8DBBSKvlBzmrH sgm3V9bcefaBVQB0gdnbj9JoQGzTOVNqVTVFg46a99uNpVja3HWdvZWDs4YKN4cE DGhHxu5DeyV/K4r3Paz/0mSBAu3Sn0l6ROejXX2GnKZFAAECQQDqjUhLSiTVAJfn rukJxEEJcvT0ELBxEu0OqiUNZCI2tbwWAP+KcZTJdJq5LR0O/ruFoUM+TskM+27y SrDuFLQBAkEA3P1PoFcYL7rs3vVG6LJZTNDz/rrG3wjMelVFUm3X7AiTqeChmh3Y HRvhoeRdP/O1Dc6MkmvKtMhmAFX3ZqngQQJASP38sIl7Wtoba9tP5F0xzCn9NvL2 pcm5AiZK75bo2tPFm6dl3wSnw+XIvLXgZCk73EMqNPq5sJOSnE5IL188AQJAL39q i+XsVuXwX4OMeBtNQktvBgMTF4EGogyN18ewLxUw18RmN3/OoYMKngc9W69/7LXG VPpCGVUxR0Uy5agBgQJAGUa3uV3UTGBSxbbtII+9NRmlFTh+EsamP/iPErCr+pmI os8GvX7q24bkYvVddXu4hwLaplXrwTjNaAs1w390IQ== -----END RSA PRIVATE KEY-----
內容都是標準的ASCII字符,開頭一行和結尾一行有明顯的標記,真正的私鑰數據是中間的不規則字符。工具
密鑰文件最終將數據經過Base64編碼進行存儲。能夠看到上述密鑰文件內容每一行的長度都很規律。這是因爲RFC2045中規定:The encoded output stream must be represented in lines of no more than 76 characters each。也就是說Base64編碼的數據每行最多不超過76字符,對於超長數據須要按行分割。測試
接下來根據私鑰生成公鑰:
λ openssl rsa -in rsa_private_key.pem -out rsa_public_key.pem -pubout writing RSA key
再來看一下公鑰的內容:
-----BEGIN PUBLIC KEY----- MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDKeYC1p4iE7koV4JOlr+doVwIy hcI3q+q/MkBtPPN/w4J/2h3ULqaKXb54Fs8ON9rDFEVLShtbxX6fYx3vBEArrd51 6KWYYcx5la1vr1KHFtJScN/p3u0vwSj7ElE8U7aZwtkXL7iqGGLOyM1wQNqyIMi7 nayPeOP2RzSYy2uUQQIDAQAB -----END PUBLIC KEY-----
這時候的私鑰還不能直接被使用,須要進行PKCS#8編碼:
λ openssl pkcs8 -topk8 -in rsa_private_key.pem -out pkcs8_rsa_private_key.pem -nocrypt
命令中指明瞭輸入私鑰文件爲rsa_private_key.pem,輸出私鑰文件爲pkcs8_rsa_private_key.pem,不採用任何二次加密(-nocrypt)
若是不進行PKCS#8編碼,Java在使用時會報錯:
java.security.spec.InvalidKeySpecException: java.security.InvalidKeyException: IOException : algid parse error, not a sequence
再來看一下,編碼後的私鑰文件是否是和以前的私鑰文件不一樣了:
-----BEGIN PRIVATE KEY----- MIICdQIBADANBgkqhkiG9w0BAQEFAASCAl8wggJbAgEAAoGBAMp5gLWniITuShXg k6Wv52hXAjKFwjer6r8yQG0883/Dgn/aHdQupopdvngWzw432sMURUtKG1vFfp9j He8EQCut3nXopZhhzHmVrW+vUocW0lJw3+ne7S/BKPsSUTxTtpnC2RcvuKoYYs7I zXBA2rIgyLudrI944/ZHNJjLa5RBAgMBAAECgYBda14lcl0c6E0qdunowpaEn9CV uv13bkzrVqY/QKYgxvZJQzwMEFIq+UHOaseyCbdX1tx59oFVAHSB2duP0mhAbNM5 U2pVNUWDjpr3242lWNrcdZ29lYOzhgo3hwQMaEfG7kN7JX8rivc9rP/SZIEC7dKf SXpE56NdfYacpkUAAQJBAOqNSEtKJNUAl+eu6QnEQQly9PQQsHES7Q6qJQ1kIja1 vBYA/4pxlMl0mrktHQ7+u4WhQz5OyQz7bvJKsO4UtAECQQDc/U+gVxgvuuze9Ubo sllM0PP+usbfCMx6VUVSbdfsCJOp4KGaHdgdG+Gh5F0/87UNzoySa8q0yGYAVfdm qeBBAkBI/fywiXta2htr20/kXTHMKf028valybkCJkrvluja08Wbp2XfBKfD5ci8 teBkKTvcQyo0+rmwk5KcTkgvXzwBAkAvf2qL5exW5fBfg4x4G01CS28GAxMXgQai DI3Xx7AvFTDXxGY3f86hgwqeBz1br3/stcZU+kIZVTFHRTLlqAGBAkAZRre5XdRM YFLFtu0gj701GaUVOH4SxqY/+I8SsKv6mYiizwa9furbhuRi9V11e7iHAtqmVevB OM1oCzXDf3Qh -----END PRIVATE KEY-----
至此,可用的密鑰對已經生成好了,私鑰使用pkcs8_rsa_private_key.pem,公鑰採用rsa_public_key.pem。
最近又遇到RSA加密的需求了,並且對方要求只能使用第一步生成的未通過PKCS#8編碼的私鑰文件。後來查看相關文獻得知第一步生成的私鑰文件編碼是PKCS#1格式,這種格式Java實際上是支持的,只不過多寫兩行代碼而已:
RSAPrivateKeyStructure asn1PrivKey = new RSAPrivateKeyStructure((ASN1Sequence) ASN1Sequence.fromByteArray(priKeyData)); RSAPrivateKeySpec rsaPrivKeySpec = new RSAPrivateKeySpec(asn1PrivKey.getModulus(), asn1PrivKey.getPrivateExponent()); KeyFactory keyFactory= KeyFactory.getInstance("RSA"); PrivateKey priKey= keyFactory.generatePrivate(rsaPrivKeySpec);
首先將PKCS#1的私鑰文件讀取出來(注意去掉減號開頭的註釋內容),而後使用Base64解碼讀出的字符串,便獲得priKeyData,也就是第一行代碼中的參數。最後一行獲得了私鑰。接下來的用法就沒什麼區別了。
RSA加密解密類:
1 import java.io.BufferedReader; 2 import java.io.BufferedWriter; 3 import java.io.FileReader; 4 import java.io.FileWriter; 5 import java.io.IOException; 6 import java.security.InvalidKeyException; 7 import java.security.KeyFactory; 8 import java.security.KeyPair; 9 import java.security.KeyPairGenerator; 10 import java.security.NoSuchAlgorithmException; 11 import java.security.SecureRandom; 12 13 import java.security.interfaces.RSAPrivateKey; 14 import java.security.interfaces.RSAPublicKey; 15 import java.security.spec.InvalidKeySpecException; 16 import java.security.spec.PKCS8EncodedKeySpec; 17 import java.security.spec.X509EncodedKeySpec; 18 19 import javax.crypto.BadPaddingException; 20 import javax.crypto.Cipher; 21 import javax.crypto.IllegalBlockSizeException; 22 import javax.crypto.NoSuchPaddingException; 23 24 import org.apache.commons.codec.binary.Base64; 25 26 public class RSAEncrypt { 27 /** 28 * 字節數據轉字符串專用集合 29 */ 30 private static final char[] HEX_CHAR = { '0', '1', '2', '3', '4', '5', '6', 31 '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' }; 32 33 /** 34 * 隨機生成密鑰對 35 */ 36 public static void genKeyPair(String filePath) { 37 // KeyPairGenerator類用於生成公鑰和私鑰對,基於RSA算法生成對象 38 KeyPairGenerator keyPairGen = null; 39 try { 40 keyPairGen = KeyPairGenerator.getInstance("RSA"); 41 } catch (NoSuchAlgorithmException e) { 42 e.printStackTrace(); 43 } 44 // 初始化密鑰對生成器,密鑰大小爲96-1024位 45 keyPairGen.initialize(1024,new SecureRandom()); 46 // 生成一個密鑰對,保存在keyPair中 47 KeyPair keyPair = keyPairGen.generateKeyPair(); 48 // 獲得私鑰 49 RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate(); 50 // 獲得公鑰 51 RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic(); 52 try { 53 // 獲得公鑰字符串 54 Base64 base64 = new Base64(); 55 String publicKeyString = new String(base64.encode(publicKey.getEncoded())); 56 // 獲得私鑰字符串 57 String privateKeyString = new String(base64.encode(privateKey.getEncoded())); 58 // 將密鑰對寫入到文件 59 FileWriter pubfw = new FileWriter(filePath + "/publicKey.keystore"); 60 FileWriter prifw = new FileWriter(filePath + "/privateKey.keystore"); 61 BufferedWriter pubbw = new BufferedWriter(pubfw); 62 BufferedWriter pribw = new BufferedWriter(prifw); 63 pubbw.write(publicKeyString); 64 pribw.write(privateKeyString); 65 pubbw.flush(); 66 pubbw.close(); 67 pubfw.close(); 68 pribw.flush(); 69 pribw.close(); 70 prifw.close(); 71 } catch (Exception e) { 72 e.printStackTrace(); 73 } 74 } 75 76 /** 77 * 從文件中輸入流中加載公鑰 78 * 79 * @param in 80 * 公鑰輸入流 81 * @throws Exception 82 * 加載公鑰時產生的異常 83 */ 84 public static String loadPublicKeyByFile(String path) throws Exception { 85 try { 86 BufferedReader br = new BufferedReader(new FileReader(path 87 + "/publicKey.keystore")); 88 String readLine = null; 89 StringBuilder sb = new StringBuilder(); 90 while ((readLine = br.readLine()) != null) { 91 sb.append(readLine); 92 } 93 br.close(); 94 return sb.toString(); 95 } catch (IOException e) { 96 throw new Exception("公鑰數據流讀取錯誤"); 97 } catch (NullPointerException e) { 98 throw new Exception("公鑰輸入流爲空"); 99 } 100 } 101 102 /** 103 * 從字符串中加載公鑰 104 * 105 * @param publicKeyStr 106 * 公鑰數據字符串 107 * @throws Exception 108 * 加載公鑰時產生的異常 109 */ 110 public static RSAPublicKey loadPublicKeyByStr(String publicKeyStr) 111 throws Exception { 112 try { 113 Base64 base64 = new Base64(); 114 byte[] buffer = base64.decode(publicKeyStr); 115 KeyFactory keyFactory = KeyFactory.getInstance("RSA"); 116 X509EncodedKeySpec keySpec = new X509EncodedKeySpec(buffer); 117 return (RSAPublicKey) keyFactory.generatePublic(keySpec); 118 } catch (NoSuchAlgorithmException e) { 119 throw new Exception("無此算法"); 120 } catch (InvalidKeySpecException e) { 121 throw new Exception("公鑰非法"); 122 } catch (NullPointerException e) { 123 throw new Exception("公鑰數據爲空"); 124 } 125 } 126 127 /** 128 * 從文件中加載私鑰 129 * 130 * @param keyFileName 131 * 私鑰文件名 132 * @return 是否成功 133 * @throws Exception 134 */ 135 public static String loadPrivateKeyByFile(String path) throws Exception { 136 try { 137 BufferedReader br = new BufferedReader(new FileReader(path 138 + "/privateKey.keystore")); 139 String readLine = null; 140 StringBuilder sb = new StringBuilder(); 141 while ((readLine = br.readLine()) != null) { 142 sb.append(readLine); 143 } 144 br.close(); 145 return sb.toString(); 146 } catch (IOException e) { 147 throw new Exception("私鑰數據讀取錯誤"); 148 } catch (NullPointerException e) { 149 throw new Exception("私鑰輸入流爲空"); 150 } 151 } 152 153 public static RSAPrivateKey loadPrivateKeyByStr(String privateKeyStr) 154 throws Exception { 155 try { 156 Base64 base64 = new Base64(); 157 byte[] buffer = base64.decode(privateKeyStr); 158 PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(buffer); 159 KeyFactory keyFactory = KeyFactory.getInstance("RSA"); 160 return (RSAPrivateKey) keyFactory.generatePrivate(keySpec); 161 } catch (NoSuchAlgorithmException e) { 162 throw new Exception("無此算法"); 163 } catch (InvalidKeySpecException e) { 164 throw new Exception("私鑰非法"); 165 } catch (NullPointerException e) { 166 throw new Exception("私鑰數據爲空"); 167 } 168 } 169 170 /** 171 * 公鑰加密過程 172 * 173 * @param publicKey 174 * 公鑰 175 * @param plainTextData 176 * 明文數據 177 * @return 178 * @throws Exception 179 * 加密過程當中的異常信息 180 */ 181 public static byte[] encrypt(RSAPublicKey publicKey, byte[] plainTextData) 182 throws Exception { 183 if (publicKey == null) { 184 throw new Exception("加密公鑰爲空, 請設置"); 185 } 186 Cipher cipher = null; 187 try { 188 // 使用默認RSA 189 cipher = Cipher.getInstance("RSA"); 190 // cipher= Cipher.getInstance("RSA", new BouncyCastleProvider()); 191 cipher.init(Cipher.ENCRYPT_MODE, publicKey); 192 byte[] output = cipher.doFinal(plainTextData); 193 return output; 194 } catch (NoSuchAlgorithmException e) { 195 throw new Exception("無此加密算法"); 196 } catch (NoSuchPaddingException e) { 197 e.printStackTrace(); 198 return null; 199 } catch (InvalidKeyException e) { 200 throw new Exception("加密公鑰非法,請檢查"); 201 } catch (IllegalBlockSizeException e) { 202 throw new Exception("明文長度非法"); 203 } catch (BadPaddingException e) { 204 throw new Exception("明文數據已損壞"); 205 } 206 } 207 208 /** 209 * 私鑰加密過程 210 * 211 * @param privateKey 212 * 私鑰 213 * @param plainTextData 214 * 明文數據 215 * @return 216 * @throws Exception 217 * 加密過程當中的異常信息 218 */ 219 public static byte[] encrypt(RSAPrivateKey privateKey, byte[] plainTextData) 220 throws Exception { 221 if (privateKey == null) { 222 throw new Exception("加密私鑰爲空, 請設置"); 223 } 224 Cipher cipher = null; 225 try { 226 // 使用默認RSA 227 cipher = Cipher.getInstance("RSA"); 228 cipher.init(Cipher.ENCRYPT_MODE, privateKey); 229 byte[] output = cipher.doFinal(plainTextData); 230 return output; 231 } catch (NoSuchAlgorithmException e) { 232 throw new Exception("無此加密算法"); 233 } catch (NoSuchPaddingException e) { 234 e.printStackTrace(); 235 return null; 236 } catch (InvalidKeyException e) { 237 throw new Exception("加密私鑰非法,請檢查"); 238 } catch (IllegalBlockSizeException e) { 239 throw new Exception("明文長度非法"); 240 } catch (BadPaddingException e) { 241 throw new Exception("明文數據已損壞"); 242 } 243 } 244 245 /** 246 * 私鑰解密過程 247 * 248 * @param privateKey 249 * 私鑰 250 * @param cipherData 251 * 密文數據 252 * @return 明文 253 * @throws Exception 254 * 解密過程當中的異常信息 255 */ 256 public static byte[] decrypt(RSAPrivateKey privateKey, byte[] cipherData) 257 throws Exception { 258 if (privateKey == null) { 259 throw new Exception("解密私鑰爲空, 請設置"); 260 } 261 Cipher cipher = null; 262 try { 263 // 使用默認RSA 264 cipher = Cipher.getInstance("RSA"); 265 // cipher= Cipher.getInstance("RSA", new BouncyCastleProvider()); 266 cipher.init(Cipher.DECRYPT_MODE, privateKey); 267 byte[] output = cipher.doFinal(cipherData); 268 return output; 269 } catch (NoSuchAlgorithmException e) { 270 throw new Exception("無此解密算法"); 271 } catch (NoSuchPaddingException e) { 272 e.printStackTrace(); 273 return null; 274 } catch (InvalidKeyException e) { 275 throw new Exception("解密私鑰非法,請檢查"); 276 } catch (IllegalBlockSizeException e) { 277 throw new Exception("密文長度非法"); 278 } catch (BadPaddingException e) { 279 throw new Exception("密文數據已損壞"); 280 } 281 } 282 283 /** 284 * 公鑰解密過程 285 * 286 * @param publicKey 287 * 公鑰 288 * @param cipherData 289 * 密文數據 290 * @return 明文 291 * @throws Exception 292 * 解密過程當中的異常信息 293 */ 294 public static byte[] decrypt(RSAPublicKey publicKey, byte[] cipherData) 295 throws Exception { 296 if (publicKey == null) { 297 throw new Exception("解密公鑰爲空, 請設置"); 298 } 299 Cipher cipher = null; 300 try { 301 // 使用默認RSA 302 cipher = Cipher.getInstance("RSA"); 303 // cipher= Cipher.getInstance("RSA", new BouncyCastleProvider()); 304 cipher.init(Cipher.DECRYPT_MODE, publicKey); 305 byte[] output = cipher.doFinal(cipherData); 306 return output; 307 } catch (NoSuchAlgorithmException e) { 308 throw new Exception("無此解密算法"); 309 } catch (NoSuchPaddingException e) { 310 e.printStackTrace(); 311 return null; 312 } catch (InvalidKeyException e) { 313 throw new Exception("解密公鑰非法,請檢查"); 314 } catch (IllegalBlockSizeException e) { 315 throw new Exception("密文長度非法"); 316 } catch (BadPaddingException e) { 317 throw new Exception("密文數據已損壞"); 318 } 319 } 320 321 /** 322 * 字節數據轉十六進制字符串 323 * 324 * @param data 325 * 輸入數據 326 * @return 十六進制內容 327 */ 328 public static String byteArrayToString(byte[] data) { 329 StringBuilder stringBuilder = new StringBuilder(); 330 for (int i = 0; i < data.length; i++) { 331 // 取出字節的高四位 做爲索引獲得相應的十六進制標識符 注意無符號右移 332 stringBuilder.append(HEX_CHAR[(data[i] & 0xf0) >>> 4]); 333 // 取出字節的低四位 做爲索引獲得相應的十六進制標識符 334 stringBuilder.append(HEX_CHAR[(data[i] & 0x0f)]); 335 if (i < data.length - 1) { 336 stringBuilder.append(' '); 337 } 338 } 339 return stringBuilder.toString(); 340 } 341 }
簽名及校驗類:
1 import java.security.KeyFactory; 2 import java.security.PrivateKey; 3 import java.security.PublicKey; 4 import java.security.spec.PKCS8EncodedKeySpec; 5 import java.security.spec.X509EncodedKeySpec; 6 7 import org.apache.commons.codec.binary.Base64; 8 9 /** 10 * RSA簽名驗籤類 11 */ 12 public class RSASignature { 13 14 /** 15 * 簽名算法 16 */ 17 public static final String SIGN_ALGORITHMS = "SHA1WithRSA"; 18 19 /** 20 * RSA簽名 21 * 22 * @param content 23 * 待簽名數據 24 * @param privateKey 25 * 商戶私鑰 26 * @param encode 27 * 字符集編碼 28 * @return 簽名值 29 */ 30 public static String sign(String content, String privateKey, String encode) { 31 try { 32 Base64 base64 = new Base64(); 33 PKCS8EncodedKeySpec priPKCS8 = new PKCS8EncodedKeySpec(base64.decode(privateKey)); 34 35 KeyFactory keyf = KeyFactory.getInstance("RSA"); 36 PrivateKey priKey = keyf.generatePrivate(priPKCS8); 37 38 java.security.Signature signature = java.security.Signature.getInstance(SIGN_ALGORITHMS); 39 40 signature.initSign(priKey); 41 signature.update(content.getBytes(encode)); 42 43 byte[] signed = signature.sign(); 44 45 return new String(base64.encode(signed)); 46 } catch (Exception e) { 47 e.printStackTrace(); 48 } 49 50 return null; 51 } 52 53 public static String sign(String content, String privateKey) { 54 try { 55 Base64 base64 = new Base64(); 56 PKCS8EncodedKeySpec priPKCS8 = new PKCS8EncodedKeySpec(base64.decode(privateKey)); 57 KeyFactory keyf = KeyFactory.getInstance("RSA"); 58 PrivateKey priKey = keyf.generatePrivate(priPKCS8); 59 java.security.Signature signature = java.security.Signature.getInstance(SIGN_ALGORITHMS); 60 signature.initSign(priKey); 61 signature.update(content.getBytes()); 62 byte[] signed = signature.sign(); 63 return new String(base64.encode(signed)); 64 } catch (Exception e) { 65 e.printStackTrace(); 66 } 67 return null; 68 } 69 70 /** 71 * RSA驗簽名檢查 72 * 73 * @param content 74 * 待簽名數據 75 * @param sign 76 * 簽名值 77 * @param publicKey 78 * 分配給開發商公鑰 79 * @param encode 80 * 字符集編碼 81 * @return 布爾值 82 */ 83 public static boolean doCheck(String content, String sign, String publicKey, String encode) { 84 try { 85 KeyFactory keyFactory = KeyFactory.getInstance("RSA"); 86 Base64 base64 = new Base64(); 87 byte[] encodedKey = base64.decode(publicKey); 88 PublicKey pubKey = keyFactory.generatePublic(new X509EncodedKeySpec(encodedKey)); 89 90 java.security.Signature signature = java.security.Signature.getInstance(SIGN_ALGORITHMS); 91 92 signature.initVerify(pubKey); 93 signature.update(content.getBytes(encode)); 94 95 boolean bverify = signature.verify(base64.decode(sign)); 96 return bverify; 97 98 } catch (Exception e) { 99 e.printStackTrace(); 100 } 101 102 return false; 103 } 104 105 public static boolean doCheck(String content, String sign, String publicKey) { 106 try { 107 KeyFactory keyFactory = KeyFactory.getInstance("RSA"); 108 Base64 base64 = new Base64(); 109 byte[] encodedKey = base64.decode(publicKey); 110 PublicKey pubKey = keyFactory.generatePublic(new X509EncodedKeySpec(encodedKey)); 111 112 java.security.Signature signature = java.security.Signature.getInstance(SIGN_ALGORITHMS); 113 114 signature.initVerify(pubKey); 115 signature.update(content.getBytes()); 116 117 boolean bverify = signature.verify(base64.decode(sign)); 118 return bverify; 119 120 } catch (Exception e) { 121 e.printStackTrace(); 122 } 123 124 return false; 125 } 126 127 }
最後是一個MainTest:
1 import org.apache.commons.codec.binary.Base64; 2 3 public class MainTest { 4 5 public static void main(String[] args) throws Exception { 6 String filepath = "G:/tmp/"; 7 8 // RSAEncrypt.genKeyPair(filepath); 9 10 Base64 base64 = new Base64(); 11 12 System.out.println("--------------公鑰加密私鑰解密過程-------------------"); 13 String plainText = "ihep_公鑰加密私鑰解密"; 14 // 公鑰加密過程 15 byte[] cipherData = RSAEncrypt.encrypt(RSAEncrypt.loadPublicKeyByStr(RSAEncrypt.loadPublicKeyByFile(filepath)), 16 plainText.getBytes()); 17 String cipher = new String(base64.encode(cipherData)); 18 // 私鑰解密過程 19 byte[] res = RSAEncrypt.decrypt(RSAEncrypt.loadPrivateKeyByStr(RSAEncrypt.loadPrivateKeyByFile(filepath)), 20 base64.decode(cipher)); 21 String restr = new String(res); 22 System.out.println("原文:" + plainText); 23 System.out.println("加密:" + cipher); 24 System.out.println("解密:" + restr); 25 System.out.println(); 26 27 System.out.println("--------------私鑰加密公鑰解密過程-------------------"); 28 plainText = "ihep_私鑰加密公鑰解密"; 29 // 私鑰加密過程 30 cipherData = RSAEncrypt.encrypt(RSAEncrypt.loadPrivateKeyByStr(RSAEncrypt.loadPrivateKeyByFile(filepath)), 31 plainText.getBytes()); 32 cipher = new String(base64.encode(cipherData)); 33 // 公鑰解密過程 34 res = RSAEncrypt.decrypt(RSAEncrypt.loadPublicKeyByStr(RSAEncrypt.loadPublicKeyByFile(filepath)), 35 base64.decode(cipher)); 36 restr = new String(res); 37 System.out.println("原文:" + plainText); 38 System.out.println("加密:" + cipher); 39 System.out.println("解密:" + restr); 40 System.out.println(); 41 42 System.out.println("---------------私鑰簽名過程------------------"); 43 String content = "ihep_這是用於簽名的原始數據"; 44 String signstr = RSASignature.sign(content, RSAEncrypt.loadPrivateKeyByFile(filepath)); 45 System.out.println("簽名原串:" + content); 46 System.out.println("簽名串:" + signstr); 47 System.out.println(); 48 49 System.out.println("---------------公鑰校驗簽名------------------"); 50 System.out.println("簽名原串:" + content); 51 System.out.println("簽名串:" + signstr); 52 53 System.out.println("驗簽結果:" + RSASignature.doCheck(content, signstr, RSAEncrypt.loadPublicKeyByFile(filepath))); 54 System.out.println(); 55 56 } 57 }
參考:
http://blog.csdn.net/chaijunkun/article/details/7275632
http://blog.csdn.net/wangqiuyun/article/details/42143957