Utilize C# encryption functionality with CryptoJS library

I am facing a scenario where I need to replicate an encryption method that is currently implemented in C#. The idea is to use the same C# project to decrypt the encrypted key from wherever it is logged.

Below is the logic utilized in C#:

using var aes = new AesCryptoServiceProvider
{
Key = Encoding.UTF8.GetBytes(key),
Mode = CipherMode.CBC,
Padding = PaddingMode.PKCS7
};
aes.GenerateIV();

using var encrypter = aes.CreateEncryptor(aes.Key, aes.IV);
using var cipherStream = new MemoryStream();
using (var tCryptoStream = new CryptoStream(cipherStream, encrypter, CryptoStreamMode.Write))
using (var tBinaryWriter = new BinaryWriter(tCryptoStream))
{
cipherStream.Write(aes.IV);
tBinaryWriter.Write(Encoding.UTF8.GetBytes(encryptMe));
tCryptoStream.FlushFinalBlock();
}
return Convert.ToBase64String(cipherStream.ToArray());

The key used is the same in both the C# and JavaScript implementations. However, I am still unable to generate the same encryption value as in C#.

I have attempted to find solutions on other Stack Overflow posts regarding this issue, but I have not been able to identify the missing element in my JavaScript implementation. Can someone please assist me?

Answer №1

In the C# code, the key is encoded in UTF-8 format. To work with CryptoJS, the key needs to be converted into a WordArray using the UTF-8 encoder. If the key is passed as a string in CryptoJS, it would be interpreted as a password and not compatible with the C# code which expects it as a key.
Furthermore, the C# code combines the IV and ciphertext, a step that must also be done in CryptoJS for successful decryption.

Revised code:

var plaintext = 'The quick brown fox jumps over the lazy dog';
var key = CryptoJS.enc.Utf8.parse('01234567890123456789012345678901'); // Fix 1: parse as WordArray
var iv = CryptoJS.lib.WordArray.random(128 / 8);
var encrypted = CryptoJS.AES.encrypt(plaintext, key, {iv: iv}); // CBC, PKCS#7 padding by default
var ivCiphertext = iv.clone().concat(encrypted.ciphertext).toString(CryptoJS.enc.Base64); // Fix 2: concatenate IV and ciphertext
console.log(ivCiphertext); // e.g. e9iXcQ2sZ6AA2ne1c3490pAPWOrTGf4UttSSX1lOiKUqwP0oWRPFF83VhZQZMMBu9JKNWIfgS+9D5V39bI4rqg==
<script src="https://cdnjs.cloudflare.com/ajax/libs/crypto-js/4.1.1/crypto-js.min.js"></script>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Hide content when clicking on the body

I have successfully implemented a collapsible sidebar triggered by a single button using the code below: <a class="btn btn-tocanvas-report" href="#" id="btnOpenSidebarListMenuReport" role="button" aria-controls=&q ...

Building CSS Using TagBuilder in .NET Core

Can you provide guidance on utilizing the Tag Builder CSS Class? I am interested in integrating it into a style class .custom-image { max-width: 100%; max-height: 100%; padding: 0; background-color: white; } TagBuilder image = new TagBuilder("img"); Wh ...

Automatically close the multiselect dropdown when the user interacts outside of it (varied scenario)

For those interested, check out this jsfiddle link: http://jsfiddle.net/jaredwilli/vUSPu/ This specific code snippet focuses on creating a multi-select dropdown feature. When a user chooses options from the dropdown and then clicks outside of the menu are ...

Using Rails: How can I insert form data upon clicking?

In my Rails application, I have a basic form for shipping details: <% form_for shipping_object do |f| %> <%= f.text_field :address1, :placeholder => "Address Line 1*", :class => "forms" %><br/> <%= f.text_field :address2, :place ...

Creating a Drop Down menu from backend code using C#

I'm attempting to create a dropdown list from the code behind, but I keep encountering this error: Object reference not set to an instance of an object. Line 101: ddlGroupName1.DataSource = cmd.ExecuteReader(); Could someone please assist? Here is m ...

