本文做者:合肥工業大學 管理學院 錢洋 email:1563178220@qq.com 內容可能有不到之處,歡迎交流。java
未經本人容許禁止轉載。算法
RSA的應用
RSA是一種非對稱加密算法。如今,不少登錄表單的密碼的都採用RSA加密,例如京東中的登錄使用公鑰對密碼進行加密。apache
Base64編碼
apache.commons-codex包提供了許多編碼格式轉換,例如Base64。dom
如下爲Base64編碼表
使用apache.commons-codex進行Base64對字符串進行編碼與解碼的程序以下:函數
package com.qian.encoded;編碼
import org.apache.commons.codec.binary.Base64;加密
public class Base64Coded {
public static void main(String[] args) {
String string = "qianyang123";
//編碼
String encode = encode(string.getBytes());
System.out.println(string + "\t編碼後的字符串爲:" + encode);
//解碼
String decode = decode(encode.getBytes());
System.out.println(encode + "\t字符串解碼後爲:" + decode);
}
//base64 解碼
public static String decode(byte[] bytes) {
return new String(Base64.decodeBase64(bytes));
}
//base64 編碼
public static String encode(byte[] bytes) {
return new String(Base64.encodeBase64(bytes));
}
}.net
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
程序的輸出結果爲:code
qianyang123 編碼後的字符串爲:cWlhbnlhbmcxMjM=
cWlhbnlhbmcxMjM= 字符串解碼後爲:qianyang123對象
RSA加密與解密
使用RSA通常須要產生公鑰和私鑰,當採用公鑰加密時,使用私鑰解密;採用私鑰加密時,使用公鑰解密。如下爲Java程序:
package com.qian.encoded;
import org.apache.commons.codec.binary.Base64;
import javax.crypto.Cipher;
import java.security.KeyFactory;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.HashMap;
import java.util.Map;
public class RSAEncrypt {
private static Map<Integer, String> keyMap = new HashMap<Integer, String>(); //用於封裝隨機產生的公鑰與私鑰
public static void main(String[] args) throws Exception {
//生成公鑰和私鑰
genKeyPair();
//加密字符串
String message = "df723820";
System.out.println("隨機生成的公鑰爲:" + keyMap.get(0));
System.out.println("隨機生成的私鑰爲:" + keyMap.get(1));
String messageEn = encrypt(message,keyMap.get(0));
System.out.println(message + "\t加密後的字符串爲:" + messageEn);
String messageDe = decrypt(messageEn,keyMap.get(1));
System.out.println("還原後的字符串爲:" + messageDe);
}
/**
* 隨機生成密鑰對
* @throws NoSuchAlgorithmException
*/
public static void genKeyPair() throws NoSuchAlgorithmException {
// KeyPairGenerator類用於生成公鑰和私鑰對,基於RSA算法生成對象
KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance("RSA");
// 初始化密鑰對生成器,密鑰大小爲96-1024位
keyPairGen.initialize(1024,new SecureRandom());
// 生成一個密鑰對,保存在keyPair中
KeyPair keyPair = keyPairGen.generateKeyPair();
RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate(); // 獲得私鑰
RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic(); // 獲得公鑰
String publicKeyString = new String(Base64.encodeBase64(publicKey.getEncoded()));
// 獲得私鑰字符串
String privateKeyString = new String(Base64.encodeBase64((privateKey.getEncoded())));
// 將公鑰和私鑰保存到Map
keyMap.put(0,publicKeyString); //0表示公鑰
keyMap.put(1,privateKeyString); //1表示私鑰
}
/**
* RSA公鑰加密
*
* @param str
* 加密字符串
* @param publicKey
* 公鑰
* @return 密文
* @throws Exception
* 加密過程當中的異常信息
*/
public static String encrypt( String str, String publicKey ) throws Exception{
//base64編碼的公鑰
byte[] decoded = Base64.decodeBase64(publicKey);
RSAPublicKey pubKey = (RSAPublicKey) KeyFactory.getInstance("RSA").generatePublic(new X509EncodedKeySpec(decoded));
//RSA加密
Cipher cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.ENCRYPT_MODE, pubKey);
String outStr = Base64.encodeBase64String(cipher.doFinal(str.getBytes("UTF-8")));
return outStr;
}
/**
* RSA私鑰解密
*
* @param str
* 加密字符串
* @param privateKey
* 私鑰
* @return 銘文
* @throws Exception
* 解密過程當中的異常信息
*/
public static String decrypt(String str, String privateKey) throws Exception{
//64位解碼加密後的字符串
byte[] inputByte = Base64.decodeBase64(str.getBytes("UTF-8"));
//base64編碼的私鑰
byte[] decoded = Base64.decodeBase64(privateKey);
RSAPrivateKey priKey = (RSAPrivateKey) KeyFactory.getInstance("RSA").generatePrivate(new PKCS8EncodedKeySpec(decoded));
//RSA解密
Cipher cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.DECRYPT_MODE, priKey);
String outStr = new String(cipher.doFinal(inputByte));
return outStr;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
在程序中,咱們首先利用genKeyPair()函數生成公鑰和私鑰並將其保存到Map集合中。而後,基於產生的公鑰對明文進行加密。針對已經已經加密的密文,咱們再次使用私鑰解密,獲得明文。
上述程序的輸出結果爲:
隨機生成的公鑰爲:MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCG77PYUAcCpANyUmsHJfuDIia9FcITsuu9lnfbE2BbEwd4SOxPBFTwEWTZ9/e+mtjP97KFEBohGkwy+VHE5KocypBv0O7YgEevwMgpvxyYY0v104CB/k0yjCFV7lc7FxY5VgEKrMiXTIkMr1ukCnWVvapvRCS6IFcsT/kkjPgfDQIDAQAB 隨機生成的私鑰爲:MIICdwIBADANBgkqhkiG9w0BAQEFAASCAmEwggJdAgEAAoGBAIbvs9hQBwKkA3JSawcl+4MiJr0VwhOy672Wd9sTYFsTB3hI7E8EVPARZNn3976a2M/3soUQGiEaTDL5UcTkqhzKkG/Q7tiAR6/AyCm/HJhjS/XTgIH+TTKMIVXuVzsXFjlWAQqsyJdMiQyvW6QKdZW9qm9EJLogVyxP+SSM+B8NAgMBAAECgYEAhj0FH9dNghUE0MCpdS0WL/jTrRxuPQase6mrhyiZnUErF0EExf87OLE1MZr8voRx2UNEOBgyxmfREozyCfyqNg1OdGYEHSyuJ9wglkhq8GVYO8IzI29Mqej0MSprtsE0BPAKBHRU/DWP19ej5bv5ZnAhLs10K7uVEsuGwJJYcMECQQDibedUr7tnGfojyjFY0vCAaVwgS0vXfno7WQyAXUz0Fv8Uy1q9nyF0RrkeA8BOk7S4ljE77ufX0rr2qL7kHW8pAkEAmI718EnQCKKJUjrQUl4iG/lYoNwW2QnxTGZmESyFwkS95PTt8K4GVHpICqRNP1JJBNxVSEVts/eA4zrxPAoBRQJBAJxxEsOQJwq1B/5yVGXqWABgyyYE4AGjgRBAFkMaM3Dx8ouLdMZOi+6qbnwuW0/u/Y4LNzkRd13GWybQsBMrwwECQEULptmavpG55kaWIcS1n+BjSK59DcYrDs+SJK2vJdaXwA4IoEvmpyzCrypJ1EBNYIjXo61y5sSlxuqQua9/o7UCQGYdM3/mF/FEC3wxdfQq0Pw/Pwn8RQxg1natRfoTyzOJDfE/YUYGjIEe2pQtDI1s+IRCwrXOB0cySbpaSHCjr5U= df723820 加密後的字符串爲:HRMm2XsytNJjmnZgn+2pFZWyTn56tsp7/yII6jdo3Wb19uy8GFtFujMekcUWqwFsO9vbvUOyD21MgI85BOtD7tsHHlj5xdtPiFEHkY1qiWIHTPpxA+WICSlw9ZY4zY0IaoxhrMAb8c9ohsrbBbyGcmUSFFdZq8CuPfj99IDLLic= 還原後的字符串爲:df723820