Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

encryption - AES-256 and PKCS7Padding fails in Java

I have a couple of library, C#, PHP and Android where they all encrypt/decrypt a string in the same way so they are all compatible with each other, i.e. C# writes and encrypts data to a database and PHP can successfully decrypt it and return the original string.

I now need to do the same thing with a standard Java application, so I've taken the code from my Android library and need libraries but I am getting an exception. As far as I know the code wasn't Android specific so it shouldn't be a problem.

Below is my encryption function

public static String encrypt(String plainPasword)
    {
            String password = "";
            try
            {
                SecretKeySpec key = new SecretKeySpec("hcxilkqbbhczfeultgbskdmaunivmfuo".getBytes("US-ASCII"), "AES");
                IvParameterSpec iv = new IvParameterSpec("ryojvlzmdalyglrj".getBytes("US-ASCII"));

                Cipher cipher = Cipher.getInstance("AES/CBC/PKCS7Padding");

                cipher.init(Cipher.ENCRYPT_MODE, key, iv);

                byte[] encoded = cipher.doFinal(plainPasword.getBytes());
                password = new String(Base64.encodeBase64(encoded));

            }
            catch (Exception ex)
            {
                System.err.println("Encryption Exception: " + ex.toString());
            }
            return password;
    }

When I call Encryption.encrypt("myString") I get the following exception:

Encryption Exception: java.security.NoSuchAlgorithmException: Cannot find any provider supporting AES/CBC/PKCS7Padding

As I said this code is working fine on Android and it shouldn't make any difference where it is running from.

Update

I found that I needed PKCS5Padding instead of 7 thanks to a link on a comment. I am now though getting the following exception:

Encryption Exception: java.security.InvalidKeyException: Illegal key size
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

First, in Java, the standard padding name is PKCS5Padding, not PKCS7Padding. Java is actually performing PKCS #7 padding, but in the JCA specification, PKCS5Padding is the name given.

Next, you are trying to use AES-256, so you'll need to install the Unlimited Strength Jurisdiction policy files.

Hopefully this is just an example and you aren't using the same IV for every message, right?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...