Created
March 3, 2022 19:15
-
-
Save awswithdotnet/e4bdbf0f66008da47bd1644218f92a5e to your computer and use it in GitHub Desktop.
kms Crypto AESEncrypter Encrypt
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 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