Skip to content

Instantly share code, notes, and snippets.

@awswithdotnet
Created March 3, 2022 19:15
Show Gist options
  • Save awswithdotnet/e4bdbf0f66008da47bd1644218f92a5e to your computer and use it in GitHub Desktop.
Save awswithdotnet/e4bdbf0f66008da47bd1644218f92a5e to your computer and use it in GitHub Desktop.
kms Crypto AESEncrypter Encrypt
public async Task<IEncryptionPackage> Encrypt(string plainText)
{
byte[] encryptedData;
GenerateDataKeyRequest dataKeyRequest = new GenerateDataKeyRequest()
{
KeyId = _keyId,
KeySpec = DataKeySpec.AES_256
};
GenerateDataKeyResponse dataKeyResponse = await _kmsClient.GenerateDataKeyAsync(dataKeyRequest);
byte[] encryptedDataKey = dataKeyResponse.CiphertextBlob.ToArray();
byte[] plainTextKey = dataKeyResponse.Plaintext.ToArray();
using(Aes aes = Aes.Create()){
ICryptoTransform cryptoTransform = aes.CreateEncryptor(plainTextKey, _iv);
using (MemoryStream memoryStream = new MemoryStream())
{
using (CryptoStream cryptoStream = new CryptoStream(memoryStream, cryptoTransform, CryptoStreamMode.Write))
{
using (StreamWriter streamWriter = new StreamWriter(cryptoStream))
{
await streamWriter.WriteAsync(plainText);
}
encryptedData = memoryStream.ToArray();
}
}
}
string encryptedString = Convert.ToBase64String(encryptedData);
IEncryptionPackage encryptionPackage = new EncryptionPackage{
CipherText = encryptedString,
EncryptedKey = Convert.ToBase64String(encryptedDataKey)
};
return encryptionPackage;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment