0

I created this method to encryped string with a key:

 public static string EncryptString(string key, string plainText)
        {
            byte[] iv = new byte[16];
            byte[] array;

            using (Aes aes = Aes.Create())
            {
                aes.Key = Encoding.UTF8.GetBytes(key);
                aes.IV = iv;

                ICryptoTransform encryptor = aes.CreateEncryptor(aes.Key, aes.IV);

                using (MemoryStream memoryStream = new MemoryStream())
                {
                    using (CryptoStream cryptoStream = new CryptoStream((Stream)memoryStream, encryptor, CryptoStreamMode.Write))
                    {
                        using (StreamWriter streamWriter = new StreamWriter((Stream)cryptoStream))
                        {
                            streamWriter.Write(plainText);
                        }

                        array = memoryStream.ToArray();
                    }
                }
            }

            return Convert.ToBase64String(array);
        }

But I also need this method in JS, to also decrypt the same string.

I am wondering about

AES, Encoding.UTF8.GetBytes, ICryptoTransform, Cryptostreammode, and MemoryStream.

Do these exist in JS?

IS this method even usable in JS?

2
  • 1
    AES encryption is of course possible in JavaScript. A 1:1 porting, however, is generally not feasible, i.e. you have to implement it using the respective JavaScript library's own constructs. Commented Feb 8, 2022 at 11:02
  • 1
    Where will this JavaScript run? In a browser? If so you don't want to decrypt it there because you would have to expose the key. Commented Feb 8, 2022 at 11:49

1 Answer 1

1

Using your C# code to encrypt a string via public static string EncryptString(string key, string plainText) I get following result:

EncryptString("xxxxxxxxxxxxxxxx", "Hello World") -> "yM377gXxX5Du71hgkPH+Fg=="

To reverse this you can check out this Javascript code:

const key = "xxxxxxxxxxxxxxxx";
const msg = "yM377gXxX5Du71hgkPH+Fg==";

const decrypted = CryptoJS.AES.decrypt(
  msg, 
  CryptoJS.enc.Utf8.parse(key),
  { mode: CryptoJS.mode.ECB }
);

console.log(decrypted.toString(CryptoJS.enc.Utf8));
<script src="https://cdnjs.cloudflare.com/ajax/libs/crypto-js/4.1.1/crypto-js.min.js"></script>

Sign up to request clarification or add additional context in comments.

1 Comment

We decided to run this logic in our c# backend now, but your logic seems totally fine. Awesome!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.