Adjust the color and surface appearance using three.js

Struggling to modify the color and image of a material, I attempted to do so with the code below: material = new THREE.MeshPhongMaterial({map:THREE.ImageUtils.loadTexture('3d/caneca/e.jpg')}); Unfortunately, my attempts were unsuccessful. The o ...

Javascript eval function providing inaccurate results

I have encountered a problem while using eval() for a calculator I am developing. When I input the following code: console.log(eval("5.2-5")); The output is: 0.20000000000000018 I am confused as to why this is happening. Thank you for your assistance. ...

Showcasing solely the latest entry in the database utilizing nodeJS

I am having an issue with my code where it is only displaying the last record from the database. How can I modify it to display all the records from the database using nodeJS? Any assistance would be greatly appreciated. Thank you. var express = require ...

Seeking assistance with Shopify - Enhancing User Experience with Javascript Cookies

Is there a way to adjust the settings of how long Shopify stores cookies on your computer for? Currently, it retains cart information for two weeks. Any suggestions on how to modify this? I am considering two possibilities: 1) Making shopping members-only ...

In order for data with two fields to be displayed correctly in an angular.js table, it must be shown twice

Within my angular.js table, data is being received and stored in a variable called dataArr. var dataArr = [ 0: "aaa", 1: "bbb" ] I have a condition that if the length of the data is greater than 0, it must be displayed twice in the table structure. For i ...

Ways to enhance error messages and improve handling of NullReferenceException exceptions

Background When working in Unity, encountering a NullReferenceException only results in an error log without triggering the IDE's debug mode. This can make it challenging for developers to consistently reproduce bugs that occur within their games. O ...

Integrating a footer into the enhanced search tab slider

I'm struggling to create a sticky footer like the one on w3schools. Even though I used the same code in my material UI demo, it's not functioning properly. I tried debugging by changing the position from fixed to absolute, but it still isn&apos ...

Retrieving information from the logger to provide back to the web application

I'm almost there, but not quite. The logger is showing the search results, but I still can't get them to display on the web app. The search function works on the web app and the results show up in the logger. Any advice would be appreciated. Th ...

What is causing the Android emulator to malfunction on the .net Maui project I'm working on?

As a newcomer to .NET MAUI, I recently started following the instructions on Microsoft's website to create my first .NET MAUI app. However, I encountered an issue when trying to set up the Android emulator as instructed. A message appeared stating "Th ...

Breaking the website with an HTML comment

Upon clicking a link to another page, I encountered the error message "Failed to execute 'insertBefore' on 'Node." Here is the code snippet that was causing the issue: <template name="reminderPage"> <a href="/newRemind">New! ...

Comparing Data Access Methods: Fluent NHibernate, ADO.NET, and Linq to SQL

Working on my Windows Form Application and utilizing ADO.Net as the Data Access layer with SQL Server as the Back End, complete with numerous stored procedures. Should I continue using ADO.NET or should I switch to learning FnH or Linq to SQL? Which path ...

What is the method for updating state in React without relying on any events to trigger

I am trying to continuously update the value of a counter variable at fixed intervals in my code. Here is what I have so far: class Counter extends React.Component { constructor(props) { super(props); this.state = { myCount: 1 ...

Switch out the innerHTML content and then revert back to the original while still preserving the events

Imagine you have a div called el with various components and events that are out of your control (like on mouse over and click). What if you wanted to insert a new widget inside this div? You might try something like this: var save = el.innerHTML; el.inn ...

How can you move away from using the url:port scheme with socket.io?

Recently, I've been delving into node.js and socket.io, but I'm struggling to eliminate the need to type "url:port" in the browser. Instead, I want users to simply enter the URL and have everything load up, similar to my work-in-progress single p ...

the language of regular expressions expressed in strings

As a beginner in Javascript and regular expressions, I found myself stuck on how to create a route that matches all URLs starting with /user/.... Initially, I thought of using app.get(/user/, function(req, res){ /*stuff*/}); However, curiosity led me to ...