Last active
January 16, 2025 15:02
-
-
Save swaters86/1f0c58aaadabb599a4951dc3317f8ead 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 static string Encrypt(string plainText, byte[] encryptionKey, byte[] iv) | |
{ | |
using var aes = Aes.Create(); | |
aes.Key = encryptionKey; | |
aes.IV = iv; | |
using var encryptor = aes.CreateEncryptor(aes.Key, aes.IV); | |
using var ms = new MemoryStream(); | |
using var cs = new CryptoStream(ms, encryptor, CryptoStreamMode.Write); | |
using (var sw = new StreamWriter(cs)) | |
{ | |
sw.Write(plainText); | |
} | |
return Convert.ToBase64String(ms.ToArray()); // Store this in the database | |
} | |
public static string Decrypt(string encryptedText, byte[] encryptionKey, byte[] iv) | |
{ | |
using var aes = Aes.Create(); | |
aes.Key = encryptionKey; | |
aes.IV = iv; | |
using var decryptor = aes.CreateDecryptor(aes.Key, aes.IV); | |
using var ms = new MemoryStream(Convert.FromBase64String(encryptedText)); | |
using var cs = new CryptoStream(ms, decryptor, CryptoStreamMode.Read); | |
using var sr = new StreamReader(cs); | |
return sr.ReadToEnd(); // Original API key | |
} | |
string encryptionKeyBase64 = Environment.GetEnvironmentVariable("ENCRYPTION_KEY"); | |
string ivBase64 = Environment.GetEnvironmentVariable("ENCRYPTION_IV"); | |
byte[] encryptionKey = Convert.FromBase64String(encryptionKeyBase64); | |
byte[] iv = Convert.FromBase64String(ivBase64); | |
string apiKey = "your-api-key"; | |
string encryptedApiKey = Encrypt(apiKey, encryptionKey, iv); | |
// Save `encryptedApiKey` in the database | |
// Decrypt the API key | |
string apiKey = Decrypt(encryptedApiKey, encryptionKey, iv); | |
32-bit encryption key example: G+GkZr3D5qWXLOiqYLoI2D8u3PIEZvQ3nzPfBi3sbz4= | |
16-bit iv key example: A9sPH0lE71JKV9LzPqs5NA== | |
--- | |
// Generate a 32-byte encryption key (AES-256) | |
byte[] key = GenerateRandomBytes(32); // For AES-128, use 16 bytes | |
byte[] iv = GenerateRandomBytes(16); // IV must always be 16 bytes | |
string keyBase64 = Convert.ToBase64String(key); | |
string ivBase64 = Convert.ToBase64String(iv); | |
Console.WriteLine($"Encryption Key (Base64): {keyBase64}"); | |
Console.WriteLine($"Initialization Vector (Base64): {ivBase64}"); | |
-- | |
set env variable: | |
setx ENCRYPTION_KEY "F1DdCqG6Bfkt5RuvtsF8pFzH5F+iYm+Ht+CxD7RxT0E=" | |
setx ENCRYPTION_IV "A4Ej9aNVd9EFNhhtQmCmJA==" | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment