ari*_*rik 10 java encryption rsa long-integer
我试图来回编码一个简单的字符串"测试".
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
}
Run Code Online (Sandbox Code Playgroud)
但是,尽管加密工作正常(ALGORITHM是"RSA"),但在尝试解密我刚从加密"test"获得的字符串时,我得到以下异常:
javax.crypto.IllegalBlockSizeException:数据不得超过256个字节
我应该将加密的字节分成256块,以便能够解密吗?
您无法将随机字节可靠地转换为a String.结果取决于运行此命令的计算机上的默认字符编码.使用许多编码时,密文将被破坏,信息将丢失.
修改您的代码以使用byte[]替代('doFinal()`方法的结果.
如果需要将其转换为byte[]字符串,请使用Base-64之类的编码.
| 归档时间: |
|
| 查看次数: |
14165 次 |
| 最近记录: |