0

I need to encrypt a string using a salt and a key to match a java encryption so that the 3rd party provider can decrypt the values on the other side.

I have tried several StackOverflow articles as I am no expert in encryption and just cannot get the same encryption string using SALT and KEY as the 3rd party provider.

I need to know which encryption type and mode in C# to use to match java's AES encryptions as used here

https://gist.github.com/ca958d5921d47c4c0a0f

czechman
  • 31
  • 4

1 Answers1

3

OK - I figured it out even though it's cheating to a degree. Because I could not find any encryption technique that would match the plain AES encryption provided by the 3rd party I asked them to change it to

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

With this I amended my C# code and finally got the integration working:

public static string Encrypt2(string plainText)
    {
        string PassPhrase = "somepassphrase";
        string SaltValue = "somesalt";
        int PasswordIterations = 0; //amend to match java encryption iteration
        string InitVector = "someiv";
        int KeySize = 0; //amend to match java encryption key size

        byte[] initVectorBytes = Encoding.ASCII.GetBytes(InitVector);
        byte[] saltValueBytes = Encoding.ASCII.GetBytes(SaltValue);

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

        Rfc2898DeriveBytes password = new Rfc2898DeriveBytes(
                                                        PassPhrase,
                                                        saltValueBytes,
                                                        PasswordIterations);

        byte[] keyBytes = password.GetBytes(KeySize / 8);
        RijndaelManaged symmetricKey = new RijndaelManaged();
        symmetricKey.Mode = CipherMode.CBC;

        ICryptoTransform encryptor = symmetricKey.CreateEncryptor(
                                                         keyBytes,
                                                         initVectorBytes);
        MemoryStream memoryStream = new MemoryStream();

        CryptoStream cryptoStream = new CryptoStream(memoryStream,
                                                     encryptor,
                                                     CryptoStreamMode.Write);

        cryptoStream.Write(plainTextBytes, 0, plainTextBytes.Length);
        cryptoStream.FlushFinalBlock();
        byte[] cipherTextBytes = memoryStream.ToArray();

        memoryStream.Close();
        cryptoStream.Close();

        string cipherText = Convert.ToBase64String(cipherTextBytes);

        return cipherText;
    }
czechman
  • 31
  • 4