public override byte[] Encrypt(byte[] key, byte[] plainText) { var n = GetNonce(); var nonce = new NSec.Cryptography.Nonce(n, 0); using var encryptionKey = NSec.Cryptography.Key.Import(_secretBox, key, NSec.Cryptography.KeyBlobFormat.RawSymmetricKey); var macAndCipherText = _secretBox.Encrypt(encryptionKey, nonce, plainText); var result = new byte[n.Length + macAndCipherText.Length]; n.CopyTo(result, 0); macAndCipherText.AsSpan().CopyTo(result.AsSpan(n.Length, macAndCipherText.Length)); return(result); }
public override unsafe byte[] Decrypt(byte[] key, byte[] nonceAndMacAndCipherText) { Span <byte> nonceBytes = stackalloc byte[SECRET_BOX_NONCE_BYTES]; nonceAndMacAndCipherText.AsSpan().Slice(0, nonceBytes.Length).CopyTo(nonceBytes); var nonce = new NSec.Cryptography.Nonce(nonceBytes, 0); Span <byte> macAndCipherText = stackalloc byte[nonceAndMacAndCipherText.Length - nonceBytes.Length]; nonceAndMacAndCipherText.AsSpan().Slice(nonceBytes.Length).CopyTo(macAndCipherText); var keySpan = key.AsSpan(); var blobF = NSec.Cryptography.KeyBlobFormat.RawSymmetricKey; using var encryptionKey = NSec.Cryptography.Key.Import(_secretBox, keySpan, blobF); if (_secretBox.Decrypt(encryptionKey, nonce, macAndCipherText, out var plaintext)) { return(plaintext); } throw new CryptographicException("Failed to decrypt data"); }