Different encryption results using C# and CryptoJS

人走茶凉 提交于 2019-11-29 12:58:20

For the write there was a problem with the flushing of the blocks. The FlushFinalBlock() is distinct from the Flush() (or from the FlushAsync()). You have to do them both, or simply dispose the CryptoStream. This will solve the fact that the code wasn't writing the last block of data.

async static Task<byte[]> Encrypt(string privateKey, string pin, byte[] data)
{
    using (var sha = SHA256.Create())
    {
        byte[] keyHash = sha.ComputeHash(Encoding.UTF8.GetBytes($"{privateKey}"));
        byte[] pinHash = sha.ComputeHash(Encoding.UTF8.GetBytes($"{pin}"));
        using (Aes aes = Aes.Create())
        {
            byte[] key = keyHash.Slice(0, aes.Key.Length);
            byte[] iv = pinHash.Slice(0, aes.IV.Length);

            Trace.WriteLine($"Key length: { key.Length }, iv length: { iv.Length }, block mode: { aes.Mode }, padding: { aes.Padding }");

            using (var stream = new MemoryStream())
            using (ICryptoTransform transform = aes.CreateEncryptor(key, iv))
            {
                using (var cryptStream = new CryptoStream(stream, transform, CryptoStreamMode.Write))
                {
                    await cryptStream.WriteAsync(data, 0, data.Length);
                }

                return stream.ToArray();
            }
        }
    }
}

The typescript code seems to be able to decrypt it.

Working fiddle: https://jsfiddle.net/uj58twrr/3/

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!