AES (Advanced Encryption Standard) is a widely used symmetric encryption algorithm that employs a block cipher technique to secure sensitive data. It is known for its strong security features and versatility, making it the preferred choice for safeguarding digital information in various applications, including online communications, data storage, and electronic transactions.
Advantages of AES Encryption
- High Security
- Standardization and Wide Adoption
- Efficiency and Speed
- Versatility
- Symmetric Encryption
- Resilience to Cryptanalysis
- Hardware and Software Support
- Proven Track Record
Here is a step by step explanation of how to use AES Encryption in WebAPI along with an example.
Step 1: Install the required packages to use AES Encryption ,we need to install the Cryptography package. You can do this by using a package manager like NuGet. Open the NuGet Package Manager and download the following packages:
System.Security.Cryptography
Step 2: Create required Models
Request Model
namespace AESExample.Models
{
public class WordModel
{
public string Data { get; set; }
}
}
Response Model
namespace AESExample.Models
{
public class DecryptModel
{
public string Key { get; set; }
public string EncryptedData { get; set; }
}
}
Step 3: Create a class for AES encryption and decryption methods
using System.Security.Cryptography;
using System.Text;
namespace AESExample.Models
{
public class AesHelper
{
private const int KeySizeInBits = 128;
public byte[] GenerateAesKey()
{
using (var aes = Aes.Create())
{
aes.KeySize = KeySizeInBits;
aes.GenerateKey();
return aes.Key;
}
}
public byte[] Encrypt(string plaintext, byte[] key)
{
byte[] plaintextBytes = Encoding.UTF8.GetBytes(plaintext);
using (var aes = Aes.Create())
{
aes.KeySize = KeySizeInBits;
aes.Key = key;
aes.Mode = CipherMode.ECB;
aes.Padding = PaddingMode.PKCS7;
using (var encryptor = aes.CreateEncryptor())
{
return encryptor.TransformFinalBlock(plaintextBytes, 0, plaintextBytes.Length);
}
}
}
public string Decrypt(byte[] ciphertext, byte[] key)
{
using (var aes = Aes.Create())
{
aes.KeySize = KeySizeInBits;
aes.Key = key;
aes.Mode = CipherMode.ECB;
aes.Padding = PaddingMode.PKCS7;
using (var decryptor = aes.CreateDecryptor())
{
byte[] decryptedBytes = decryptor.TransformFinalBlock(ciphertext, 0, ciphertext.Length);
return Encoding.UTF8.GetString(decryptedBytes);
}
}
}
Here,
GenerateAesKey():
This method generates a random AES key of the specified key size (128 bits in this case)
Encrypt(string plaintext, byte[] key):
This method takes a plaintext string and an AES key as input. It converts the plaintext to a byte array, creates an AES object, sets the key and other encryption parameters (such as Cipher Mode and Padding Mode), and then performs AES encryption using the ECB (Electronic Codebook) mode. The encrypted data is returned as a byte array.
Decrypt(byte[] ciphertext, byte[] key):
This method takes a byte array of encrypted data and an AES key as input. It creates an AES object, sets the key and encryption parameters, and then performs AES decryption using the ECB mode. The decrypted data is returned as a UTF-8 encoded string
Step 3: Create a controller.
using AESExample.Models;
using Microsoft.AspNetCore.Mvc;
using System.Security.Cryptography;
namespace AESExample.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class AESController : ControllerBase
{
private readonly AesHelper aesHelper;
public AESController()
{
aesHelper = new AesHelper();
}
[HttpPost("encrypt")]
public IActionResult EncryptData( WordModel wordModel)
{
byte[] aesKey = aesHelper.GenerateAesKey();
byte[] encryptedData = aesHelper.Encrypt(wordModel.Data, aesKey);
string encryptedText = Convert.ToBase64String(encryptedData);
var response = new
{
Key = Convert.ToBase64String(aesKey),
EncryptedData = encryptedText
};
return Ok(response);
}
[HttpPost("decrypt")]
public IActionResult DecryptData( DecryptModel decryptModel)
{
byte[] aesKey = Convert.FromBase64String(decryptModel.Key);
byte[] encryptedData = Convert.FromBase64String(decryptModel.EncryptedData);
string decryptedText = aesHelper.Decrypt(encryptedData, aesKey);
return Ok(decryptedText);
}
}
}
EncryptData :
The action takes a WordModel object as input, which is expected to contain the property Data (representing the plaintext to be encrypted).
A new AES key is generated using the GenerateAesKey method from the AesHelper.
The Encrypt method from the AesHelper is called to encrypt the plaintext (wordModel.Data) using the generated AES key. The encrypted data is then converted to a Base64 string to ensure it can be safely represented in text format.
The response is constructed as an anonymous object containing the Key (the Base64-encoded AES key) and EncryptedData (the Base64-encoded encrypted text).
DecryptData :
The action takes a DecryptModel object as input, which is expected to contain the properties Key (representing the Base64-encoded AES key) and EncryptedData (representing the Base64-encoded encrypted text).
The Base64-encoded AES key and encrypted data are converted back to byte arrays using Convert.FromBase64String.
The Decrypt method from the AesHelper is called to decrypt the data using the provided AES key.
The decrypted plaintext is returned in the response
In conclusion, AES encryption stands as a powerful tool for securing sensitive data in the digital world. Its strong security, standardization, and efficiency make it a popular choice for protecting information across various applications.
No Comment! Be the first one.