java.security.NoSuchAlgorithmException:Cannot find

2019-01-18 19:20发布

问题:

I was trying to encrypt data using AES algorithm. However, with the following exception has occurred.

java.security.NoSuchAlgorithmException:
    Cannot find any provider supporting AES/ECB/PKCS7PADDING

Someone know a solution to this issue? My JDK's version is 1.7.

回答1:

You don't want to specify PKCS#7 padding for block cipher use. You want to specify PKCS#5 padding. PKCS#5 is specified for use with block ciphers while PKCS#7 is not (it's use for different places like in S/MIME). I will point out that PKCS#5 and PKCS#7 actually specify exactly the same type of padding (they are the same!), but it's called #5 when used in this context. :)

So, instead of "AES/ECB/PKCS7PADDING", you want "AES/ECB/PKCS5PADDING". This is a cipher implementation that every implementation of the Java platform is required to support. See the documentation of the Cipher class for more details.



回答2:

For a very comprehensive explanation of the issue that includes the text of the PKCS#5 and PKCS#7 cryptographic standards, please take a look here.


PKCS#5 padding means padding 1 to 8 bytes. The padding bytes themselves contain the amount of padding bytes encoded as a byte. PKCS#5 padding was specified for DES, but it would be suitable for any block cipher with a block size of 8 bytes.

Now the DES specifications and even the PKCS#5 specification for password based encryption precede and Java by quite a long time. AES was only standardized in 2002, long after Java and even Java 2 was introduced. So (triple) DES and PKCS#5 padding was integrated into Java before AES made its appearance.

When Java - or more precisely, the Sun JCE provider - gained AES functionality it required a padding method for a block size of 16 bytes. PKCS#7 specifies this padding method that is identical to PKCS#5 padding, except that it is defined for block sizes of 2 to 255 bytes (the maximum value of a byte if it encodes a zero based unsigned integer). However, the padding method was already there; it was named "PKCS5Padding". So instead of introducing a new name, "PKCS5Padding" was simply re-used.

By now the Sun provider should really support "PKCS7Padding" as PKCS#5 padding is simply incorrect. It's not just a Java naming issue, it's an issue for any developer that tries to implement cryptographic protocols or port other applications to Java. For now however, you should use "PKCS5Padding" instead of "PKCS7Padding".



回答3:

if you want to use AES/ECB/PKCS7Padding then bouncy castle will support http://www.bouncycastle.org/specifications.html