How to fix error “java.security.NoSuchAlgorithmException: RSA/ECB/PKCS1Padding”

放肆的年华 提交于 2020-07-10 06:58:27

问题


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 ... the solution is to use algorithm "RSA/ECB/PKCS1Padding" instead of "RSA". [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.

来源:https://stackoverflow.com/questions/62629974/how-to-fix-error-java-security-nosuchalgorithmexception-rsa-ecb-pkcs1padding

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!