有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

加密如何修复错误“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: Data must not be longer than 245 bytes

。。。根据this StackOverflow answer here 解决方案是使用算法"RSA/ECB/PKCS1Padding"而不是"RSA" [更新:此结论不正确。]

当我将ALGORITHM = "RSA";更改为ALGORITHM = "RSA/ECB/PKCS1Padding";时,我得到了这个错误

"java.security.NoSuchAlgorithmException: RSA/ECB/PKCS1Padding"

如何修复此“NoSuchAlgorithm”错误

仅供参考,我正在使用Spring工具套件4(4.6.0)和Java 1.8.0241,它们要么随附,要么由Mac软件更新安装


共 (0) 个答案