public void DecryptFail()
 {
     foreach (var brokenCiphertext in _ciphertext.WithChangedBit())
     {
         var plaintextActual = XSalsa20Poly1305.TryDecrypt(brokenCiphertext, _key, _nonce);
         Assert.AreEqual(null, plaintextActual);
     }
 }
        public void DecryptSuccessSegments()
        {
            var plaintextActual = new byte[_ciphertext.Length - XSalsa20Poly1305.MacSizeInBytes].Pad();
            var success         = XSalsa20Poly1305.TryDecrypt(plaintextActual, _ciphertext.Pad(), _key.Pad(), _nonce.Pad());

            Assert.IsTrue(success);
            TestHelpers.AssertEqualBytes(_plaintext, plaintextActual.UnPad());
        }
Example #3
0
 /// <summary>
 /// Attempt to decrypt a byte array using the Shared key between a sender's Public miniLock ID and the Secret key.
 /// </summary>
 /// <param name="SenderPublicKey"></param>
 /// <param name="Payload"></param>
 /// <param name="OriginalNonce"></param>
 /// <returns>Null if authenticated decrypt fails.</returns>
 public byte[] TryDecrypt(string SenderPublicID, bool SenderPublicIDIsBase64Encoded, byte[] Payload, byte[] OriginalNonce)
 {
     if (!Initialized)
     {
         throw new NullReferenceException("Keys object not initilized with an e-mail address and passphrase.");
     }
     return(XSalsa20Poly1305.TryDecrypt(Payload, GetShared(SenderPublicID, SenderPublicIDIsBase64Encoded), OriginalNonce));
 }
Example #4
0
 /// <summary>
 /// Attempt to decrypt a byte array using the Secret key.
 /// </summary>
 /// <param name="Payload"></param>
 /// <param name="OriginalNonce"></param>
 /// <returns>Null if authenticated decrypt fails.</returns>
 public byte[] TryDecrypt(byte[] Payload, byte[] OriginalNonce)
 {
     if (!Initialized)
     {
         throw new NullReferenceException("Keys object not initilized with an e-mail address and passphrase.");
     }
     return(XSalsa20Poly1305.TryDecrypt(Payload, Secret, OriginalNonce));
 }
Example #5
0
 /// <summary>
 /// Attempt to decrypt a byte array using the Shared key between a sender's Public Key byte array and the Secret key.
 /// </summary>
 /// <param name="SenderPublicKey"></param>
 /// <param name="Payload"></param>
 /// <param name="OriginalNonce"></param>
 /// <returns>Null if authenticated decrypt fails.</returns>
 public byte[] TryDecrypt(byte[] SenderPublicKey, byte[] Payload, byte[] OriginalNonce)
 {
     if (!Initialized)
     {
         throw new NullReferenceException("Keys object not initilized with an e-mail address and passphrase.");
     }
     byte[] shared = GetShared(SenderPublicKey);
     return(XSalsa20Poly1305.TryDecrypt(Payload, shared, OriginalNonce));
 }
 public void RoundTripSuccessWithManyLengths()
 {
     for (int length = 0; length < 1000; length++)
     {
         var plaintextExpected = Enumerable.Range(0, length).Select(i => (byte)i).ToArray();
         var ciphertext        = XSalsa20Poly1305.Encrypt(plaintextExpected.ToArray(), _key, _nonce);
         var plaintextActual   = XSalsa20Poly1305.TryDecrypt(ciphertext, _key, _nonce);
         TestHelpers.AssertEqualBytes(plaintextExpected, plaintextActual);
     }
 }
 public void RoundTripFailWithManyLengths()
 {
     for (int length = 0; length < 130; length++)//130 bytes exceeds two blocks
     {
         var originalPlaintext = Enumerable.Range(0, length).Select(i => (byte)i).ToArray();
         var ciphertext        = XSalsa20Poly1305.Encrypt(originalPlaintext.ToArray(), _key, _nonce);
         foreach (var brokenCiphertext in ciphertext.WithChangedBit())
         {
             var plaintextActual = XSalsa20Poly1305.TryDecrypt(brokenCiphertext, _key, _nonce);
             Assert.AreEqual(null, plaintextActual);
         }
     }
 }
 public void RoundTripSuccessWithManyLengthsSegments()
 {
     for (int length = 0; length < 1000; length++)
     {
         var plaintextExpected = Enumerable.Range(0, length).Select(i => (byte)i).ToArray();
         var ciphertext        = new byte[plaintextExpected.Length + XSalsa20Poly1305.MacSizeInBytes].Pad();
         var plaintextActual   = new byte[plaintextExpected.Length].Pad();
         XSalsa20Poly1305.Encrypt(ciphertext, plaintextExpected.ToArray().Pad(), _key.Pad(), _nonce.Pad());
         ciphertext.UnPad();//verify padding
         XSalsa20Poly1305.TryDecrypt(plaintextActual, ciphertext, _key.Pad(), _nonce.Pad());
         TestHelpers.AssertEqualBytes(plaintextExpected, plaintextActual.UnPad());
     }
 }
 public void DecryptFailSegments()
 {
     foreach (var brokenCiphertext in _ciphertext.WithChangedBit())
     {
         var plaintextActual = new byte[_ciphertext.Length - XSalsa20Poly1305.MacSizeInBytes].Pad();
         for (int i = 0; i < plaintextActual.Count; i++)
         {
             plaintextActual.Array[plaintextActual.Offset + i] = 0x37;
         }
         var success = XSalsa20Poly1305.TryDecrypt(plaintextActual, brokenCiphertext.Pad(), _key.Pad(), _nonce.Pad());
         Assert.IsFalse(success);
         TestHelpers.AssertEqualBytes(new byte[_plaintext.Length], plaintextActual.UnPad());
     }
 }
        public string DecryptData(byte[] decryptionKey, EncryptedChannelData encryptedData)
        {
            string decryptedText = null;

            byte[] cipher = null;
            byte[] nonce  = null;
            if (encryptedData != null)
            {
                if (encryptedData.ciphertext != null)
                {
                    cipher = Convert.FromBase64String(encryptedData.ciphertext);
                }

                if (encryptedData.nonce != null)
                {
                    nonce = Convert.FromBase64String(encryptedData.nonce);
                }
            }

            if (cipher != null && nonce != null)
            {
                using (XSalsa20Poly1305 secretBox = new XSalsa20Poly1305(decryptionKey))
                {
                    byte[] decryptedBytes = new byte[cipher.Length - XSalsa20Poly1305.TagLength];
                    if (secretBox.TryDecrypt(decryptedBytes, cipher, nonce))
                    {
                        decryptedText = Encoding.UTF8.GetString(decryptedBytes);
                    }
                    else
                    {
                        throw new ChannelDecryptionException("Decryption failed for channel.");
                    }
                }
            }
            else
            {
                throw new ChannelDecryptionException("Insufficient data received; requires encrypted data with 'ciphertext' and 'nonce'.");
            }

            return(decryptedText);
        }
Example #11
0
        public void TestPerformanceSmallPayload()
        {
            var firstkey = new byte[]
            {
                0x1b, 0x27, 0x55, 0x64, 0x73, 0xe9, 0x85,
                0xd4, 0x62, 0xcd, 0x51, 0x19, 0x7a, 0x9a,
                0x46, 0xc7, 0x60, 0x09, 0x54, 0x9e, 0xac,
                0x64, 0x74, 0xf2, 0x06, 0xc4, 0xee, 0x08,
                0x44, 0xf6, 0x83, 0x89
            };

            var nonce = new byte[]
            {
                0x69, 0x69, 0x6e, 0xe9, 0x55, 0xb6,
                0x2b, 0x73, 0xcd, 0x62, 0xbd, 0xa8,
                0x75, 0xfc, 0x73, 0xd6, 0x82, 0x19,
                0xe0, 0x03, 0x6b, 0x7a, 0x0b, 0x37
            };

            var message = new byte[128];

            message[0] = 1;

            var message2 = new byte[message.Length];

            var cipher = new byte[message.Length + XSalsa20Poly1305.TagLength];

            var xSalsa20Poly1305 = new XSalsa20Poly1305(firstkey);

            var sw      = Stopwatch.StartNew();
            int counter = 0;

            do
            {
                xSalsa20Poly1305.Encrypt(cipher, message, nonce);
                xSalsa20Poly1305.TryDecrypt(message2, cipher, nonce);
                counter++;
            } while (sw.ElapsedMilliseconds < 10000);
            Console.WriteLine("iterations " + counter);
        }
Example #12
0
        public void TestPerformance()
        {
            var firstkey = new byte[]
            {
                0x1b, 0x27, 0x55, 0x64, 0x73, 0xe9, 0x85,
                0xd4, 0x62, 0xcd, 0x51, 0x19, 0x7a, 0x9a,
                0x46, 0xc7, 0x60, 0x09, 0x54, 0x9e, 0xac,
                0x64, 0x74, 0xf2, 0x06, 0xc4, 0xee, 0x08,
                0x44, 0xf6, 0x83, 0x89
            };

            var nonce = new byte[]
            {
                0x69, 0x69, 0x6e, 0xe9, 0x55, 0xb6,
                0x2b, 0x73, 0xcd, 0x62, 0xbd, 0xa8,
                0x75, 0xfc, 0x73, 0xd6, 0x82, 0x19,
                0xe0, 0x03, 0x6b, 0x7a, 0x0b, 0x37
            };

            var message = new byte[1000000];

            message[0] = 1;

            var message2 = new byte[message.Length];

            var cipher = new byte[message.Length + XSalsa20Poly1305.TagLength];

            var xSalsa20Poly1305 = new XSalsa20Poly1305(firstkey);

            var sw = Stopwatch.StartNew();

            for (int i = 0; i < 100; i++)
            {
                xSalsa20Poly1305.Encrypt(cipher, message, nonce);
                xSalsa20Poly1305.TryDecrypt(message2, cipher, nonce);
            }
            Console.WriteLine("Encrypt + Decrypt took " + sw.ElapsedMilliseconds);
            Assert.AreEqual(message, message2);
        }
Example #13
0
        PushMsgResult ProcessInitiate(ref Msg msg)
        {
            if (!CheckBasicCommandStructure(ref msg))
            {
                return(PushMsgResult.Error);
            }

            Span <byte> initiate = msg;

            if (!IsCommand("INITIATE", ref msg))
            {
                return(PushMsgResult.Error);
            }

            if (initiate.Length < 257)
            {
                return(PushMsgResult.Error);
            }

            Span <byte> cookieNonce     = stackalloc byte[Curve25519XSalsa20Poly1305.NonceLength];
            Span <byte> cookiePlaintext = stackalloc byte[64];
            Span <byte> cookieBox       = initiate.Slice(25, 80);

            CookieNoncePrefix.CopyTo(cookieNonce);
            initiate.Slice(9, 16).CopyTo(cookieNonce.Slice(8));

            using var secretBox = new XSalsa20Poly1305(m_cookieKey);
            bool decrypted = secretBox.TryDecrypt(cookiePlaintext, cookieBox, cookieNonce);

            if (!decrypted)
            {
                return(PushMsgResult.Error);
            }

            //  Check cookie plain text is as expected [C' + s']
            if (!SpanUtility.Equals(m_cnClientKey, cookiePlaintext.Slice(0, 32)) ||
                !SpanUtility.Equals(m_cnSecretKey, cookiePlaintext.Slice(32, 32)))
            {
                return(PushMsgResult.Error);
            }

            Span <byte> initiateNonce = stackalloc byte[Curve25519XSalsa20Poly1305.NonceLength];

            byte[] initiatePlaintext = new byte[msg.Size - 113];
            var    initiateBox       = initiate.Slice(113);

            InitiatieNoncePrefix.CopyTo(initiateNonce);
            initiate.Slice(105, 8).CopyTo(initiateNonce.Slice(16));
            m_peerNonce = NetworkOrderBitsConverter.ToUInt64(initiate, 105);

            using var box = new Curve25519XSalsa20Poly1305(m_cnSecretKey, m_cnClientKey);
            bool decrypt = box.TryDecrypt(initiatePlaintext, initiateBox, initiateNonce);

            if (!decrypt)
            {
                return(PushMsgResult.Error);
            }

            Span <byte> vouchNonce     = stackalloc byte[Curve25519XSalsa20Poly1305.NonceLength];
            Span <byte> vouchPlaintext = stackalloc byte[64];
            Span <byte> vouchBox       = new Span <byte>(initiatePlaintext, 48, 80);
            var         clientKey      = new Span <byte>(initiatePlaintext, 0, 32);

            VouchNoncePrefix.CopyTo(vouchNonce);
            new Span <byte>(initiatePlaintext, 32, 16).CopyTo(vouchNonce.Slice(8));

            using var box2 = new Curve25519XSalsa20Poly1305(m_cnSecretKey, clientKey);
            decrypt        = box2.TryDecrypt(vouchPlaintext, vouchBox, vouchNonce);
            if (!decrypt)
            {
                return(PushMsgResult.Error);
            }

            //  What we decrypted must be the client's short-term public key
            if (!SpanUtility.Equals(vouchPlaintext.Slice(0, 32), m_cnClientKey))
            {
                return(PushMsgResult.Error);
            }

            //  Create the session box
            m_box = new Curve25519XSalsa20Poly1305(m_cnSecretKey, m_cnClientKey);

            //  This supports the Stonehouse pattern (encryption without authentication).
            m_state = State.SendingReady;

            if (!ParseMetadata(new Span <byte>(initiatePlaintext, 128, initiatePlaintext.Length - 128 - 16)))
            {
                return(PushMsgResult.Error);
            }

            vouchPlaintext.Clear();
            Array.Clear(initiatePlaintext, 0, initiatePlaintext.Length);

            return(PushMsgResult.Ok);
        }
