Click here to Skip to main content
15,881,600 members
Please Sign up or sign in to vote.
5.00/5 (1 vote)
See more:
Hi!
I have two apps that communicate between them with encrypted data. Nodejs app sends the encrypted data and the WEBAPI made in C# receive it and decrypt it. My problem is when I'm trying to decrypt AES encrypted data I receive this error :

System.Security.Cryptography.CryptographicException: 'Specified initialization vector (IV) does not match the block size for this algorithm.'


For decryption I'm using this class :

C#
public static string AESDecrypt(string cipherText, string keyBase64, string vectorBase64)
        {
            using (Aes aesAlgorithm = Aes.Create())
            {
                System.Diagnostics.Debug.WriteLine($"ciphertext : {cipherText}, keybase64 : {keyBase64}, vectorBase64 : {vectorBase64}");

                aesAlgorithm.Key = Convert.FromBase64String(keyBase64);


                // I'm receiving the error here
                aesAlgorithm.IV = Convert.FromBase64String(vectorBase64);


                Console.WriteLine($"Aes Cipher Mode : {aesAlgorithm.Mode}");
                Console.WriteLine($"Aes Padding Mode: {aesAlgorithm.Padding}");
                Console.WriteLine($"Aes Key Size : {aesAlgorithm.KeySize}");
                Console.WriteLine($"Aes Block Size : {aesAlgorithm.BlockSize}");

                // Create decryptor object
                ICryptoTransform decryptor = aesAlgorithm.CreateDecryptor();

                byte[] cipher = Convert.FromBase64String(cipherText);

                //Decryption will be done in a memory stream through a CryptoStream object
                using (MemoryStream ms = new MemoryStream(cipher))
                {
                    using (CryptoStream cs = new CryptoStream(ms, decryptor, CryptoStreamMode.Read))
                    {
                        using (StreamReader sr = new StreamReader(cs))
                        {
                            return sr.ReadToEnd();
                        }
                    }
                }
            }

        }


The data is encrypted in NodeJS app with this function :

JavaScript
const keyfile = getKey(PATHTOFILE);
const aesKeyFileContent = JSON.parse(rsaDecryption(keyfile.toString()));
const encrypter = crypto.createCipheriv('aes-256-cbc', aesKeyFileContent.password.toString(), aesKeyFileContent.iv.toString());
let encryptedMsg = encrypter.update(string, 'utf-8', 'hex');
encryptedMsg += encrypter.final('hex');
return encryptedMsg;



The data I want to decrypt :

