/// <summary> /// Decrypts the <paramref name="ciphertext"/> into the <paramref name="plaintext"/> provided destination buffer if the authentication <paramref name="tag"/> can be validated. /// </summary> /// <param name="nonce">The nonce associated with this message, which must match the value provided during encryption.</param> /// <param name="ciphertext">The encrypted content to decrypt.</param> /// <param name="tag">The authentication tag produced for this message during encryption.</param> /// <param name="plaintext">The byte span to receive the decrypted contents.</param> /// <param name="associatedData">Extra data associated with this message, which must match the value provided during encryption.</param> /// <exception cref="CryptographicException">The tag value could not be verified, or the decryption operation otherwise failed.</exception> public void Decrypt(ReadOnlySpan <byte> nonce, ReadOnlySpan <byte> ciphertext, ReadOnlySpan <byte> tag, Span <byte> plaintext, ReadOnlySpan <byte> associatedData = default) { if (nonce.IsEmpty || nonce.Length != _snuffle.NonceSizeInBytes) { throw new ArgumentException(Snuffle.FormatNonceLengthExceptionMessage(_snuffle.GetType().Name, nonce.Length, _snuffle.NonceSizeInBytes)); } try { var aadPaddedLen = GetPaddedLength(associatedData, Poly1305.MAC_TAG_SIZE_IN_BYTES); var ciphertextPaddedLen = GetPaddedLength(ciphertext, Poly1305.MAC_TAG_SIZE_IN_BYTES); var macData = new Span <byte>(new byte[aadPaddedLen + ciphertextPaddedLen + Poly1305.MAC_TAG_SIZE_IN_BYTES]); PrepareMacDataRfc8439(macData, associatedData, aadPaddedLen, ciphertext, ciphertextPaddedLen); Poly1305.VerifyMac(GetMacKey(nonce), macData, tag); } catch (CryptographicException ex) when(ex.Message.Contains("length")) { throw; } catch (Exception ex) { throw new CryptographicException(AEAD_EXCEPTION_INVALID_TAG, ex); } _snuffle.Decrypt(ciphertext, nonce, plaintext); }
public const string AEAD_EXCEPTION_INVALID_TAG = "The tag value could not be verified, or the decryption operation otherwise failed."; // "AEAD Bad Tag Exception"; /// <summary> /// Initializes a new instance of the <see cref="SnufflePoly1305"/> class. /// </summary> /// <param name="key">The secret key.</param> public SnufflePoly1305(ReadOnlyMemory <byte> key) { _snuffle = CreateSnuffleInstance(key, 1); _macKeySnuffle = CreateSnuffleInstance(key, 0); }