Different encryption results using C# and CryptoJS

前端 未结 1 1507
粉色の甜心
粉色の甜心 2020-12-20 05:27

I encrypt some data using AES in a server application, which is written in C#. I use a predefined key (32 bytes) and IV (16 bytes), for instance...

Key: 81fe         


        
相关标签:
1条回答
  • 2020-12-20 06:11

    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/

    0 讨论(0)
提交回复
热议问题