Created
June 17, 2024 10:52
-
-
Save chrdek/d909610bba3d0c075fb7170cf80366e2 to your computer and use it in GitHub Desktop.
[Csharp] AES Galois Counter Mode Compliant Cipher Text Wrapper Example (plaintext or generated key)
This file contains 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 AESGCMBytes { //AES-GCM Core wrapper class starts here. | |
//auto-properties for internal values store | |
public byte[] tempKey {get; set;} | |
public byte[] tempTag {get; set;} | |
public byte[] cipherText {get; set;} | |
public byte[] tempNonce{get; set;} | |
public string Encrypt(string plainTextinput) { | |
var key = new byte[16]; //MaxSize of plaintext input Key = 16 characters | |
RandomNumberGenerator.Fill(Encoding.UTF8.GetBytes("Test1NG12456O@K!")); | |
Console.WriteLine("Default key length ="+key.Length); | |
this.tempKey = key; | |
using var aes = new AesGcm(key); | |
var nonce = new byte[AesGcm.NonceByteSizes.MaxSize]; // MaxSize = 12 | |
RandomNumberGenerator.Fill(nonce); | |
var plaintextBytes = Encoding.UTF8.GetBytes(plainTextinput); | |
var ciphertext = new byte[plaintextBytes.Length]; | |
var tag = new byte[AesGcm.TagByteSizes.MaxSize]; // MaxSize = 16 | |
aes.Encrypt(nonce, plaintextBytes, ciphertext, tag); | |
this.cipherText = ciphertext; | |
this.tempNonce = nonce; | |
this.tempTag = tag; | |
return Encoding.UTF8.GetString(ciphertext); //Convert.ToBase64String(ciphertext); ///Use Base64 for network based transmissions , web | |
} | |
public string Decrypt(byte[] ciphertext, byte[] nonce, byte[] tag, byte[] key) | |
{ | |
using (var aes = new AesGcm(key)) | |
{ | |
var plaintextBytes = new byte[ciphertext.Length]; | |
aes.Decrypt(nonce, ciphertext, tag, plaintextBytes); | |
return Encoding.UTF8.GetString(plaintextBytes); //Use Base64 for network based transmissions , web | |
} | |
} | |
} // Core wrapper AES-GCM class end here.. | |
void Main() | |
{ | |
AESGCMBytes EncrDecrClass = new AESGCMBytes(); | |
string strinput = "t/f90j230-k23fm\"''3'2"; | |
string cipherCopy = EncrDecrClass.Encrypt(strinput); | |
Console.WriteLine("Encrypted resulting GCM string = "+EncrDecrClass.Encrypt(strinput)); | |
Console.WriteLine("Key = "+Encoding.UTF8.GetString(EncrDecrClass.tempKey)); | |
Console.WriteLine("Decrypted resulting GCM string = "+EncrDecrClass.Decrypt(EncrDecrClass.cipherText, | |
EncrDecrClass.tempNonce, | |
EncrDecrClass.tempTag, | |
EncrDecrClass.tempKey)); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment