英文:
How to fix error "java.security.NoSuchAlgorithmException: RSA/ECB/PKCS1Padding"
问题
我有一些已编写的公钥/私钥加密代码。当要加密的数据较短时,它能正常工作,例如:"this is plain text"
。
private static final String ALGORITHM = "RSA";
public static byte[] encryptWithPrivateKey(byte[] privateKey, byte[] inputData) throws Exception {
PrivateKey key = KeyFactory.getInstance(ALGORITHM).generatePrivate(new PKCS8EncodedKeySpec(privateKey));
Cipher cipher = Cipher.getInstance(ALGORITHM);
cipher.init(Cipher.ENCRYPT_MODE, key);
byte[] encryptedBytes = cipher.doFinal(inputData);
return encryptedBytes;
}
但是,当我尝试加密一个较长的字符串时,我收到了一个错误...
javax.crypto.IllegalBlockSizeException: 数据长度不能超过245字节
... 根据这个 StackOverflow 回答 ... <s>解决方法是使用算法 RSA/ECB/PKCS1Padding
而不是 RSA
。</s> [更新:这个结论是不正确的。]
当我将 ALGORITHM = "RSA"
更改为 ALGORITHM = "RSA/ECB/PKCS1Padding"
时,我收到了这个错误...
"java.security.NoSuchAlgorithmException: RSA/ECB/PKCS1Padding"
如何修复这个 "NoSuchAlgorithm" 错误?
只是提供信息,我正在使用Spring Tool Suite 4(4.6.0)和Java 1.8.0_241,这些可能是与它捆绑或由Mac软件更新安装的。
英文:
I have some public/private encryption code written. It works fine when the data to be encrypted is short, example: "this is plain text".
private static final String ALGORITHM = "RSA";
public static byte[] encryptWithPrivateKey(byte[] privateKey, byte[] inputData) throws Exception {
PrivateKey key = KeyFactory.getInstance(ALGORITHM).generatePrivate(new PKCS8EncodedKeySpec(privateKey));
Cipher cipher = Cipher.getInstance(ALGORITHM);
cipher.init(Cipher.ENCRYPT_MODE, key);
byte[] encryptedBytes = cipher.doFinal(inputData);
return encryptedBytes;
}
But when I try to encrypt a much longer string, I get an error ...
javax.crypto.IllegalBlockSizeException: Data must not be longer than 245 bytes
... according to this StackOverflow answer here ... <s>the solution is to use algorithm "RSA/ECB/PKCS1Padding"
instead of "RSA"
.</s> [UPDATE: This conclusion was incorrect.]
When I changed ALGORITHM = "RSA";
to ALGORITHM = "RSA/ECB/PKCS1Padding";
, I get this error ...
"java.security.NoSuchAlgorithmException: RSA/ECB/PKCS1Padding"
How do I fix this "NoSuchAlgorithm" error?
Just FYI, I'm using Spring Tool Suite 4 (4.6.0) and Java 1.8.0_241 that either came with it or was installed by Mac software updates.
专注分享java语言的经验与见解,让所有开发者获益!
评论