0

I'm trying for some time to encrypt a message in AES that use a C# app , but it never works . Can someone help me?

Javascript

const cryptojs = require("crypto-js");

cryptojs.AES.decrypt( ciphertext, "gpubphkxqdrkizxgyomipluuyfkvhnci");

C#

public static string Encrypt(string plainText, string keyString) {
            byte[] cipherData;
            Aes aes = Aes.Create();
            aes.Key = Encoding.UTF8.GetBytes(keyString);
            aes.Mode = CipherMode.CBC;//ECB and CBC
            aes.Padding = PaddingMode.PKCS7;
            //aes.BlockSize = 4;
            //aes.KeySize = 128 / 8;
            aes.GenerateIV();
            ICryptoTransform cipher = aes.CreateEncryptor(aes.Key, aes.IV);

            using (MemoryStream ms = new MemoryStream()) {
                using (CryptoStream cs = new CryptoStream(ms, cipher, CryptoStreamMode.Write)) {
                    using (StreamWriter sw = new StreamWriter(cs)) {
                        sw.Write(plainText);
                    }
                }
                cipherData = ms.ToArray();
            }

            byte[] combinedData = new byte[aes.IV.Length + cipherData.Length];
            Array.Copy(aes.IV, 0, combinedData, 0, aes.IV.Length);
            Array.Copy(cipherData, 0, combinedData, aes.IV.Length, cipherData.Length);
            
            return Convert.ToBase64String(combinedData);
        }
  • 1
    Did any of the many other cryptojs / C# questions help you? You _did_ research those before posting, right? – ProgrammingLlama Sep 07 '21 at 07:50
  • c # other questions did not help – Bataa Bataa Sep 07 '21 at 08:02
  • 2
    So I presume [this question](https://stackoverflow.com/questions/63081553/aes-encryption-with-c-sharp-decryption-with-crypto-js) was of no use? Or [this one](https://stackoverflow.com/questions/47891104/compatible-aes-encryption-and-decryption-for-c-sharp-and-javascript)? – ProgrammingLlama Sep 07 '21 at 08:04
  • 1
    I assume your aim is to encrypt some data in C# and to decrypt the data in CryptoJs ? Your CryptoJs decryption code is using a key derivation function to derive an AES-256 key because your input is a passphrase (and not a key). In this question "https://stackoverflow.com/q/63081553/8166854" (linked before by @Llama) you find the "DeriveKeyAndIv" function that is doing the job for you, it derives an AES-256 encryption key and the IV you need for your AES-256-CBC encryption function in C#. – Michael Fehr Sep 07 '21 at 09:41
  • The C# code works and does not need to be changed. What is missing in the CryptoJS code is 1. the separation of IV and ciphertext, 2. the passing of the IV as `WordArray` and the ciphertext as Base64 encoded string or as `CipherParams` object and 3. the conversion of the key into a `WordArray` with the Utf8 encoder. Then decryption works. You can apply 1:1 the JavaScript code from [this answer](https://stackoverflow.com/a/68411945). – Topaco Sep 07 '21 at 10:47

0 Answers0