e197a391deb9a20ba5612c3199f40003a8253b55ab3d8977fa753a7ca45987092b251720dd296d962b850ef2527b9729608fd5e75c127da5789413b743d0629ad032db372d59dd19680745710b7dd4a1acf06af29cdb6a1338e5404347a645916db2e768a0b45d4748c9d59992b929b2cd12aa6f6424c679db0f770100c0298753101cfc12583601e423f37f492c63181d926add0209bf5fa2fc65bb094135e3dd5a567486368a755db87433916ba8b9f40a4984370eb25e05b70e602ff11f5b09b1722e1d8255504d4c96819e6e66350252b155ee6f0108c282126ac59d2276bfbc40f6d3fdc2720bc9f35a1b94b4867676c840596fc2cfdad604f264e791c72b5bce11a4892dedd9927c7ceb4b9b39eb642da2bea3a4d654c5d5a0971b88ca3289edf305b6afd8a55075ed27009648cafb9d964971313c02357157467235c1fcd634c574a8cd88e64ddfa2d64535f6970ad6326bf22be50da066b1bca1a2f32af9e96c227aa22996d73f7686af69ddc663603eb78c0e1d83bac081703691389d87e7d8723e500f868f02e8baff52b143aa067a8feb3fb78c97cc435c591ea783398b6d3518254c852c4c53595cb8dd0cd645b3513d0357fdb04a366d600dbca1ea3aa251577c611fc26a75556d85454a9c55fdec20d50268dcfd19a67824e87ad9a7d023ba696f5a3b6d1cf9fae06f93397077ce785500586c6462bec90a91e495ee0fa8b88b93f144b687fe00b7284958ea53a6921f2f8fe2775444cd12fa932f9302868f9f124b877484f63d61499e296ca9f0747cc3221a6361d40e44dfd177216dfdbd9ec711d7e27bdcfe7005f0321a15783cff1b8ff14bb70e26144a0878cbf66003eade0c166940474ca16f949d5e37a563c9e86f1f09f52f9cf3b3643a8f48cf06cb5890a41a8408f55bb0fd4a13fb2917bddb80903ff80384e191f6d914cf0baee55d698e38e6376b3e73609f12288dd4a0b846f25ceca714126a2b9c9f720b54c3859014a9664f2626b344b5ed41e3558f3c8d9c1d101e48f9b4032db4d68fa6fc37b32628fe222026fdde07e3edb62088fc6e94d1f8c0655fb4322a1448e6ebe9898dc256c47041e3c751bce5dbcbdd47f8f629078e7453ff07abc6348b380f4a9960e04dc32730d0a173df39fbcc1ac4e473b86f3f8211a5f194434667e8efc5ef4c0cdcd124bbdc5f265dae33fdec0467c16e1073f8f9cd4c7f937af68917e5ae7d80d66abfa859e3b03b6673833e2fd9f2d131dff849a229a7d38fa3c855aa3516754a4fde0ec503ff98d6e66f24a8b6b2e3b4501398d140b4e5a46acc694e54dd745dc030ee30ffba13f3c535a393fdc9192c21d088dd75cbd65888823aff0be52c95c3ba090d54bdcd571750b212ef2e768f86c73e3d3f4b6f730e09f9cef13e3bfb578bc439888ea34f22a69cd2ac7f7a7305c0e017ba4283c5ad4c449684030493fe5f0820fdbd966414f4c6720b0e85690e58cfd87a409c032e5d3638694c97be4aa70a77296b4205dbc248628db5bd50d51aea2504614ffee0fe9b70605d121d3f38f86df619dea7fd30335a7db092b2d41fd823abc53318e84439b72972cfcf66ca2c954dd4dd8e6f5d5bc0783067112a886d2cc607fe180615e385ae52d1b8ceb3e2352d745e9007d49f4a06b765a14bae8c010d322ab74639c3a5d999f17fcf34915a9b5ccb37a2e9f7448be506244e4f4f35fed39989318e44ab2798acfb0c7a827bb8eba30c34358529ab26a955b8f200deb5b7962f4d970147d1e89e6adc4188e3d3f01dd00000e1dbd7788b00e0f354c8fbbed6a7513e0c62e27827e79d095fdea15754152e2c4dd6f308fc4cfe8959049b340705d54b8a418daa333e25db5dff23ce1eab1f09904b867039c9963acdd1d6c625587634a5ba75f5e16011bef94525c77c3a30183f84a9dc13819bc340d130b3df5dcda2836f3b6645757b8f96f5239f400b169df2351f90ad432b9178ea358c3e76384f88e35b27b4d5906f177c589eea8119e18a555600ef0831cc6818340d54f6ea9f19301762e112746c9b9907a94fc7ac82edec4f7c03f4f766dd2d82a77a9d844772ab345c0e8830e3d51a821179755a48774bcafdeb02ce63df24134ce5b83c3f286ea32e5c2d09ec7ef7eda5a2fa3e595ec93cf825a395b7fc29f3473f286faeff79f13d1db02d5ce635962505ef774dde4ce5ce16876ea26a950318c465f4723a3ef01146810b90f8afcae4bc6259722ffc35ed487d8d7e8b3bab420021b2474000f6208fa9a1ef770bf7b06b915e15a3fac48e1eac3b593f7c216bfe04cb96d1f207f45bcf70cc7e07955d4c2f97f541c55af8dae5d5a6e6d82c939a2db63d5fc8c93eb312ce2a6edc3bc2a77cf6f36e1f79e59d8bfe2365e01d673ec46bdd409c755683ab8c01dcf5922525191697b5a744488e47bc89a2ce9c70bc2fec38c6a999f67c7ff0ec98ab36458c00a21a64b22dc56c4180c0fb9877c3fb86f1873aa76380a90a9ab803f12c67cfbeb5c827716c11fa0dc5de8d7290a67367021cc155eb492c57eb7564a0ebe12d574e461cc85a2a6734191980aa3bf235833b3fe9dc20d60ce8e8b4e0342179f08306e40eece7846e0b93e14c5d2041523825a18f975946d36f926f36efb6b11e59c99954d29f4ec5634103e4b49214e578457a75e3aa8d2a6d467b3f378b4d3e5a7cc9f7ad51bc81c4bde3b30dafdc18c5e99e790d0ab1e8bcbf937be8c6cef2d36cabfabc226cda2d930b84765b4c7a3daac47f9621114d5ee74383f8b895c694e6764354acaef9203f7167b5bab82c001a04e1ce679f50e72ce3c375691a2911fa733b2b89c8777322b0eabaf8584d8dba1246edc6588f200c742f55046127ece05231420e5be97fef86cf0ac2e12030c3e7b6e145355c2a9dc7f4b49829b62ed9d595d2ab24e8372c3b03f9c7dc24b098aa59e245542ecd29c7b13292078d2943a5527b21595ed0e55311685452769b75e1b4febb610fd4bb27145c939642af2aa8ceba70222512db5ce62228698f433478ce68c349773d2be2534b9968b61508b94a66a03f51daac416dd018b6898a6e5b7b7ddc60b7167f8b87cff36b6f8773402ba0ef6b35956c0c29a7237fab95cb62d9fc5f2c2f50fd24a7155b74eaaa648dbd4ec81890056e29ffbbe50a6aa3a20892d353ee9fe9ccc06551614c9884723d01e9f6dc352a82d64d824f4bd2e70ee252c61f09e85d46a1c6240417684758c3ea628307e4324d5a08b9e194da90193c91a7e1740ced90326d2fe9


