密碼系統AES私鑰RSA公鑰的加解密示例
前言
密鑰是成對存在的,加密和解密是采用不同的密鑰(公開密鑰),也就是非對稱密鑰密碼系統,每個通信方均需要兩個密鑰,即公鑰和私鑰,使用公鑰進行加密操作,使用私鑰進行解密操作。公鑰是公開的,不需要保密,而私鑰是由個人自己持有,並且必須妥善保管和註意保密。密碼學裡面博大精深,下面的實例僅供參考
百科的詮釋
公鑰(Public Key)與私鑰(Private Key)是通過一種算法得到的一個密鑰對(即一個公鑰和一個私鑰),公鑰是密鑰對中公開的部分,私鑰則是非公開的部分。公鑰通常用於加密會話密鑰、驗證數字簽名,或加密可以用相應的私鑰解密的數據。通過這種算法得到的密鑰對能保證在世界范圍內是唯一的。使用這個密鑰對的時候,如果用其中一個密鑰加密一段數據,必須用另一個密鑰解密。比如用公鑰加密數據就必須用私鑰解密,如果用私鑰加密也必須用公鑰解密,否則解密將不會成功。
java使用公私鑰加解密的實例
僅供參考
/** * 數據加密 plainTextData要加密的字符串 * @param plainTextData * @return * @throws Exception */ public static Map encrypt(String plainTextData) throws Exception { HashMap result = new HashMap(); // keySpec 生成對稱密鑰 KeyGenerator keyGenerator = KeyGenerator.getInstance("AES"); keyGenerator.init(128); SecretKey secretKey = keyGenerator.generateKey(); SecretKeySpec keySpec = new SecretKeySpec(secretKey.getEncoded(), "AES"); // RSA 用對方公鑰對‘對稱密鑰'進行加密 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)); // 加密數據 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; } /** * 數據解密 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";//使用對方的私鑰解密 cipher.init(Cipher.UNWRAP_MODE, loadPrivateKeyByStr(loadKeyByFile(keyFilePathName))); Key key = cipher.unwrap(wrappedKey, "AES", Cipher.SECRET_KEY); // 解密數據 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; } /** * 輸出公私鑰對 * @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公鑰的加解密示例的詳細內容,更多關於AES RSA公私鑰加解密的資料請關註WalkonNet其它相關文章!
推薦閱讀:
- 教你用Java實現RSA非對稱加密算法
- Java如何實現對稱加密
- 總結一些Java常用的加密算法
- SpringBoot安全策略開發之集成數據傳輸加密
- 微信小程序用戶授權獲取手機號(getPhoneNumber)