Skip to content

Instantly share code, notes, and snippets.

@marcwittke
Created August 4, 2020 20:29
Show Gist options
  • Save marcwittke/d4623342a73aa29a55d7dab7551ef6cb to your computer and use it in GitHub Desktop.
Save marcwittke/d4623342a73aa29a55d7dab7551ef6cb to your computer and use it in GitHub Desktop.
using System;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using JetBrains.Annotations;
namespace TicketShop.Domain.Sales
{
public interface ISymmetricEncryption
{
string Encrypt(string s);
string Decrypt(string s);
}
public class SymmetricEncryption : ISymmetricEncryption
{
[NotNull] private readonly string _passPhrase;
public SymmetricEncryption([NotNull] string passPhrase)
{
_passPhrase = passPhrase ?? throw new ArgumentNullException(nameof(passPhrase));
}
public string Encrypt([NotNull] string s)
{
if (s == null) throw new ArgumentNullException(nameof(s));
return StringCipher.Encrypt(s, _passPhrase);
}
public string Decrypt([NotNull] string s)
{
if (s == null) throw new ArgumentNullException(nameof(s));
return StringCipher.Decrypt(s, _passPhrase);
}
}
public static class StringCipher
{
// This constant is used to determine the key size of the encryption algorithm in bits.
// We divide this by 8 within the code below to get the equivalent number of bytes.
private const int Keysize = 128;
// This constant determines the number of iterations for the password bytes generation function.
private const int DerivationIterations = 1000;
public static string Encrypt(string plainText, string passPhrase)
{
// Salt and IV is randomly generated each time, but is prepended to encrypted cipher text
// so that the same Salt and IV values can be used when decrypting.
var saltStringBytes = Generate128BitsOfRandomEntropy();
var ivStringBytes = Generate128BitsOfRandomEntropy();
var plainTextBytes = Encoding.UTF8.GetBytes(plainText);
using (var password = new Rfc2898DeriveBytes(passPhrase, saltStringBytes, DerivationIterations))
{
var keyBytes = password.GetBytes(Keysize / 8);
using (var cryptoAlgorithm = Aes.Create())
{
Debug.Assert(cryptoAlgorithm != null, nameof(cryptoAlgorithm) + " != null");
cryptoAlgorithm.BlockSize = 128;
cryptoAlgorithm.Mode = CipherMode.CBC;
cryptoAlgorithm.Padding = PaddingMode.PKCS7;
using (ICryptoTransform encryptor = cryptoAlgorithm.CreateEncryptor(keyBytes, ivStringBytes))
{
using (var memoryStream = new MemoryStream())
{
using (var cryptoStream = new CryptoStream(memoryStream, encryptor, CryptoStreamMode.Write))
{
cryptoStream.Write(plainTextBytes, 0, plainTextBytes.Length);
cryptoStream.FlushFinalBlock();
// Create the final bytes as a concatenation of the random salt bytes, the random iv bytes and the cipher bytes.
var cipherTextBytes = saltStringBytes;
cipherTextBytes = cipherTextBytes.Concat(ivStringBytes).ToArray();
cipherTextBytes = cipherTextBytes.Concat(memoryStream.ToArray()).ToArray();
return Convert.ToBase64String(cipherTextBytes);
}
}
}
}
}
}
public static string Decrypt(string cipherText, string passPhrase)
{
// Get the complete stream of bytes that represent:
// [32 bytes of Salt] + [32 bytes of IV] + [n bytes of CipherText]
var cipherTextBytesWithSaltAndIv = Convert.FromBase64String(cipherText);
// Get the salt bytes by extracting the first 32 bytes from the supplied cipherText bytes.
var saltStringBytes = cipherTextBytesWithSaltAndIv.Take(Keysize / 8).ToArray();
// Get the IV bytes by extracting the next 32 bytes from the supplied cipherText bytes.
var ivStringBytes = cipherTextBytesWithSaltAndIv.Skip(Keysize / 8).Take(Keysize / 8).ToArray();
// Get the actual cipher text bytes by removing the first 64 bytes from the cipherText string.
var cipherTextBytes = cipherTextBytesWithSaltAndIv.Skip((Keysize / 8) * 2).Take(cipherTextBytesWithSaltAndIv.Length - ((Keysize / 8) * 2)).ToArray();
using (var password = new Rfc2898DeriveBytes(passPhrase, saltStringBytes, DerivationIterations))
{
var keyBytes = password.GetBytes(Keysize / 8);
using (var cryptoAlgorithm = Aes.Create())
{
Debug.Assert(cryptoAlgorithm != null, nameof(cryptoAlgorithm) + " != null");
cryptoAlgorithm.BlockSize = 128;
cryptoAlgorithm.Mode = CipherMode.CBC;
cryptoAlgorithm.Padding = PaddingMode.PKCS7;
using (ICryptoTransform decryptor = cryptoAlgorithm.CreateDecryptor(keyBytes, ivStringBytes))
{
using (var memoryStream = new MemoryStream(cipherTextBytes))
{
using (var cryptoStream = new CryptoStream(memoryStream, decryptor, CryptoStreamMode.Read))
{
var plainTextBytes = new byte[cipherTextBytes.Length];
var decryptedByteCount = cryptoStream.Read(plainTextBytes, 0, plainTextBytes.Length);
return Encoding.UTF8.GetString(plainTextBytes, 0, decryptedByteCount);
}
}
}
}
}
}
private static byte[] Generate128BitsOfRandomEntropy()
{
var randomBytes = new byte[16]; // 16 Bytes will give us 128 bits.
using (var rngCsp = RandomNumberGenerator.Create())
{
// Fill the array with cryptographically secure random bytes.
rngCsp.GetBytes(randomBytes);
}
return randomBytes;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment