Skip to content

Instantly share code, notes, and snippets.

@guntidheerajkumar
Created February 16, 2021 17:18
Show Gist options
  • Save guntidheerajkumar/6287cc244ca398e4cf2020fbce6857a5 to your computer and use it in GitHub Desktop.
Save guntidheerajkumar/6287cc244ca398e4cf2020fbce6857a5 to your computer and use it in GitHub Desktop.
public class EncryptDecrypt
{
public (string Key, string IVBase64) InitSymmetricEncryptionKeyIV()
{
var key = GetEncodedRandomString(32); // 256
Aes cipher = CreateCipher(key);
var IVBase64 = Convert.ToBase64String(cipher.IV);
return (key, IVBase64);
}
private string GetEncodedRandomString(int length)
{
var base64 = Convert.ToBase64String(GenerateRandomBytes(length));
return base64;
}
private Aes CreateCipher(string keyBase64)
{
// Default values: Keysize 256, Padding PKC27
Aes cipher = Aes.Create();
cipher.Mode = CipherMode.CBC; // Ensure the integrity of the ciphertext if using CBC
cipher.Padding = PaddingMode.ISO10126;
cipher.Key = Convert.FromBase64String(keyBase64);
return cipher;
}
private byte[] GenerateRandomBytes(int length)
{
var byteArray = new byte[length];
RandomNumberGenerator.Fill(byteArray);
return byteArray;
}
public string Encrypt(string text, string IV, string key)
{
Aes cipher = CreateCipher(key);
cipher.IV = Convert.FromBase64String(IV);
ICryptoTransform cryptTransform = cipher.CreateEncryptor();
byte[] plaintext = Encoding.UTF8.GetBytes(text);
byte[] cipherText = cryptTransform.TransformFinalBlock(plaintext, 0, plaintext.Length);
return Convert.ToBase64String(cipherText);
}
public string Decrypt(string encryptedText, string IV, string key)
{
Aes cipher = CreateCipher(key);
cipher.IV = Convert.FromBase64String(IV);
ICryptoTransform cryptTransform = cipher.CreateDecryptor();
byte[] encryptedBytes = Convert.FromBase64String(encryptedText);
byte[] plainBytes = cryptTransform.TransformFinalBlock(encryptedBytes, 0, encryptedBytes.Length);
return Encoding.UTF8.GetString(plainBytes);
}
}
@guntidheerajkumar
Copy link
Author

guntidheerajkumar commented Feb 16, 2021

var symmetricEncryptDecrypt = new SymmetricEncryptDecrypt();
var (Key, IVBase64) = symmetricEncryptDecrypt.InitSymmetricEncryptionKeyIV();

EmployeeName = symmetricEncryptDecrypt.Encrypt(HREzeEmployeeDetail.FullName, IVBase64, Key);
var dataVal = symmetricEncryptDecrypt.Decrypt(EmployeeName, IVBase64, Key);

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment