RSA算法是流行最廣泛的非對稱加密算法,也是唯一的基於因式分解的非對稱加密算法。相比DH算法,RSA算法更重要。
發展歷史
1978年MIT三位學者提出對稱加密算法:RSA算法,隨後RSA算法被廣泛應用。非對稱加密算法的破解一直受人關注:
- 1999年,RSA-144被成功破解;
- 2002年,RSA-158也被成功破解;
應用場景和特點
RSA的應用場景和DH算法一樣,密鑰協商
。但是RSA算法比DH算法簡單,沒有那麼複雜。但是DH算法的安全隱患在於,公鑰傳輸的過程中是容易泄露和被截獲的。
- RSA算法中,公鑰可以加密也可以解密,私鑰也是一樣的,也就是公私密鑰的性質是一樣的。
- RSA算法中,公鑰加密的數據只能用私鑰解密,私鑰加密的數據也僅能用公鑰解密;
- RSA算法,僅需要一套密鑰即可完成加解密操作;
- 公鑰密鑰長度比私鑰密鑰長度要小。
RSA算法不直接參與數據加密,而是參與對稱加密算法的密鑰交換工作,而且一般情況下,我們不需要自己編程。
一定要遵循:公鑰加密,私鑰解密;私鑰加密,公鑰解密的原則;
Java中算法實現
Java支持RSA算法,工作模式爲ECB模式,不能選擇,沒藥長度是512-65535,默認是1024,填充方式有多種可以選擇。
public class RSATest {
public static final String KEY_ALGORITHM = "RSA";
private static final int KEY_SIZE = 1024;
public static void main(String[] args) throws Exception {
// 1.產生密鑰對
KeyPair keyPair = initKey();
byte[] privateKey = keyPair.getPrivate().getEncoded();
byte[] publicKey = keyPair.getPublic().getEncoded();
log("Public Key : %s", toBase64(publicKey));
log("Private Key : %s", toBase64(privateKey));
String input = "要加密的數據";
// 2.私鑰加密
byte[] priKeyData = encrpty(getPrivateKey(privateKey), input.getBytes());
byte[] rs1 = decrpty(getPublicKey(publicKey), priKeyData);
log("私鑰加密:%s , 公鑰解密:%s ", toBase64(priKeyData), new String(rs1));
byte[] pubKeyData = encrpty(getPublicKey(publicKey), input.getBytes());
byte[] rs2 = decrpty(getPrivateKey(privateKey), pubKeyData);
log("公鑰加密:%s , 私鑰解密:%s ", toBase64(pubKeyData), new String(rs2));
}
private static KeyPair initKey() throws Exception {
KeyPairGenerator keyPairGr = KeyPairGenerator.getInstance(KEY_ALGORITHM);
keyPairGr.initialize(KEY_SIZE);
KeyPair keyPair = keyPairGr.generateKeyPair();
// RSAPublicKey
return keyPair;
}
private static PrivateKey getPrivateKey(byte[] priKey) throws Exception {
PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(priKey);
KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
PrivateKey privateKey = keyFactory.generatePrivate(pkcs8KeySpec);
return privateKey;
}
private static PublicKey getPublicKey(byte[] pubKey) throws Exception {
X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(pubKey);
KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
PublicKey publicKey = keyFactory.generatePublic(x509KeySpec);
return publicKey;
}
private static byte[] decrpty(Key key, byte[] data) throws Exception {
Cipher cipher = Cipher.getInstance(key.getAlgorithm());
cipher.init(Cipher.DECRYPT_MODE, key);
return cipher.doFinal(data);
}
private static byte[] encrpty(Key key, byte[] data) throws Exception {
Cipher cipher = Cipher.getInstance(key.getAlgorithm());
cipher.init(Cipher.ENCRYPT_MODE, key);
return cipher.doFinal(data);
}
private static void log(String tmp, Object... params) {
System.out.println(String.format(tmp, params));
}
private static String toBase64(byte[] data) {
return new String(Base64.getEncoder().encode(data));
}
}