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); }
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 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[] EncryptSymmetric(byte[] message, byte[] nonce, byte[] sharedKey) { return(XSalsa20Poly1305.Encrypt(message, sharedKey, 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 void Encrypt() { var ciphertextActual = XSalsa20Poly1305.Encrypt(_plaintext, _key, _nonce); TestHelpers.AssertEqualBytes(_ciphertext, ciphertextActual); }
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); } }