0

I am trying to convert a C# encryption method in angular by using crypto-js library in my angular project.

Here is the implementation of C# method

private const string EncryptionKey = "SomeSecretKEY";
private readonly static byte[] Salt = Encoding.ASCII.GetBytes(EncryptionKey.Length.ToString());

public static String EncryptPassword(string password)
{
    var rijndaelCipher = new RijndaelManaged();
    byte[] plainText = Encoding.Unicode.GetBytes(password);
    var secretKey = new PasswordDeriveBytes(EncryptionKey, Salt);


    using (ICryptoTransform encryptor = rijndaelCipher.CreateEncryptor(secretKey.GetBytes(32), secretKey.GetBytes(16)))
    {
        using (var memoryStream = new MemoryStream())
        {
            using (var cryptoStream = new CryptoStream(memoryStream, encryptor, CryptoStreamMode.Write))
            {
                cryptoStream.Write(plainText, 0, plainText.Length);
                cryptoStream.FlushFinalBlock();
                return Convert.ToBase64String(memoryStream.ToArray());
            }
        }
    }
}

And this is what i an trying in angular

var enckey = "SomeSecretKEY";
var salt = CryptoJS.enc.Hex.parse(enckey.length.toString());
var key32Byte = CryptoJS.PBKDF2(enckey, salt, {
    keySize: 256 / 32
});
var iv = CryptoJS.PBKDF2(enckey, salt, {
    keySize: 128 / 32
});
var secret = CryptoJS.enc.Base64.parse("messageforencryption");
var enc = CryptoJS.AES.encrypt(secret, key32Byte.toString(), {"iv": iv.toString()});
console.log(enc.toString());

I have not access to change the already written C# method. Thanks in advance for any help.

4
  • Taking it one step at a time, have you tested that your code produces the same salt? Commented Sep 24, 2019 at 11:01
  • Yes, the salt is also different, Encoding.ASCII.GetBytes equivalent is not not there in cryptojs. Commented Sep 24, 2019 at 11:09
  • In crypto-js most of the things returning WordArray, so that i am not able to compare with c# getbyte() byte arrays. Commented Sep 24, 2019 at 11:11
  • 1
    On the C#-side the PasswordDeriveBytes-method is used to generate the password, on the JavaScript-side PBKDF2. PasswordDeriveBytes is a proprietary MS extension of PBKDF1, which cannot be reduced to PBKDF1 for a key larger than 20 bytes and/or a salt larger than 8 bytes. Therefore a change to PBKDF1 on the JavaScript-side is no solution. Since the C#-code obviously can't be changed, only the (expensive) implementation of the PasswordDeriveBytes-functionality on the JavaScript-side remains. Here PasswordDeriveBytes is explained. Commented Sep 24, 2019 at 17:16

0

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.