I'm generating the password and IV with this in nodejs app :
JavaScript
const aesPassword = crypto.randomBytes(32).toString('hex').slice(0, 32);
const aesIV = crypto.randomBytes(16).toString('hex').slice(0, 16);




Password and IV I'm using :
Password : e35473525c979e3edff964067254f769
IV : 342e9269eb1741e8

What I have tried:

I've tried to assign a chipermode and paddingmode without succes.

C#
using (Aes aesAlgorithm = Aes.Create())
            {
                System.Diagnostics.Debug.WriteLine($"ciphertext : {cipherText}, keybase64 : {keyBase64}, vectorBase64 : {vectorBase64}");

                aesAlgorithm.Mode = CipherMode.CBC;
                aesAlgorithm.Padding = PaddingMode.PKCS7;
                aesAlgorithm.Key = Convert.FromBase64String(keyBase64);
                aesAlgorithm.IV = Convert.FromBase64String(vectorBase64);


                Console.WriteLine($"Aes Cipher Mode : {aesAlgorithm.Mode}");
                Console.WriteLine($"Aes Padding Mode: {aesAlgorithm.Padding}");
                Console.WriteLine($"Aes Key Size : {aesAlgorithm.KeySize}");
                Console.WriteLine($"Aes Block Size : {aesAlgorithm.BlockSize}");

                // Create decryptor object
                ICryptoTransform decryptor = aesAlgorithm.CreateDecryptor();

                byte[] cipher = Convert.FromBase64String(cipherText);

                //Decryption will be done in a memory stream through a CryptoStream object
                using (MemoryStream ms = new MemoryStream(cipher))
                {
                    using (CryptoStream cs = new CryptoStream(ms, decryptor, CryptoStreamMode.Read))
                    {
                        using (StreamReader sr = new StreamReader(cs))
                        {
                            return sr.ReadToEnd();
                        }
                    }
                }
            }
Posted
Updated 25-Oct-22 2:33am
v3
Comments
Peter_in_2780 25-Oct-22 5:58am    
The error message is pretty clear: The IV is the wrong length. It should be the size of one algorithm block.
Gaby94 25-Oct-22 6:13am    
Well I decrypted the same message with the same password and IV in nodejs and worked, why it doesn't work in C# ?

1 solution

You seem to be throwing strings at the Convert.FromBase64String method without understanding the content of the string, nor the purpose of the method.

In fact, none of the strings in your code are Base64-encoded[^].

Your key and IV are simply UTF8 strings; Node.js uses UTF8 to convert them to byte arrays:
C#
aesAlgorithm.Key = System.Text.Encoding.UTF8.GetBytes(keyBase64);
aesAlgorithm.IV = System.Text.Encoding.UTF8.GetBytes(vectorBase64);

