/// <summary> /// Returns encryption instructions to encrypt content with AES/GCM/NoPadding algorithm /// Creates encryption key used for AES/GCM/NoPadding and encrypt it with AES/GCM /// Encrypted key follows nonce(12 bytes) + key cipher text(16 or 32 bytes) + tag(16 bytes) format /// Tag is appended by the AES/GCM cipher with encryption process /// </summary> /// <param name="materials"></param> /// <returns></returns> private static EncryptionInstructions EncryptEnvelopeKeyUsingSymmetricKeyV2(EncryptionMaterialsV2 materials) { var aes = materials.SymmetricProvider as Aes; if (aes == null) { throw new NotSupportedException("AES is the only supported algorithm with this method."); } switch (materials.SymmetricProviderType) { case SymmetricAlgorithmType.AesGcm: { var aesObject = Aes.Create(); var nonce = aesObject.IV.Take(DefaultNonceSize).ToArray(); var associatedText = Encoding.UTF8.GetBytes(XAmzAesGcmCekAlgValue); var cipher = AesGcmUtils.CreateCipher(true, materials.SymmetricProvider.Key, DefaultTagBitsLength, nonce, associatedText); var envelopeKey = cipher.DoFinal(aesObject.Key); var encryptedEnvelopeKey = nonce.Concat(envelopeKey).ToArray(); var instructions = new EncryptionInstructions(materials.MaterialsDescription, aesObject.Key, encryptedEnvelopeKey, nonce, XAmzWrapAlgAesGcmValue, XAmzAesGcmCekAlgValue); return(instructions); } default: { throw new NotSupportedException($"{materials.SymmetricProviderType} isn't supported with SymmetricProvider"); } } }
private static byte[] DecryptEnvelopeKeyUsingSymmetricKeyV2(SymmetricAlgorithm symmetricAlgorithm, byte[] encryptedEnvelopeKey) { var nonce = encryptedEnvelopeKey.Take(DefaultNonceSize).ToArray(); var encryptedKey = encryptedEnvelopeKey.Skip(nonce.Length).ToArray(); var associatedText = Encoding.UTF8.GetBytes(XAmzAesGcmCekAlgValue); var cipher = AesGcmUtils.CreateCipher(false, symmetricAlgorithm.Key, DefaultTagBitsLength, nonce, associatedText); var envelopeKey = cipher.DoFinal(encryptedKey); return(envelopeKey); }