0

I'm trying to convert the following code from C# to Java, but I get different result values of keys. Here are my codes:

C#:

        plainText = "Hello World";
        passPhrase = "IhDyHz6bgQyS0Ff1/1s=";
        saltValue = "0A0Qvv09OXd3GsYHVrA=";
        hashAlgorithm = "SHA1";
        passwordIterations = 3;
        initVector = "GjrlRZ6INgNckBqv";
        keySize = 256;

        byte[] initVectorBytes = Encoding.ASCII.GetBytes(initVector);
        byte[] saltValueBytes = Encoding.ASCII.GetBytes(saltValue);

        byte[] plainTextBytes = Encoding.UTF8.GetBytes(plainText);

        PasswordDeriveBytes password = new PasswordDeriveBytes(
                                                        passPhrase,
                                                        saltValueBytes,
                                                        hashAlgorithm,
                                                        passwordIterations);

        byte[] keyBytes = password.GetBytes(keySize / 8);

Java

        byte[] password = PassPhrase.getBytes("ASCII");
        byte[] salt = PKCS5S1ParametersGenerator.PKCS5PasswordToBytes(SaltValue.toCharArray());

        PKCS5S1ParametersGenerator generator = new PasswordDeriveBytes(new SHA1Digest()); 
        generator.init(password, salt, PasswordIterations); 

        byte[] key = ((KeyParameter)generator.generateDerivedParameters(32)).getKey(); 

The issue is that I get different keys even with the same parameters provided on both codes: (only the first 4 bytes match)

NOTE: this values had been converted to Base64:

C#: GWR/loJAuuiPvP0cuGGCVXErz16HjOZ7yQkCCHfBux4= Java: GWR/4oCT

If I keep playing with the number provided to generateDerivedParameters(32), it only gives me more bytes but still doesn't match the result at .Net.

I can't change the .Net code, so please any suggestion must be done at Java side.

Thanks in advance.

1 Answer 1

1

The generateDerivedParameters method says: "keySize the size of the key we want (in bits)". So you have to use generateDerivedParameters(32 * 8)

Sign up to request clarification or add additional context in comments.

3 Comments

Thanks for the clarification, but still not matching the C# key, this is the result: GWR/4oCT4oCaQMK6w6jvv73CvMO9HMK4YeKAmlVxK8OPXuKAocWSw6Z7w4kJAgh3w4HCux4=
Looks like different standard (sic!) of Base64 is used different alphabet. Could you compare bytes, the binary values to verify if it's the same?
OMG you're totally right, even though I've tested a lot the Base64 Java method conversion against its simil in C#, this time I've been foolish by this, looking at the bytes, they are actually the same.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.