首先RSA是一個非對稱的加密算法,所以在使用該算法加密解密之前,必須先行生成密鑰對,包括公鑰和私鑰
JDK中提供了生成密鑰對的類KeyPairGenerator,實例如下:
public static Map<String, Object> genKeyPair() throws Exception {
// 獲取公鑰私鑰密鑰對的生成器
KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA");
// 初始化確定密鑰大小的密鑰生成器
kpg.initialize(1024);
// 生成密鑰對
KeyPair kp = kpg.generateKeyPair();
RSAPublicKey publicKey = (RSAPublicKey) kp.getPublic();
RSAPrivateKey privateKey = (RSAPrivateKey) kp.getPrivate();
Map<String, Object> keyMap = new HashMap<String, Object>();
keyMap.put(PUBLIC_KEY, publicKey);
keyMap.put(PRIVATE_KEY, privateKey);
return keyMap;
}
以上這段代碼返回的是一個Map類型的數據,其中存儲了公鑰和私鑰
當你完成了密鑰對的生成之後,你就可以將公鑰公開出去了,讓相關的加密程序通過該公鑰對實施RSA加密
public static byte[] encryptByPublicKey(byte[] data, String publicKey)
throws Exception {
//data即是待加密的數據String.getBytes即可
byte[] keyBytes = Base64Utils.decode(publicKey);
//根據指定的編碼密鑰創建一個新的X509EncodedKeySpec
X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(keyBytes);
KeyFactory keyFactory = KeyFactory.getInstance(ENCRYPT_ALGORITHM);
//根據提供的密鑰規范生成公鑰對象
Key publicK = keyFactory.generatePublic(x509KeySpec);
// 對數據加密
Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
//用密鑰初始化加密模式的cipher,所有後面的doFinal方法做的是加密
cipher.init(Cipher.ENCRYPT_MODE, publicK);
int inputLen = data.length;
ByteArrayOutputStream out = new ByteArrayOutputStream();
int offSet = 0;
byte[] cache;
int i = 0;
// 對數據分段加密
while (inputLen - offSet > 0) {
if (inputLen - offSet > MAX_ENCRYPT_BLOCK) {//一次加密的字節長度
cache = cipher.doFinal(data, offSet, MAX_ENCRYPT_BLOCK);
} else {
cache = cipher.doFinal(data, offSet, inputLen - offSet);
}
out.write(cache, 0, cache.length);
i++;
offSet = i * MAX_ENCRYPT_BLOCK;
}
byte[] encryptedData = out.toByteArray();
out.close();
return encryptedData;
}
加密完成之後通過自己的私鑰對密文進行解密
public static byte[] decryptByPrivateKey(byte[] data, String privateKey)
throws Exception {
byte[] keyBytes = Base64Utils.decode(privateKey);
PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(keyBytes);
KeyFactory keyFactory = KeyFactory.getInstance(ENCRYPT_ALGORITHM);
Key privateK = keyFactory.generatePrivate(pkcs8KeySpec);
Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
cipher.init(Cipher.DECRYPT_MODE, privateK);
int inputLen = data.length;
ByteArrayOutputStream out = new ByteArrayOutputStream();
int offSet = 0;
byte[] cache;
int i = 0;
// 對數據分段解密
while (inputLen - offSet > 0) {
if (inputLen - offSet > MAX_DECRYPT_BLOCK) {
cache = cipher.doFinal(data, offSet, MAX_DECRYPT_BLOCK);
} else {
cache = cipher.doFinal(data, offSet, inputLen - offSet);
}
out.write(cache, 0, cache.length);
i++;
offSet = i * MAX_DECRYPT_BLOCK;
}
byte[] decryptedData = out.toByteArray();
out.close();
return decryptedData;
}
生成密鑰對:
try {
Map<String, Object> keyMap = RSAUtils.genKeyPair();
publicKey = RSAUtils.getPublicKey(keyMap);
privateKey = RSAUtils.getPrivateKey(keyMap);
System.out.println("公鑰-->" + publicKey);
System.out.println("私鑰-->" + privateKey);
} catch (Exception e) {
e.printStackTrace();
}
運行結果展示:
公鑰-->MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCjJOdVRlDN/5nWHmpFtc9XffgmT2SAj7b+yBk55HSr1iQQt5k8/4O5qdnk3qxhgIgWuSyDpxR2FK5dzfXsomjc0L2CZGaStAkbbvw1wbOSYo11cxNpkphn3PIVbuBxrpEuCJ4HrMKTuBk662aA0ysxy2/BrK4NXxtRlMxI+/BYsQIDAQAB
私鑰-->MIICdwIBADANBgkqhkiG9w0BAQEFAASCAmEwggJdAgEAAoGBAKMk51VGUM3/mdYeakW1z1d9+CZPZICPtv7IGTnkdKvWJBC3mTz/g7mp2eTerGGAiBa5LIOnFHYUrl3N9eyiaNzQvYJkZpK0CRtu/DXBs5JijXVzE2mSmGfc8hVu4HGukS4IngeswpO4GTrrZoDTKzHLb8Gsrg1fG1GUzEj78FixAgMBAAECgYBoQPTzsXOBsI0GH3maAoz1RDKHiMSYwz4Vopk8PZmxFa8GX801BbOPudLcRs+xnwlYPA0ONH8G1kB3AV7eUQrgxjHzqk61ahfbZ7w2yJl326Uag+q7SZI3bxoLKeqhCSD6GggvS9pSEgxu9u21GABxrYSGeRQe42sLLNpG8YKmAQJBAPv8j8MBMip+MhNYKMvPlmzA0/nUzLBLgZraHT0UMupEy6BHIYQnwXaabChs3QLrCMRt7payIK9CjO53oJPrrVkCQQClvhmgvursiUOiAzjkxgE11IPhw6FOx4nf/Om+jNnDEEO6VV//LNqwadKas1f7JwO6VyIsqJitPj9kuGTZm2MZAkBa5QeWd9/4o/y8LZjJq9++6u+Lts7+6L2fdf4GAjs7dgVdk0rruMt4VMue6WXvn4hSErV1dluD3KWpf01VDjZBAkEAjwWpBc5Z2L1mUGLpcHjwyGvXVjVDeEC12ERdzCGtNCdP2nYbvY4ONJdMtlQ2grKbA+x2wATIow6JE7gOxrzQ2QJBAJCWGti2LP9ftl2X5XhZ0VK+DOGIrdBzXs/g/zkKNh393VEJvB7qloK03aY4R4Vw4ssCUsf3YAShMQUpjoDFqEg=
利用公鑰加密,私鑰解密:
System.out.println("公鑰加密——私鑰解密");
System.out.println("加密前數據的內容是-->" + sourceStr);
byte[] data = sourceStr.getBytes();
byte[] encryptData = RSAUtils.encryptByPublicKey(data, publicKey);
System.out.println("加密後的數據內容是-->" + new String(encryptData));
byte[] decryptData = RSAUtils.decryptByPrivateKey(encryptData,
privateKey);
System.out.println("解密後的數據內容是-->" + new String(decryptData));
公鑰加密——私鑰解密
加密前數據的內容是-->這是一段待加密的數據
加密後的數據內容是-->(���%5 [�͖W��uA- ��m�u�&w�2��gQ���-5�Q���`7:Й�C,�8t�qM�gJ��e2"�)y��͓����� �Y��@�y*_�M�����x*;�f1���v֚�@�h�}P?X�2
解密後的數據內容是-->這是一段待加密的數據
PHP-RSA加密跨域通訊實戰 http://www.linuxidc.com/Linux/2014-10/107881.htm
使用Python的OpenSSL庫來進行RSA加密 http://www.linuxidc.com/Linux/2012-05/59456.htm