需求很簡單:iPad 端把密碼用 RSA 加密後傳給 Java 後端解密。結果兩邊各自測試都正常,一換對方的鑰匙對卻怎麼樣都驗不過。本文記錄這個問題的成因與解法。
RSA 屬於非對稱加密,一組鑰匙包含公鑰與私鑰。一般用法是公鑰加密、私鑰解密;反過來用私鑰加密、公鑰解密也成立。此外還可以做簽章驗證:先用私鑰對資料加密並產生簽名,接收端用公鑰驗簽通過後才解密,目的是確認資料來源可信。
由此可見,RSA 的一切關鍵就在「鑰匙對」本身。兩邊各自產生的鑰匙對都能正常加解密,但交換使用就失敗——問題顯然不在演算法,而在編碼格式。
繼續追查後找到關鍵:在 Mac 上用系統自帶的 OpenSSL 產生的鑰匙對是 X.509 編碼格式,而 Java 這邊所需的私鑰必須是 PKCS#8 格式。兩者結構不同,直接餵給 KeyFactory 自然會失敗。
解法就是把 Mac 上產生的私鑰做一次格式轉換(openssl pkcs8 -topk8 -inform PEM -outform PEM ...),Java 端即可正常載入。

以下是一個完整的 RSA 工具類,含鑰匙對產生、載入、加解密與十六進位轉換:
public class RSAEncrypt {
private static final String DEFAULT_PUBLIC_KEY =
"MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQChDzcjw/rWgFwnxunbKp7/4e8w" + "\r" +
"/UmXx2jk6qEEn69t6N2R1i/LmcyDT1xr/T2AHGOiXNQ5V8W4iCaaeNawi7aJaRht" + "\r" +
"Vx1uOH/2U378fscEESEG8XDqll0GCfB1/TjKI2aitVSzXOtRs8kYgGU78f7VmDNg" + "\r" +
"XIlk3gdhnzh+uoEQywIDAQAB" + "\r";
private static final String DEFAULT_PRIVATE_KEY =
"MIICdQIBADANBgkqhkiG9w0BAQEFAASCAl8wggJbAgEAAoGBAKEPNyPD+taAXCfG" + "\r" +
"6dsqnv/h7zD9SZfHaOTqoQSfr23o3ZHWL8uZzINPXGv9PYAcY6Jc1DlXxbiIJpp4" + "\r" +
"1rCLtolpGG1XHW44f/ZTfvx+xwQRIQbxcOqWXQYJ8HX9OMojZqK1VLNc61GzyRiA" + "\r" +
"ZTvx/tWYM2BciWTeB2GfOH66gRDLAgMBAAECAQAB..." + "\r";
private RSAPrivateKey privateKey;
private RSAPublicKey publicKey;
private static final char[] HEX_CHAR =
{'0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f'};
public RSAPrivateKey getPrivateKey() { return privateKey; }
public RSAPublicKey getPublicKey() { return publicKey; }
/** 隨機產生鑰匙對 */
public void genKeyPair() throws NoSuchAlgorithmException {
KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance("RSA");
keyPairGen.initialize(1024, new SecureRandom());
KeyPair keyPair = keyPairGen.generateKeyPair();
this.privateKey = (RSAPrivateKey) keyPair.getPrivate();
this.publicKey = (RSAPublicKey) keyPair.getPublic();
}
/** 從串流載入公鑰(會自動跳過 BEGIN/END 註解行) */
public void loadPublicKey(InputStream in) throws Exception {
try {
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String readLine;
StringBuilder sb = new StringBuilder();
while ((readLine = br.readLine()) != null) {
if (readLine.charAt(0) == '-') continue;
sb.append(readLine).append('\r');
}
loadPublicKey(sb.toString());
} catch (IOException e) {
throw new Exception("公鑰數據流讀取錯誤");
} catch (NullPointerException e) {
throw new Exception("公鑰輸入流為空");
}
}
/** 從字串載入公鑰,此處使用 X.509 規格 */
public void loadPublicKey(String publicKeyStr) throws Exception {
try {
BASE64Decoder base64Decoder = new BASE64Decoder();
byte[] buffer = base64Decoder.decodeBuffer(publicKeyStr);
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
X509EncodedKeySpec keySpec = new X509EncodedKeySpec(buffer);
this.publicKey = (RSAPublicKey) keyFactory.generatePublic(keySpec);
} catch (NoSuchAlgorithmException e) {
throw new Exception("無此算法");
} catch (InvalidKeySpecException e) {
throw new Exception("公鑰非法");
} catch (IOException e) {
throw new Exception("公鑰數據內容讀取錯誤");
} catch (NullPointerException e) {
throw new Exception("公鑰數據為空");
}
}
/** 從串流載入私鑰 */
public void loadPrivateKey(InputStream in) throws Exception {
try {
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String readLine;
StringBuilder sb = new StringBuilder();
while ((readLine = br.readLine()) != null) {
if (readLine.charAt(0) == '-') continue;
sb.append(readLine).append('\r');
}
loadPrivateKey(sb.toString());
} catch (IOException e) {
throw new Exception("私鑰數據讀取錯誤");
} catch (NullPointerException e) {
throw new Exception("私鑰輸入流為空");
}
}
/** 從字串載入私鑰,此處使用 PKCS#8 規格 */
public void loadPrivateKey(String privateKeyStr) throws Exception {
try {
BASE64Decoder base64Decoder = new BASE64Decoder();
byte[] buffer = base64Decoder.decodeBuffer(privateKeyStr);
PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(buffer);
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
this.privateKey = (RSAPrivateKey) keyFactory.generatePrivate(keySpec);
} catch (NoSuchAlgorithmException e) {
throw new Exception("無此算法");
} catch (InvalidKeySpecException e) {
throw new Exception("私鑰非法");
} catch (IOException e) {
throw new Exception("私鑰數據內容讀取錯誤");
} catch (NullPointerException e) {
throw new Exception("私鑰數據為空");
}
}
/** 公鑰加密 */
public byte[] encrypt(RSAPublicKey publicKey, byte[] plainTextData) throws Exception {
if (publicKey == null) throw new Exception("加密公鑰為空, 請設置");
try {
Cipher cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.ENCRYPT_MODE, publicKey);
return cipher.doFinal(plainTextData);
} catch (NoSuchAlgorithmException e) {
throw new Exception("無此加密算法");
} catch (NoSuchPaddingException e) {
return null;
} catch (InvalidKeyException e) {
throw new Exception("加密公鑰非法, 請檢查");
} catch (IllegalBlockSizeException e) {
throw new Exception("明文長度非法");
} catch (BadPaddingException e) {
throw new Exception("明文數據已損壞");
}
}
/** 私鑰解密 */
public byte[] decrypt(RSAPrivateKey privateKey, byte[] cipherData) throws Exception {
if (privateKey == null) throw new Exception("解密私鑰為空, 請設置");
try {
Cipher cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.DECRYPT_MODE, privateKey);
return cipher.doFinal(cipherData);
} catch (NoSuchAlgorithmException e) {
throw new Exception("無此解密算法");
} catch (NoSuchPaddingException e) {
return null;
} catch (InvalidKeyException e) {
throw new Exception("解密私鑰非法, 請檢查");
} catch (IllegalBlockSizeException e) {
throw new Exception("密文長度非法");
} catch (BadPaddingException e) {
throw new Exception("密文數據已損壞");
}
}
/** 位元組陣列轉十六進位字串 */
public static String byteArrayToString(byte[] data) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < data.length; i++) {
sb.append(HEX_CHAR[(data[i] & 0xf0) >>> 4]); // 高四位,注意用無號右移
sb.append(HEX_CHAR[(data[i] & 0x0f)]); // 低四位
if (i < data.length - 1) sb.append(' ');
}
return sb.toString();
}
public static void main(String[] args) {
RSAEncrypt rsaEncrypt = new RSAEncrypt();
// rsaEncrypt.genKeyPair();
try {
rsaEncrypt.loadPublicKey(RSAEncrypt.DEFAULT_PUBLIC_KEY);
System.out.println("加載公鑰成功");
} catch (Exception e) {
System.err.println("加載公鑰失敗:" + e.getMessage());
}
try {
rsaEncrypt.loadPrivateKey(RSAEncrypt.DEFAULT_PRIVATE_KEY);
System.out.println("加載私鑰成功");
} catch (Exception e) {
System.err.println("加載私鑰失敗:" + e.getMessage());
}
String encryptStr = "abc";
try {
byte[] cipher = rsaEncrypt.encrypt(rsaEncrypt.getPublicKey(), encryptStr.getBytes());
byte[] plainText = rsaEncrypt.decrypt(rsaEncrypt.getPrivateKey(), cipher);
System.out.println("密文長度:" + cipher.length);
System.out.println(RSAEncrypt.byteArrayToString(cipher));
System.out.println("明文長度:" + plainText.length);
System.out.println(new String(plainText));
} catch (Exception e) {
System.err.println(e.getMessage());
}
}
}
這個類別提供兩種載入鑰匙的方式:字串或檔案串流。要注意的是,檔案必須是 .pem 格式;載入時會自動跳過以 - 開頭的 BEGIN/END 註解行。
iOS 端的加密要求的是 .der 格式(DER 是二進位編碼,PEM 則是 Base64 的文字包裝),因此鑰匙同樣需要轉檔。相關做法可參考:RSA in iOS Using Public Key Generated by OpenSSL
iOS 加密後得到的是 NSData,先做 Base64 編碼轉成字串傳給 Java,Java 用 BASE64Decoder 解回 byte[],就能直接交給上面的 decrypt 處理。