public void EncryptSegments() { var ciphertextActual = new byte[_plaintext.Length + XSalsa20Poly1305.MacSizeInBytes].Pad(); XSalsa20Poly1305.Encrypt(ciphertextActual, _plaintext.Pad(), _key.Pad(), _nonce.Pad()); TestHelpers.AssertEqualBytes(_ciphertext, ciphertextActual.UnPad()); }
PullMsgResult ProduceWelcome(ref Msg msg) { Span <byte> cookieNonce = stackalloc byte[Curve25519XSalsa20Poly1305.NonceLength]; Span <byte> cookiePlaintext = stackalloc byte[64]; Span <byte> cookieCiphertext = stackalloc byte[64 + XSalsa20Poly1305.TagLength]; // Create full nonce for encryption // 8-byte prefix plus 16-byte random nonce CookieNoncePrefix.CopyTo(cookieNonce); using var rng = RandomNumberGenerator.Create(); #if NETSTANDARD2_1 rng.GetBytes(cookieNonce.Slice(8)); #else byte[] temp = new byte[16]; rng.GetBytes(temp); temp.CopyTo(cookieNonce.Slice(8)); #endif // Generate cookie = Box [C' + s'](t) m_cnClientKey.CopyTo(cookiePlaintext); m_cnSecretKey.CopyTo(cookiePlaintext.Slice(32)); // Generate fresh cookie key rng.GetBytes(m_cookieKey); // Encrypt using symmetric cookie key using var secretBox = new XSalsa20Poly1305(m_cookieKey); secretBox.Encrypt(cookieCiphertext, cookiePlaintext, cookieNonce); cookiePlaintext.Clear(); Span <byte> welcomeNonce = stackalloc byte[Curve25519XSalsa20Poly1305.NonceLength]; Span <byte> welcomePlaintext = stackalloc byte[128]; Span <byte> welcomeCiphertext = stackalloc byte[128 + Curve25519XSalsa20Poly1305.TagLength]; // Create full nonce for encryption // 8-byte prefix plus 16-byte random nonce WelcomeNoncePrefix.CopyTo(welcomeNonce); #if NETSTANDARD2_1 rng.GetBytes(welcomeNonce.Slice(8)); #else rng.GetBytes(temp); temp.CopyTo(welcomeNonce.Slice(8)); #endif // Create 144-byte Box [S' + cookie](S->C') m_cnPublicKey.CopyTo(welcomePlaintext); cookieNonce.Slice(8).CopyTo(welcomePlaintext.Slice(32)); cookieCiphertext.CopyTo(welcomePlaintext.Slice(48)); using var box = new Curve25519XSalsa20Poly1305(m_secretKey, m_cnClientKey); box.Encrypt(welcomeCiphertext, welcomePlaintext, welcomeNonce); welcomePlaintext.Clear(); msg.InitPool(168); // TODO: we can save some allocation here by allocating this earlier Span <byte> welcome = msg; WelcomeLiteral.CopyTo(welcome); welcomeNonce.Slice(8, 16).CopyTo(welcome.Slice(8)); welcomeCiphertext.CopyTo(welcome.Slice(24)); return(PullMsgResult.Ok); }
/// <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)); }
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()); }
/// <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)); }
/// <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 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 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 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); }
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); }
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); }
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); }
public static byte[] DecryptSymmetric(byte[] message, byte[] nonce, byte[] sharedKey) { return(XSalsa20Poly1305.TryDecrypt(message, sharedKey, nonce)); }
public byte[] Decrypt(byte[] ciphertext, byte[] key, byte[] nonce) { return(XSalsa20Poly1305.TryDecrypt(ciphertext, key, nonce)); }
public (byte[] ciphertext, byte[] nonce) Encrypt(byte[] plaintext, byte[] key, byte[] nonce = default) { nonce ??= PrivateKey.GetSecureRandomeBytes(XSalsa20Poly1305.NonceSizeInBytes); return(XSalsa20Poly1305.Encrypt(plaintext, key, nonce), nonce); }
public static long EncryptFile(System.IO.FileInfo SourceFile, FileStream DestinationFile, string[] Recipients, Keys SenderKeys) { // crypto variables // THESE SHOULD BE RANDOM! byte[] fileNonce = Utilities.GenerateRandomBytes(16); byte[] fileKey = Utilities.GenerateRandomBytes(32); Keys ephemeral = new Keys(true); // these are dependant on recipients byte[] sharedKey = null; // validate parameters //process chunks Blake2sCSharp.Hasher b2s = Blake2sCSharp.Blake2S.Create(); UTF8Encoding utf8 = new UTF8Encoding(); // use cache file instead of a memory stream to conserve used memory MemoryStream ms = new MemoryStream(); // processed chunks go here string tempFile = null; FileStream cacheFs = GetTempFileStream(out tempFile); FileStream fs = new FileStream(SourceFile.FullName, FileMode.Open, FileAccess.Read); long fileCursor = 0; byte[] chunk = null; UInt64 chunkCount = 0; byte[] chunkNonce = new byte[24]; // always a constant length // this part of the nonce doesn't change Array.Copy(fileNonce, chunkNonce, fileNonce.Length); // copy it once and be done with it do { if (chunkCount == 0) // first chunk is always '\0'-padded filename { chunk = new byte[256]; byte[] filename = utf8.GetBytes(SourceFile.Name); Array.Copy(filename, chunk, filename.Length); filename.Wipe(); // DON'T LEAK!!! } else { if (fileCursor + MAX_CHUNK_SIZE >= SourceFile.Length) { // last chunk chunkNonce[23] |= 0x80; chunk = new byte[SourceFile.Length - fileCursor]; } else { chunk = new byte[MAX_CHUNK_SIZE]; } if (fs.Read(chunk, 0, chunk.Length) != chunk.Length) { // read error! fs.Close(); fs.Dispose(); TrashTempFileStream(cacheFs, tempFile); throw new System.IO.IOException("Abrupt end of file / read error from source."); } fileCursor += chunk.Length; } byte[] outBuffer = XSalsa20Poly1305.Encrypt(chunk, fileKey, chunkNonce); byte[] chunkLengthBytes = Utilities.UInt32ToBytes((uint)chunk.Length); cacheFs.Write(chunkLengthBytes, 0, 4); // use cache file b2s.Update(chunkLengthBytes); // hash as we go cacheFs.Write(outBuffer, 0, outBuffer.Length); // use cache file b2s.Update(outBuffer); // hash as we go // since the first chunkNonce is just the fileNonce and a bunch of 0x00's, // it's safe to do the chunk counter as a post-process update Utilities.UInt64ToBytes(++chunkCount, chunkNonce, 16); } while (fileCursor < SourceFile.Length); cacheFs.Flush(true); // make sure everything is flushed to the disk cache cacheFs.Position = 0; // leave it open so that we can read it back into the destination // get the ciphertext hash for the header byte[] cipherTextHash = b2s.Finish(); // done encrypting to the cache, now to build the header //build header (fileInfo needed first, but same for all recipients)... FileInfo fi = new FileInfo( fileKey.ToBase64String(), fileNonce.ToBase64String(), cipherTextHash.ToBase64String()); byte[] fiBytes = utf8.GetBytes(fi.ToJSON()); // encrypt this to the recipients next... //build inner headers next (one for each recipient) Dictionary <string, string> innerHeaders = new Dictionary <string, string>(Recipients.Length); foreach (string recip in Recipients) { // each recipient is not identified in the outer header, only a random NONCE byte[] recipientNonce = Utilities.GenerateRandomBytes(24); sharedKey = // INNER SHARED KEY (Sender Secret + Recipient Public) SenderKeys.GetShared(recip); InnerHeaderInfo ih = new InnerHeaderInfo( SenderKeys.PublicID, recip, XSalsa20Poly1305.Encrypt(fiBytes, sharedKey, recipientNonce).ToBase64String()); // fileInfo JSON object encrypted, Base64 sharedKey = // OUTER SHARED KEY (Ephemeral Secret + Recipient Public) ephemeral.GetShared(recip); string encryptedInnerHeader = ih.ToJSON(); encryptedInnerHeader = XSalsa20Poly1305.Encrypt(utf8.GetBytes(encryptedInnerHeader), sharedKey, recipientNonce).ToBase64String(); innerHeaders.Add(recipientNonce.ToBase64String(), encryptedInnerHeader); } // finally the outer header, ready for stuffing into the file HeaderInfo hi = new HeaderInfo(1, ephemeral.PublicKey.ToBase64String(), innerHeaders); string fileHeader = hi.ToJSON(); // build the final file... DestinationFile.Write(utf8.GetBytes("miniLock"), 0, 8); // file identifier (aka "magic bytes") DestinationFile.Write(Utilities.UInt32ToBytes((uint)fileHeader.Length), 0, 4); // header length in 4 little endian bytes DestinationFile.Write(utf8.GetBytes(fileHeader), 0, fileHeader.Length); // the full JSON header object // read back from the cache file into the destination file... byte[] buffer; for (int i = 0; i < cacheFs.Length; i += buffer.Length) { if (i + MAX_CHUNK_SIZE >= cacheFs.Length) { buffer = new byte[cacheFs.Length - i]; } else { buffer = new byte[MAX_CHUNK_SIZE]; } if (cacheFs.Read(buffer, 0, buffer.Length) != buffer.Length) { throw new System.IO.IOException("Abrupt end of cache file"); } DestinationFile.Write(buffer, 0, buffer.Length); // the ciphertext } // now flush and close, and grab length for reporting to caller DestinationFile.Flush(); long tempOutputFileLength = DestinationFile.Length; DestinationFile.Close(); DestinationFile.Dispose(); // kill the cache and the directory created for it TrashTempFileStream(cacheFs, tempFile); return(tempOutputFileLength); }
public static void Main() { const int n = 10000; Thread.CurrentThread.CurrentCulture = CultureInfo.InvariantCulture; Console.WriteLine("Architecture: {0} bit", IntPtr.Size * 8); Console.WriteLine("CPU-Frequency: {0} MHz", Cpu.CpuFreq); Cpu.Setup(); Console.WriteLine(); Console.ReadKey(); var m = new byte[100]; var seed = new byte[32]; byte[] privateKey; byte[] publicKey; Ed25519.KeyPairFromSeed(out publicKey, out privateKey, seed); var sig = Ed25519.Sign(m, privateKey); Ed25519.Sign(m, privateKey); if (!Ed25519.Verify(sig, m, publicKey)) { throw new Exception("Bug"); } if (Ed25519.Verify(sig, m.Concat(new byte[] { 1 }).ToArray(), publicKey)) { throw new Exception("Bug"); } Console.BackgroundColor = ConsoleColor.Black; { Console.ForegroundColor = ConsoleColor.Yellow; Console.WriteLine("=== Edwards ==="); Benchmark("KeyGen", () => Ed25519.KeyPairFromSeed(out publicKey, out privateKey, seed), n); Benchmark("Sign", () => Ed25519.Sign(m, privateKey), n); Benchmark("Verify", () => Ed25519.Verify(sig, m, publicKey), n); Benchmark("KeyExchange", () => Ed25519.KeyExchange(publicKey, privateKey), n); Console.WriteLine(); } { Console.ForegroundColor = ConsoleColor.Yellow; Console.WriteLine("=== Montgomery ==="); Benchmark("KeyGen", () => MontgomeryCurve25519.GetPublicKey(seed), n); Benchmark("KeyExchange", () => MontgomeryCurve25519.KeyExchange(publicKey, seed), n); Console.WriteLine(); } foreach (var size in new[] { 1, 128 * 1024 }) { Console.ForegroundColor = ConsoleColor.Yellow; Console.WriteLine("=== Symmetric ({0}) ===", SizeToString(size)); var message = new byte[size]; var ciphertext = new byte[message.Length + 16]; var key = new byte[32]; var nonce = new byte[24]; Benchmark("HSalsa20Core", () => HSalsa20Core(size), n, size); Benchmark("XSalsa20Poly1305 Encrypt", () => XSalsa20Poly1305.Encrypt(new ArraySegment <byte>(ciphertext), new ArraySegment <byte>(message), new ArraySegment <byte>(key), new ArraySegment <byte>(nonce)), n, size); Benchmark("SHA512Managed", () => new SHA512Managed().ComputeHash(message), n, size); Benchmark("SHA512Cng", () => new SHA512Cng().ComputeHash(message), n, size); Benchmark("SHA512CSP", () => new SHA512CryptoServiceProvider().ComputeHash(message), n, size); Benchmark("SHA512Chaos", () => Sha512.Hash(message), n, size); } }
public void DecryptSuccess() { var plaintextActual = XSalsa20Poly1305.TryDecrypt(_ciphertext, _key, _nonce); TestHelpers.AssertEqualBytes(_plaintext, plaintextActual); }
/// <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 DecryptTooShort() { var plaintextActual = XSalsa20Poly1305.TryDecrypt(new byte[15], _key, _nonce); Assert.AreEqual(null, plaintextActual); }
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); }
public void Encrypt() { var ciphertextActual = XSalsa20Poly1305.Encrypt(_plaintext, _key, _nonce); TestHelpers.AssertEqualBytes(_ciphertext, ciphertextActual); }