/// <summary> /// Create an AES key that is encrypted using a RSA certificate, this is the parsed version for increased efficiancy /// /// To create the parsed cert <see cref="Kalix.ApiCrypto.RSA.RSACertificateParser.ParsePublicCertificate"/> /// </summary> /// <param name="keySize">Required AES key size</param> /// <param name="rsaCert">RSA parsed public certificate used to sign</param> /// <returns>data that can be stored</returns> public static byte[] CreateBlob(AESKeySize keySize, RSAServiceProvider rsaCert) { int intKeySize; switch (keySize) { case AESKeySize.AES128: intKeySize = 128; break; case AESKeySize.AES192: intKeySize = 192; break; case AESKeySize.AES256: intKeySize = 256; break; default: throw new ArgumentOutOfRangeException("keySize", "Unknown key size"); } var aesProvider = new RijndaelManaged(); aesProvider.KeySize = intKeySize; aesProvider.GenerateKey(); // Encrypt using the RSA cert and return return rsaCert.EncryptValue(aesProvider.Key); }
public static async Task<IEncryptor> CreateEncryptor(IOptimisticStore store, StoreLocation keyLocation, RSAServiceProvider rsaCert) { bool isFound; byte[] blob; do { var data = await store.LoadData(keyLocation).ConfigureAwait(false); if (data == null) { // Have to create a new key blob = AESBlob.CreateBlob(DefaultKeySize, rsaCert); var ct = CancellationToken.None; // We use an optimistic write so that it will only create the file IF THE FILE DOES NOT EXIST // This will catch rare cases where two server calls may try to create two keys var result = await store.TryOptimisticWrite(keyLocation, null, null, async (s) => { await s.WriteAsync(blob, 0, blob.Length, ct).ConfigureAwait(false); return blob.Length; }, ct).ConfigureAwait(false); isFound = result.Result; } else { blob = await data.Stream.ReadBytes().ConfigureAwait(false); isFound = true; } } while (!isFound); var encryptor = AESBlob.CreateEncryptor(blob, rsaCert); return new CertProtectedEncryptor(keyLocation.Container, encryptor); }
/// <summary> /// Create an AES encryptor from an encrypted AES key, you can use the encryptor to create. This is the parsed version for increased efficiancy /// /// To create the parsed cert <see cref="Kalix.ApiCrypto.RSA.RSACertificateParser.ParsePrivateCertificate"/> /// </summary> /// <param name="blob">AES data created from the <see cref="CreateBlob(AESKeySize, X509Certificate2)"/> or <see cref="CreateBlob(AESKeySize, RSAServiceProvider)"/> method</param> /// <param name="rsaCert">Parsed RSA certificate to decrypt data, must have a private key</param> /// <returns>Encryptor that can be used to encrypt/decrypt any number of documents</returns> public static AESEncryptor CreateEncryptor(byte[] blob, RSAServiceProvider rsaCert) { var key = rsaCert.DecryptValue(blob); return new AESEncryptor(key); }