1

I am struggling to convert the following code to c#:

private SecretKey generateSecretKey(char[] key, byte[] salt) {
  this.FACTORY = SecretKeyFactory.getInstance("PBEWithHmacSHA256AndAES_256");
  KeySpec spec = new PBEKeySpec(key, salt, 65536, 256);
  SecretKey tmp = this.FACTORY.generateSecret(spec);
  return new SecretKeySpec(tmp.getEncoded(), "AES");
} 

what is the corresponding algorithm behind PBEWithHmacSHA256AndAES_256/PBEKeySpec in c#?

the java code is then used for something like this:

this.secretKey = generateSecretKey(this.key, newSalt);
Cipher c = Cipher.getInstance("AES/CBC/PKCS5PADDING");
c.init(2, this.secretKey, new IvParameterSpec(IV));

Also I have noticed that PKCS5PADDING does not exist in C# can it be replaced with PKCS7? Any help would be appreciated!

Rene Steen
  • 11
  • 1

1 Answers1

0

I did a quick research and here you go!

Seems the 7 & 5 padding algs. are the same.
Try using a separate library, such as BouncyCastle.
Encrypt string with Bouncy Castle AES/CBC/PKCS7

Alright, seems that we could manage to solve part of your problem, but unfortunately Bouncy Castle doesn't support PBEWITHHMACSHA256ANDAES_256.

The last idea that pop up in mind is to use IKVM.net. I know that it's not recommended, but it should work. Find the sources and recompile it with PBEWITHHMACSHA256ANDAES_256 provider from e.g. com.sun.crypto.provider.SunJCE. More about recompiling here.

In .Net in order to generate PBKDF2 hash you can use Rfc2898DeriveBytes

Example:

using (var pbkdf2 = new Rfc2898DeriveBytes(
    password,
    saltBytes,
    interactionCount,
    HashAlgorithmName.SHA256))
{
        derived = pbkdf2.GetBytes(32);
}
proximab
  • 1,865
  • 1
  • 13
  • 18