Example #14
0
        public void Test1()
        {
            var firstkey = new byte[]
            {
                0x1b, 0x27, 0x55, 0x64, 0x73, 0xe9, 0x85,
                0xd4, 0x62, 0xcd, 0x51, 0x19, 0x7a, 0x9a,
                0x46, 0xc7, 0x60, 0x09, 0x54, 0x9e, 0xac,
                0x64, 0x74, 0xf2, 0x06, 0xc4, 0xee, 0x08,
                0x44, 0xf6, 0x83, 0x89
            };

            var nonce = new byte[]
            {
                0x69, 0x69, 0x6e, 0xe9, 0x55, 0xb6,
                0x2b, 0x73, 0xcd, 0x62, 0xbd, 0xa8,
                0x75, 0xfc, 0x73, 0xd6, 0x82, 0x19,
                0xe0, 0x03, 0x6b, 0x7a, 0x0b, 0x37
            };

            var message = new byte[]
            {
                0xbe, 0x07, 0x5f, 0xc5, 0x3c, 0x81, 0xf2, 0xd5, 0xcf, 0x14, 0x13, 0x16,
                0xeb, 0xeb, 0x0c, 0x7b, 0x52, 0x28, 0xc5, 0x2a, 0x4c, 0x62, 0xcb, 0xd4,
                0x4b, 0x66, 0x84, 0x9b, 0x64, 0x24, 0x4f, 0xfc, 0xe5, 0xec, 0xba, 0xaf,
                0x33, 0xbd, 0x75, 0x1a, 0x1a, 0xc7, 0x28, 0xd4, 0x5e, 0x6c, 0x61, 0x29,
                0x6c, 0xdc, 0x3c, 0x01, 0x23, 0x35, 0x61, 0xf4, 0x1d, 0xb6, 0x6c, 0xce,
                0x31, 0x4a, 0xdb, 0x31, 0x0e, 0x3b, 0xe8, 0x25, 0x0c, 0x46, 0xf0, 0x6d,
                0xce, 0xea, 0x3a, 0x7f, 0xa1, 0x34, 0x80, 0x57, 0xe2, 0xf6, 0x55, 0x6a,
                0xd6, 0xb1, 0x31, 0x8a, 0x02, 0x4a, 0x83, 0x8f, 0x21, 0xaf, 0x1f, 0xde,
                0x04, 0x89, 0x77, 0xeb, 0x48, 0xf5, 0x9f, 0xfd, 0x49, 0x24, 0xca, 0x1c,
                0x60, 0x90, 0x2e, 0x52, 0xf0, 0xa0, 0x89, 0xbc, 0x76, 0x89, 0x70, 0x40,
                0xe0, 0x82, 0xf9, 0x37, 0x76, 0x38, 0x48, 0x64, 0x5e, 0x07, 0x05
            };

            var expected = new byte[]
            {
                0xf3, 0xff, 0xc7, 0x70, 0x3f, 0x94, 0x00, 0xe5, 0x2a, 0x7d, 0xfb, 0x4b, 0x3d, 0x33, 0x05, 0xd9, 0x8e,
                0x99, 0x3b, 0x9f, 0x48, 0x68, 0x12, 0x73, 0xc2, 0x96, 0x50, 0xba, 0x32, 0xfc, 0x76, 0xce, 0x48, 0x33,
                0x2e, 0xa7, 0x16, 0x4d, 0x96, 0xa4, 0x47, 0x6f, 0xb8, 0xc5, 0x31, 0xa1, 0x18, 0x6a, 0xc0, 0xdf, 0xc1,
                0x7c, 0x98, 0xdc, 0xe8, 0x7b, 0x4d, 0xa7, 0xf0, 0x11, 0xec, 0x48, 0xc9, 0x72, 0x71, 0xd2, 0xc2, 0x0f,
                0x9b, 0x92, 0x8f, 0xe2, 0x27, 0x0d, 0x6f, 0xb8, 0x63, 0xd5, 0x17, 0x38, 0xb4, 0x8e, 0xee, 0xe3, 0x14,
                0xa7, 0xcc, 0x8a, 0xb9, 0x32, 0x16, 0x45, 0x48, 0xe5, 0x26, 0xae, 0x90, 0x22, 0x43, 0x68, 0x51, 0x7a,
                0xcf, 0xea, 0xbd, 0x6b, 0xb3, 0x73, 0x2b, 0xc0, 0xe9, 0xda, 0x99, 0x83, 0x2b, 0x61, 0xca, 0x01, 0xb6,
                0xde, 0x56, 0x24, 0x4a, 0x9e, 0x88, 0xd5, 0xf9, 0xb3, 0x79, 0x73, 0xf6, 0x22, 0xa4, 0x3d, 0x14, 0xa6,
                0x59, 0x9b, 0x1f, 0x65, 0x4c, 0xb4, 0x5a, 0x74, 0xe3, 0x55, 0xa5
            };

            var cipher = new byte[message.Length + XSalsa20Poly1305.TagLength];

            XSalsa20Poly1305 xSalsa20Poly1305 = new XSalsa20Poly1305(firstkey);

            xSalsa20Poly1305.Encrypt(cipher, message, nonce);

            Assert.AreEqual(expected, cipher);

            var message2 = new byte[message.Length];
            var result   = xSalsa20Poly1305.TryDecrypt(message2, cipher, nonce);

            Assert.AreEqual(message, message2);
            Assert.IsTrue(result);
        }
Example #15
0
 public static byte[] DecryptSymmetric(byte[] message, byte[] nonce, byte[] sharedKey)
 {
     return(XSalsa20Poly1305.TryDecrypt(message, sharedKey, nonce));
 }