Your ciphertext is not Base64-encoded either; since you specified hex as the output encoding, it's a simple hexadecimal representation of the byte array. If you're using .NET 5 or later, you can use the Convert.FromHexString[^] method:
C#
byte[] cipher = Convert.FromHexString(cipherText);
If you're stuck with an older version, you'll need to write your own - for example:
C#
static byte[] FromHexString(string input)
{
    if (string.IsNullOrEmpty(input)) return Array.Empty<byte>();
    if ((input.Length & 1) != 0) throw new ArgumentException("Invalid hex string length", nameof(input));
    
    byte[] result = new byte[input.Length >> 1];
    for (int index = 0, charIndex = 0; index < result.Length; index++, charIndex += 2)
    {
        char c1 = input[charIndex];
        char c2 = input[charIndex + 1];
        byte n1 = HexChar(c1);
        byte n2 = HexChar(c2);
        result[index] = (byte)(n1 << 4 | n2);
    }
    
    return result;
}

static byte HexChar(char c)
{
    if ('0' <= c && c <= '9') return (byte)(c - '0');
    if ('a' <= c && c <= 'f') return (byte)(c - 'a' + 10);
    if ('A' <= c && c <= 'F') return (byte)(c - 'A' + 10);
    throw new ArgumentException($"Invalid hex char: '{c}'", nameof(c));
}

With those changes in place, your ciphertext can be decrypted successfully:
JSON
{"SystemInformations":{"system":{"manufacturer":"VMware, Inc.","model":"VMware7,1","version":"None","serial":"VMware-56 4d e8 7d 71 8c 8f c6-cd 07 fc 3e 7b 55 2d 3e","uuid":"7de84d56-8c71-c68f-cd07-fc3e7b552d3e","sku":"","virtual":true,"virtualHost":"VMware"},"bios":{"vendor":"VMware, Inc.","version":"INTEL  - 6040000","releaseDate":"2019-08-15","revision":"","serial":"VMware-56 4d e8 7d 71 8c 8f c6-cd 07 fc 3e 7b 55 2d 3e"},"baseboard":{"manufacturer":"Intel Corporation","model":"440BX Desktop Reference Platform","version":"None","serial":"None","assetTag":"","memMax":269484032,"memSlots":64},"os":{"platform":"Windows","distro":"Microsoft Windows 10 Pro","release":"10.0.19044","codename":"","kernel":"10.0.19044","arch":"x64","hostname":"DESKTOP-JQSJAF8","fqdn":"DESKTOP-JQSJAF8","codepage":" 437","logofile":"windows","serial":"00331-10000-00001-AA192","build":"19044","servicepack":"0.0","uefi":true,"hypervisor":true,"remoteSession":false},"uuid":{"os":"261c0d95-2d66-4e37-a398-523901753bb9","hardware":"7de84d56-8c71-c68f-cd07-fc3e7b552d3e","macs":["00:0c:29:55:2d:3e"]},"cpu":{"manufacturer":"Intel","brand":"Core™ i9-9980HK","vendor":"GenuineIntel","family":"6","model":"158","stepping":"13","revision":"","voltage":"","speed":2.4,"speedMin":2.4,"speedMax":2.4,"governor":"","cores":4,"physicalCores":4,"processors":1,"socket":"ZIF Socket","flags":"de pse tsc msr mce sep mtrr mca cmov psn clfsh ds mmx fxsr sse sse2 ss htt tm ia64 pbe","virtualization":true,"cache":{"l1d":0,"l1i":0,"l2":"","l3":0}},"memLayout":[{"size":17179869184,"bank":"RAM slot #0","type":"DRAM","ecc":false,"clockSpeed":0,"formFactor":"DIMM","manufacturer":"VMware Virtual RAM","partNum":"VMW-16384MB","serialNum":"00000001","voltageConfigured":0,"voltageMin":0,"voltageMax":0}],"diskLayout":[{"device":"SCSI\\DISK&VEN_VMWARE_&PROD_VMWARE_VIRTUAL_S\\5&1EC51BF7&0&000000","type":"HD","name":"VMware, VMware Virtual S SCSI Disk Device","vendor":"","size":214745610240,"bytesPerSector":512,"totalCylinders":26108,"totalHeads":255,"totalSectors":419425020,"totalTracks":6657540,"tracksPerCylinder":255,"sectorsPerTrack":63,"firmwareRevision":"1.0","serialNum":"","interfaceType":"SCSI","smartStatus":"Ok","temperature":null}]},"ProductInformations":{"licensekey":"AAAA-AAAA-AAAA-AAAA","version":"1","prodType":"scada"}}
 
Share this answer
 
v2
Comments
Gaby94 25-Oct-22 8:41am    
Thanks you so much, I've been stuck for hours at this. I forgot to mention, I'm using .net framework 4.7.2 (Yes, I'm planning to move to .NET Core)

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900