Encrypt using JavaScript and Decrypt using C#

In today’s digital world, ensuring the security and privacy of data is a top priority. One of the fundamental techniques to safeguard sensitive information is encryption. But what exactly is encryption, and why is it so important? In this article, we’ll explore encryption and decryption concepts and how to use AES encryption through CryptoJS in JavaScript and .NET for secure data handling.

What is Encryption?

Encryption is the process of converting plain text (readable data) into a coded format (ciphertext) using a key and an algorithm. This process ensures that even if unauthorized users intercept the data, they won’t be able to make sense of it without the correct decryption key.

Decryption, on the other hand, is the reverse process, where ciphertext is converted back into the original plain text using the appropriate key.

Why Do We Need Encryption?

Encryption is essential for protecting sensitive information from unauthorized access, ensuring data privacy, and maintaining the integrity of communication. Some common scenarios where encryption is used include:

  • Protecting login credentials (passwords, PINs)

  • Securing communication (emails, chat messages)

  • Encrypting financial transactions (bank account details, credit card numbers)

What is AES Encryption?

AES (Advanced Encryption Standard) is one of the most widely used encryption algorithms, known for its speed and security. It is a symmetric encryption algorithm, meaning that the same key is used for both encryption and decryption. AES supports multiple key sizes: 128-bit, 192-bit, and 256-bit, with 128-bit being the most commonly used.

In this article, we will look at how AES is implemented using CryptoJS for JavaScript encryption on the client side and .NET for decryption on the server side.

Implementing AES Encryption with CryptoJS

Step 1: Setup HTML Markup

You will need to create the user interface with the necessary HTML controls:

<asp:TextBox ID="txtPlain" runat="server" placeholder="Enter text to encrypt" />
<asp:Button ID="btnSubmit" runat="server" Text="Submit" OnClientClick="Encrypt()" OnClick="Submit" />
<hr />
<asp:Label ID="lblDecrypted" runat="server" />
  • TextBox (txtPlain): For entering the plain text that needs to be encrypted.

  • Button (btnSubmit): To trigger the encryption process.

  • Label (lblDecrypted): To display the decrypted text.

Step 2: Including CryptoJS

To use AES encryption in JavaScript, you need to include the CryptoJS library, which provides the AES algorithm.

<script src="https://cdnjs.cloudflare.com/ajax/libs/crypto-js/4.2.0/crypto-js.min.js" integrity="sha512-a+SUDuwNzXDvz4XrIcXHuCf089/iJAoN4lmrXJg18XnduKK6YlDHNRalv4yd1N40OKI80tFidF+rqTFKGPoWFQ==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>

Step 3: Encrypting the Text

Now, we write the JavaScript function to encrypt the text when the user clicks the submit button:

// Secret Key.
var secretKey = "$ASPcAwSNIgcPPEoTSa0ODw#";

// Secret Bytes.
var secretBytes = CryptoJS.enc.Utf8.parse(secretKey);

function Encrypt() {
    // Read the Plain text.
    var txtPlain = document.getElementById("<%=txtPlain.ClientID%>");
    
    // Encrypt with AES Algorithm using Secret Key.
    var encrypted = CryptoJS.AES.encrypt(txtPlain.value, secretBytes, {
        mode: CryptoJS.mode.ECB,
        padding: CryptoJS.pad.Pkcs7
    });

    // Set the encrypted text in TextBox.
    txtPlain.value = encrypted;
}

Decrypting the Encrypted Text using C# (.NET)

While the encryption happens on the client side using JavaScript, the decryption is typically performed on the server side for security reasons. Here's how to decrypt the AES encrypted text using C# in a .NET environment.

Step 1: Decryption Method

In C#, the decryption involves converting the encrypted text from Base64 and using the same key and AES algorithm to decrypt it.

protected void Submit(object sender, EventArgs e)
{
    lblDecrypted.Text = this.Decrypt(Request.Form[txtPlain.UniqueID]);
}

private string Decrypt(string encryptedText)
{
    // Secret Key.
    string secretKey = "$ASPcAwSNIgcPPEoTSa0ODw#";

    // Secret Bytes.
    byte[] secretBytes = Encoding.UTF8.GetBytes(secretKey);

    // Encrypted Bytes.
    byte[] encryptedBytes = Convert.FromBase64String(encryptedText);

    // Decrypt with AES Algorithm using Secret Key.
    using (Aes aes = Aes.Create())
    {
        aes.Key = secretBytes;
        aes.Mode = CipherMode.ECB;
        aes.Padding = PaddingMode.PKCS7;

        byte[] decryptedBytes = null;
        using (ICryptoTransform decryptor = aes.CreateDecryptor())
        {
            decryptedBytes = decryptor.TransformFinalBlock(encryptedBytes, 0, encryptedBytes.Length);
        }
        return Encoding.UTF8.GetString(decryptedBytes);
    }
}

Conclusion

In this blog, we have learned about the encryption and decryption process, focusing on AES encryption and its implementation using CryptoJS on the client side and .NET on the server side. AES provides a secure way to protect sensitive information during transmission, ensuring that even if data is intercepted, it remains unreadable without the decryption key.

Key Takeaways

  • Encryption transforms data into an unreadable format using a secret key and algorithm.

  • Decryption converts the encrypted data back into its original form.

  • AES is a symmetric encryption algorithm commonly used for securing data.

  • CryptoJS provides an easy way to perform AES encryption on the client side in JavaScript.

  • The .NET framework allows you to decrypt AES encrypted text securely on the server side.

By using these techniques, you can significantly improve the security of sensitive information in your web applications.