RSA 解密實踐

前言

通常與第三方 API 進行數據通訊時,API 提供方可能會要求對請求參數進行加密。算法

RSA 加密算法一直是最廣爲使用的"非對稱加密算法"。絕不誇張地說,只要有計算機網絡的地方,就有RSA算法。網絡

簡單的梳理一下 RSA 的總體流程,假設咱們是甲方,API 提供方是乙方。dom

  1. 甲方生成一對密鑰包含 公鑰 和 私鑰。
  2. 甲方向乙方發出網絡請求,將 公鑰 以及其餘數據發送給乙方。
  3. 乙方在業務程序執行完成以後,使用接收到的 公鑰 對響應的數據進行加密。
  4. 甲方接收到乙方響應的 密文,使用在 1. 中生成的 私鑰 進行解密。

從這個流程能夠看到,RSA 就是一把鎖 ????,他有兩把鑰匙 ????,一把用來上鎖,一把用來解鎖。ide

生成密鑰對

/**
 * 生成 RSA 密鑰對
 *
 * @return Map
 */public Map<String, String> buildRSAKeyPair() {
    Map<String, String> keyPairMap = new HashMap<>();try {// KeyPairGenerator類用於生成公鑰和私鑰對,基於RSA算法生成對象KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");// 初始化密鑰對生成器,密鑰大小爲96-1024位keyPairGenerator.initialize(1024, new SecureRandom());// 生成一個密鑰對,保存在keyPair中KeyPair keyPair = keyPairGenerator.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())));// 將公鑰和私鑰保存到MapkeyPairMap.put("privateKey", privateKeyString);
        keyPairMap.put("publicKey", publicKeyString);return keyPairMap;
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();throw new RuntimeException("生成 RSA 密鑰對時出現異常!");
    }
}複製代碼

解密

/**
 * 使用私密解密
 *
 * @param str        密文
 * @param privateKey 私密
 * @return String
 */public String decrypt(String str, String privateKey) {try {//64位解碼加密後的字符串byte[] inputByte = Base64.decodeBase64(str.getBytes(StandardCharsets.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);return new String(cipher.doFinal(inputByte));
    } catch (Exception e) {
        e.printStackTrace();throw new RuntimeException("RSA 解密時出現異常!");
    }
}複製代碼
相關文章
相關標籤/搜索