我想編碼一個簡單的字符串「測試」來回。Java RSA加密
public static String encode(Key publicKey, String data) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException {
byte[] byteData = data.getBytes(); // convert string to byte array
Cipher cipher = Cipher.getInstance(ALGORITHM); // create conversion processing object
cipher.init(Cipher.ENCRYPT_MODE, publicKey); // initialize object's mode and key
byte[] encryptedByteData = cipher.doFinal(byteData); // use object for encryption
return new String(encryptedByteData); // convert encrypted byte array to string and return it
}
public static String decode(Key privateKey, String data) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException {
byte[] byteData = data.getBytes(); // convert string to byte array
Cipher cipher = Cipher.getInstance(ALGORITHM); // create conversion processing object
cipher.init(Cipher.DECRYPT_MODE, privateKey); // initialize object's mode and key
System.out.println(byteData.length);
byte[] decryptedByteData = cipher.doFinal(byteData); // use object for decryption
return new String(decryptedByteData); // convert decrypted byte array to string and return it
}
然而,儘管加密工作得很好(算法是「RSA」),試圖解密我剛剛從加密「測試」得到的字符串時,我得到異常以下:
javax.crypto.IllegalBlockSizeException:數據長度不能超過256字節
我應該將加密的字節分成256塊以便能夠解密嗎?
啊,完美,謝謝,完美無缺!是的,我猜想腐敗是當我將加密的字節數組轉換爲字符串。 – arik 2011-05-20 21:05:44