Created
February 16, 2021 17:18
-
-
Save guntidheerajkumar/6287cc244ca398e4cf2020fbce6857a5 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | |
} | |
} |
Author
guntidheerajkumar
commented
Feb 16, 2021
•
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment