How to generate the same AES key in Java (Android) as in .Net?

I need to generate an AES key in Java (Android) from the salt and password specified in .Net WebService. I need to have the same key as the key generated in .net with the same password and salt (using Rfc2898DeriveBytes and AesManaged ()). Here is my Android code:

char[] passwordAsCharArray = password.toCharArray(); PBEKeySpec pbeKeySpec = new PBEKeySpec(passwordAsCharArray, salt, 1000, 256); SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1"); SecretKeySpec secretKey = new SecretKeySpec(factory.generateSecret(spec).getEncoded(), "AES"); 

Here is the code in .net:

 byte[] keyBytes = Encoding.Unicode.GetBytes(key); Rfc2898DeriveBytes derivedKey = new Rfc2898DeriveBytes(key, keyBytes); AesManaged rijndaelCSP = new AesManaged(); rijndaelCSP.BlockSize = 128; rijndaelCSP.KeySize = 256; rijndaelCSP.Key = derivedKey.GetBytes(rijndaelCSP.KeySize / 8); rijndaelCSP.IV = derivedKey.GetBytes(rijndaelCSP.BlockSize / 8); ICryptoTransform decryptor = rijndaelCSP.CreateDecryptor(); 

When I compare both keys, they are different. Any ideas on how to create the same keys on Android as in .Net? (I know that the key that was generated in .net is correct). The number of iterations in .Net is 1000, the salt and password are also the same as in Android.


Well, it turned out that I don't need the exact same key (like an array of bytes). I needed this in order to decrypt the file (in Java), which was encrypted in .Net - with this key it gives me a Bad Padding Exception, so I think the key was different and this causes a problem, but all that I needed to do this, create IV as a key - this solved my problem. Thanks for the answer!

+4
source share
1 answer

It looks like you used the โ€œkeyโ€ (which should be a password) as a salt in your .NET code, while the Java part uses the specified salt. In addition, you specified a Unicode character set for decoding the salt, which is strange, the salt should be a random octet string (== byte array) from the very beginning.

I would recommend converting your password and random salt into byte arrays first, comparing them using the hexadecimal representation (on the console or in your debugger), and only then using them as input parameters for the PBKDF2 function in each. I would recommend UTF-8 encoding for your password.

Always specify all parameters in cryptography, do not use the default, for example. to count the iterations. If your input is disabled by one bit, the output will be completely incorrect, and it is impossible to determine which parameter was responsible.

It seems that the Java and .NET primitive PBKDF2 are identical on both platforms, there is working code on the Internet.

+2
source

All Articles