如何修复错误 “java.security.NoSuchAlgorithmException: RSA/ECB/PKCS1Padding”

huangapple 未分类评论49阅读模式
英文:

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: &quot;this is plain text&quot;.

private static final String ALGORITHM = &quot;RSA&quot;;

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 &quot;RSA/ECB/PKCS1Padding&quot; instead of &quot;RSA&quot;.</s> [UPDATE: This conclusion was incorrect.]

When I changed ALGORITHM = &quot;RSA&quot;; to ALGORITHM = &quot;RSA/ECB/PKCS1Padding&quot;;, I get this error ...

&quot;java.security.NoSuchAlgorithmException: RSA/ECB/PKCS1Padding&quot;

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.

huangapple
  • 本文由 发表于 2020年6月29日 09:26:11
  • 转载请务必保留本文链接:https://java.coder-hub.com/62629974.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定