Example #16
0
 public byte[] Decrypt(byte[] ciphertext, byte[] key, byte[] nonce)
 {
     return(XSalsa20Poly1305.TryDecrypt(ciphertext, key, nonce));
 }
        /// <summary>
        /// Decrypt a miniLock file using the specified Keys
        /// </summary>
        /// <param name="TheFile"></param>
        /// <param name="RecipientKeys"></param>
        /// <returns>null on any error, or a DecryptedFile object with the raw file contents, a plaintext hash,
        /// the SenderID, and the stored filename</returns>
        public static DecryptedFileDetails DecryptFile(FileStream SourceFile, string DestinationFileFullPath, bool OverWriteDestination, miniLockManaged.Keys RecipientKeys)
        {
            if (SourceFile == null)
            {
                throw new ArgumentNullException("SourceFile");
            }
            if (DestinationFileFullPath == null)
            {
                throw new ArgumentNullException("DestinationFile");
            }
            if (!SourceFile.CanRead)
            {
                throw new InvalidOperationException("Source File not readable!");
            }
            if (System.IO.File.Exists(DestinationFileFullPath) && !OverWriteDestination)
            {
                // be fault tolerant
                System.IO.FileInfo existing    = new System.IO.FileInfo(DestinationFileFullPath);
                string             newFilename = DestinationFileFullPath;
                int counter = 1;
                do
                {
                    newFilename  = DestinationFileFullPath.Replace(existing.Extension, "");
                    newFilename += '(' + counter++.ToString() + ')' + existing.Extension;
                } while (File.Exists(newFilename));
                DestinationFileFullPath = newFilename;
                // this is not fault tolerant
                //throw new InvalidOperationException("Destination File already exists!  Set OverWriteDestination true or choose a different filename.");
            }

            FullHeader fileStuff = new FullHeader();
            HeaderInfo h;

            byte[] buffer = null;

            // after this call, the source file pointer should be positioned to the end of the header
            int hLen = IngestHeader(ref SourceFile, out h);

            if (hLen < 0)
            {
                SourceFile.Close();
                SourceFile.Dispose();
                return(null);
            }
            hLen += 12;                                             // the 8 magic bytes and the 4 header length bytes and the length of the JSON header object
            long theCliff = SourceFile.Length - hLen;               // this is the ADJUSTED point where the file cursor falls off the cliff

            if (!TryDecryptHeader(h, RecipientKeys, out fileStuff)) // ciphertext hash is compared later
            {
                fileStuff.Clear();
                SourceFile.Close();
                SourceFile.Dispose();
                return(null);
            }

            Blake2sCSharp.Hasher b2sPlain  = Blake2sCSharp.Blake2S.Create(); // a nice-to-have for the user
            Blake2sCSharp.Hasher b2sCipher = Blake2sCSharp.Blake2S.Create(); // a check to make sure the ciphertext wasn't altered
            //note:  in theory, if the ciphertext doesn't decrypt at any point, there is likely something wrong with it up to and
            //  including truncation/extension
            //  BUT the hash is included in the header, and should be checked.

            DecryptedFileDetails results = new DecryptedFileDetails();

            results.ActualDecryptedFilePath = DestinationFileFullPath; // if the filename got changed, it happened before this point
            string tempFile = null;                                    // save the filename of the temp file so that the temp directory created with it is also killed

            System.IO.FileStream tempFS = GetTempFileStream(out tempFile);

            int    cursor      = 0;
            UInt64 chunkNumber = 0;

            byte[] chunkNonce = new byte[24];                                        // always a constant length
            Array.Copy(fileStuff.fileNonce, chunkNonce, fileStuff.fileNonce.Length); // copy it once and be done with it
            do
            {
                // how big is this chunk? (32bit number, little endien)
                buffer = new byte[4];
                if (SourceFile.Read(buffer, 0, buffer.Length) != buffer.Length)
                {
                    //read error
                    fileStuff.Clear();
                    SourceFile.Close();
                    SourceFile.Dispose();
                    TrashTempFileStream(tempFS, tempFile);
                    return(null);
                }
                b2sCipher.Update(buffer);  // have to include ALL the bytes, even the chunk-length bytes
                UInt32 chunkLength = Utilities.BytesToUInt32(buffer);
                if (chunkLength > MAX_CHUNK_SIZE)
                {
                    //something went wrong!
                    fileStuff.Clear();
                    SourceFile.Close();
                    SourceFile.Dispose();
                    TrashTempFileStream(tempFS, tempFile);
                    return(null);
                }
                cursor += 4; // move past the chunk length

                //the XSalsa20Poly1305 process, ALWAYS expands the plaintext by MacSizeInBytes
                // (authentication), so read the plaintext chunk length, add those bytes to the
                // value, then read that many bytes out of the ciphertext buffer
                byte[] chunk = new byte[chunkLength + XSalsa20Poly1305.MacSizeInBytes];
                //Array.Copy(buffer, cursor,
                //           chunk, 0,
                //           chunk.Length);
                if (SourceFile.Read(chunk, 0, chunk.Length) != chunk.Length)
                {
                    //read error
                    fileStuff.Clear();
                    SourceFile.Close();
                    SourceFile.Dispose();
                    TrashTempFileStream(tempFS, tempFile);
                    return(null);
                }
                b2sCipher.Update(chunk); // get hash of cipher text to compare to stored File Info Object
                cursor += chunk.Length;  // move the cursor past this chunk
                if (cursor >= theCliff)  // this is the last chunk
                {
                    // set most significant bit of nonce
                    chunkNonce[23] |= 0x80;
                }
                byte[] decryptBytes = XSalsa20Poly1305.TryDecrypt(chunk, fileStuff.fileKey, chunkNonce);
                if (decryptBytes == null)
                {
                    // nonce or key incorrect, or chunk has been altered (truncated?)
                    buffer = null;
                    fileStuff.Clear();
                    SourceFile.Close();
                    SourceFile.Dispose();
                    TrashTempFileStream(tempFS, tempFile);
                    return(null);
                }
                if (chunkNumber == 0) // first chunk is always filename '\0' padded
                {
                    results.StoredFilename = new UTF8Encoding().GetString(decryptBytes).Replace("\0", "").Trim();
                }
                else
                {
                    b2sPlain.Update(decryptBytes);                      // give the user a nice PlainText hash
                    tempFS.Write(decryptBytes, 0, decryptBytes.Length); // start building the output file
                }
                decryptBytes.Wipe();                                    // DON'T LEAK!!!
                // since the first chunkNonce is just the fileNonce and a bunch of 0x00's,
                //  it's safe to do the chunk number update as a post-process operation
                Utilities.UInt64ToBytes(++chunkNumber, chunkNonce, 16);
            } while (cursor < theCliff);
            SourceFile.Close();
            SourceFile.Dispose();
            byte[] ctActualHash = b2sCipher.Finish();
            if (!CryptoBytes.ConstantTimeEquals(ctActualHash, fileStuff.ciphertextHash))
            {
                // ciphertext was altered
                TrashTempFileStream(tempFS, tempFile);
                return(null);
            }
            results.SenderID = Keys.GetPublicIDFromKeyBytes(fileStuff.senderID);
            fileStuff.Clear(); // wipe the sensitive stuff!
            tempFS.Flush();
            tempFS.Close();
            tempFS.Dispose();
            //produce a handy hash for use by the end-user (not part of the spec)
            results.PlainTextBlake2sHash = b2sPlain.Finish().ToBase64String();

            System.IO.File.Move(tempFile, DestinationFileFullPath);
            // WARNING:  only use if the method that created the temp file also created a random subdir!
            Directory.Delete(new System.IO.FileInfo(tempFile).DirectoryName, true); // this is done since we didn't use TrashTempfileStream

            return(results);
        }
        public void DecryptSuccess()
        {
            var plaintextActual = XSalsa20Poly1305.TryDecrypt(_ciphertext, _key, _nonce);

            TestHelpers.AssertEqualBytes(_plaintext, plaintextActual);
        }
        public void DecryptTooShort()
        {
            var plaintextActual = XSalsa20Poly1305.TryDecrypt(new byte[15], _key, _nonce);

            Assert.AreEqual(null, plaintextActual);
        }