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
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/