密碼系統(tǒng)AES私鑰RSA公鑰的加解密示例
前言
密鑰是成對(duì)存在的,加密和解密是采用不同的密鑰(公開密鑰),也就是非對(duì)稱密鑰密碼系統(tǒng),每個(gè)通信方均需要兩個(gè)密鑰,即公鑰和私鑰,使用公鑰進(jìn)行加密操作,使用私鑰進(jìn)行解密操作。公鑰是公開的,不需要保密,而私鑰是由個(gè)人自己持有,并且必須妥善保管和注意保密。密碼學(xué)里面博大精深,下面的實(shí)例僅供參考
百科的詮釋
公鑰(Public Key)與私鑰(Private Key)是通過一種算法得到的一個(gè)密鑰對(duì)(即一個(gè)公鑰和一個(gè)私鑰),公鑰是密鑰對(duì)中公開的部分,私鑰則是非公開的部分。公鑰通常用于加密會(huì)話密鑰、驗(yàn)證數(shù)字簽名,或加密可以用相應(yīng)的私鑰解密的數(shù)據(jù)。通過這種算法得到的密鑰對(duì)能保證在世界范圍內(nèi)是唯一的。使用這個(gè)密鑰對(duì)的時(shí)候,如果用其中一個(gè)密鑰加密一段數(shù)據(jù),必須用另一個(gè)密鑰解密。比如用公鑰加密數(shù)據(jù)就必須用私鑰解密,如果用私鑰加密也必須用公鑰解密,否則解密將不會(huì)成功。
java使用公私鑰加解密的實(shí)例
僅供參考
/**
* 數(shù)據(jù)加密 plainTextData要加密的字符串
* @param plainTextData
* @return
* @throws Exception
*/
public static Map encrypt(String plainTextData)
throws Exception {
HashMap result = new HashMap();
// keySpec 生成對(duì)稱密鑰
KeyGenerator keyGenerator = KeyGenerator.getInstance("AES");
keyGenerator.init(128);
SecretKey secretKey = keyGenerator.generateKey();
SecretKeySpec keySpec = new SecretKeySpec(secretKey.getEncoded(), "AES");
// RSA 用對(duì)方公鑰對(duì)‘對(duì)稱密鑰'進(jìn)行加密
Cipher cipher = Cipher.getInstance("RSA");
String keyFilePathName = pertery.getProperty("bsbank_Key_path")+"PublicKey.keystore";
cipher.init(Cipher.WRAP_MODE,
loadPublicKeyByStr(loadKeyByFile(keyFilePathName)));
byte[] wrappedKey = cipher.wrap(keySpec);
result.put("wrappedKey", Base64.encodeBase64String(wrappedKey));
// 加密數(shù)據(jù)
cipher = Cipher.getInstance("AES");
cipher.init(Cipher.ENCRYPT_MODE, keySpec);
byte[] encryptedData = cipher.doFinal(plainTextData.getBytes("UTF-8"));
result.put("encryptedData", Base64.encodeBase64String(encryptedData));
return result;
}
/**
* 數(shù)據(jù)解密 encryptedData
* @param encryptedData
* @return
* @throws Exception
*/
public static Map decrypt(Map encryptedData)
throws Exception {
// 獲取密鑰
byte[] wrappedKey = Base64.decodeBase64(encryptedData.get("wrappedKey")
.toString());
HashMap result = new HashMap();
// RSA解密密鑰
Cipher cipher = Cipher.getInstance("RSA");
String keyFilePathName = pertery.getProperty("bsbank_Key_path")+"privateKey.keystore";//使用對(duì)方的私鑰解密
cipher.init(Cipher.UNWRAP_MODE,
loadPrivateKeyByStr(loadKeyByFile(keyFilePathName)));
Key key = cipher.unwrap(wrappedKey, "AES", Cipher.SECRET_KEY);
// 解密數(shù)據(jù)
cipher = Cipher.getInstance("AES");
cipher.init(Cipher.DECRYPT_MODE, key);
byte[] decryptedData = cipher.doFinal(Base64.decodeBase64(encryptedData
.get("encryptedData").toString()));
result.put("decryptedData", new String(decryptedData, "UTF-8"));
result.put("wrappedKey", Base64.encodeBase64String(wrappedKey));
return result;
}
private static String loadKeyByFile(String filePathName) throws Exception {
BufferedReader br = null;
StringBuilder sb = new StringBuilder();
try {
br = new BufferedReader(new FileReader(filePathName));
String readLine = null;
while ((readLine = br.readLine()) != null) {
sb.append(readLine);
}
} catch (Exception e) {
throw e;
} finally {
if (null != br) {
br.close();
}
}
return sb.toString();
}
private static RSAPublicKey loadPublicKeyByStr(String publicKeyStr)
throws Exception {
RSAPublicKey publicKey = null;
try {
byte[] buffer = Base64.decodeBase64(publicKeyStr);
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
X509EncodedKeySpec keySpec = new X509EncodedKeySpec(buffer);
publicKey = (RSAPublicKey) keyFactory.generatePublic(keySpec);
} catch (Exception e) {
logger.error("failed to load pubKey", e);
throw e;
}
return publicKey;
}
private static RSAPrivateKey loadPrivateKeyByStr(String privateKeyStr)
throws Exception {
RSAPrivateKey privateKey = null;
try {
byte[] buffer = Base64.decodeBase64(privateKeyStr);
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(buffer);
privateKey = (RSAPrivateKey) keyFactory.generatePrivate(keySpec);
} catch (Exception e) {
logger.error("failed to loadPrivateKeyByStr", e);
throw e;
}
return privateKey;
}
/**
* 輸出公私鑰對(duì)
* @param filePath
* @throws Exception
*/
private static void genKeyPair(String filePath) throws Exception {
KeyPairGenerator keyPairGen = null;
try {
keyPairGen = KeyPairGenerator.getInstance("RSA");
} catch (NoSuchAlgorithmException e) {
logger.error("failed to do key gen", e);
throw e;
}
keyPairGen.initialize(1024, new SecureRandom());
KeyPair keyPair = keyPairGen.generateKeyPair();
RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();
RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();
try {
String publicKeyString = Base64.encodeBase64String(publicKey
.getEncoded());
String privateKeyString = Base64.encodeBase64String(privateKey
.getEncoded());
FileWriter pubfw = new FileWriter(filePath + "/PublicKey.keystore");
FileWriter prifw = new FileWriter(filePath + "/PrivateKey.keystore");
BufferedWriter pubbw = new BufferedWriter(pubfw);
BufferedWriter pribw = new BufferedWriter(prifw);
pubbw.write(publicKeyString);
pribw.write(privateKeyString);
pubbw.flush();
pubbw.close();
pubfw.close();
pribw.flush();
pribw.close();
prifw.close();
} catch (IOException e) {
logger.error("failed to genKeypair", e);
}
}以上就是詮釋AES私鑰RSA公鑰的加解密示例的詳細(xì)內(nèi)容,更多關(guān)于AES RSA公私鑰加解密的資料請(qǐng)關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
springboot如何獲取yaml/yml(或properties)配置文件信息
在SpringBoot項(xiàng)目中,讀取配置文件信息是常見需求,可以通過@Autowired注入Environment類,使用@Value注解直接注入配置信息,或定義工具類結(jié)合ApplicationRunner進(jìn)行高級(jí)配置信息獲取,特別提到2024-11-11
JAVA位運(yùn)算的知識(shí)點(diǎn)總結(jié)
在本篇文章里小編給大家整理的是關(guān)于JAVA有關(guān)位運(yùn)算的全套梳理,需要的朋友們可以參考學(xué)習(xí)下。2020-03-03
Java中Redis存儲(chǔ)String類型會(huì)有亂碼的問題及解決方案
在java中使用Redis存儲(chǔ)String類型的數(shù)據(jù)時(shí),會(huì)出現(xiàn)亂碼,我寫了一條存儲(chǔ)key為name,值為虎哥的字符串,然后獲取一下這個(gè)key為name的值,打印得到的值,下面通過實(shí)例代碼介紹Java中Redis存儲(chǔ)String類型會(huì)有亂碼的問題及解決方案,一起看看吧2024-04-04
深入學(xué)習(xí)MyBatis中的參數(shù)(推薦)
大家日常使用MyBatis經(jīng)常會(huì)遇到一些異常,想要避免參數(shù)引起的錯(cuò)誤,我們需要深入了解參數(shù)。想了解參數(shù),我們首先看MyBatis處理參數(shù)和使用參數(shù)的全部過程。下面這篇文章主要給大家介紹了MyBatis中參數(shù)的的相關(guān)資料,需要的朋友可以參考借鑒,下面來一起看看吧。2017-06-06
jenkins配置詳細(xì)指南(附j(luò)dk多個(gè)版本配置)
Jenkins是一款CICD(持續(xù)集成與持續(xù)交付)工具,Jenkins可以幫你在寫完代碼后,一鍵完成開發(fā)過程中的一系列自動(dòng)化部署的工作,這篇文章主要給大家介紹了關(guān)于jenkins配置的相關(guān)資料,文中還附j(luò)dk多個(gè)版本配置指南,需要的朋友可以參考下2024-02-02
JMeter參數(shù)化4種實(shí)現(xiàn)方式(小結(jié))
參數(shù)化是自動(dòng)化測試腳本的一種常用技巧,可將腳本中的某些輸入使用參數(shù)來代替,JMeter提供了多種參數(shù)化方式,下面就其中常用的4種展開闡述,感興趣的可以來了解一下2021-12-12

