Example #1
0
        public static int CryptoStreamXor(byte[] C, byte[] M, long Mlen, byte[] N, byte[] K)
        {
            byte[] subkey = new byte[32];

            Hsalsa20.CryptoCore(subkey, N, K, Xsalsa20.sigma);
            return(Salsa20.CryptoStreamXor(C, M, (int)Mlen, N, 16, subkey));
        }
Example #2
0
        public void EncryptDecrypt()
        {
            // generate data to encrypt
            byte[] input;
            using (MemoryStream stream = new MemoryStream())
                using (BinaryWriter writer = new BinaryWriter(stream))
                {
                    for (short value = -1024; value <= 1023; value++)
                    {
                        writer.Write(value);
                    }
                    writer.Flush();

                    input = stream.ToArray();
                }

            using (SymmetricAlgorithm salsa20 = new Salsa20())
            {
                byte[] encrypted = new byte[input.Length];
                using (ICryptoTransform encrypt = salsa20.CreateEncryptor())
                    encrypt.TransformBlock(input, 0, input.Length, encrypted, 0);

                byte[] decrypted = new byte[input.Length];
                using (ICryptoTransform decrypt = salsa20.CreateDecryptor())
                    decrypt.TransformBlock(encrypted, 0, encrypted.Length, decrypted, 0);

                CollectionAssert.AreEqual(input, decrypted);
            }
        }
Example #3
0
        public static int CryptoStream(byte[] C, int Clen, byte[] N, byte[] K)
        {
            byte[] subkey = new byte[32];

            Hsalsa20.CryptoCore(subkey, N, K, Xsalsa20.sigma);
            return(Salsa20.CryptoStream(C, Clen, N, 16, subkey));
        }
Example #4
0
        /// <summary>
        /// Get a SharedSecret Key for this pair (my Private Key - your Public Key)
        /// </summary>
        /// <param name="peerPublicKey"></param>
        /// <param name="privateKey"></param>
        /// <returns></returns>
        /// <exception cref="ArgumentNullException"></exception>
        /// <exception cref="ArgumentException"></exception>
        public static byte[] GetSharedSecretKey(byte[] peerPublicKey, byte[] privateKey)
        {
            if (peerPublicKey == null)
            {
                throw new ArgumentNullException(nameof(peerPublicKey));
            }
            if (peerPublicKey.Length != PublicKeySizeInBytes)
            {
                throw new ArgumentException($"{nameof(peerPublicKey)} must be {PublicKeySizeInBytes}");
            }

            if (privateKey == null)
            {
                throw new ArgumentNullException(nameof(privateKey));
            }
            if (privateKey.Length != PrivateKeySizeInBytes)
            {
                throw new ArgumentException($"{nameof(privateKey)} must be {PrivateKeySizeInBytes}");
            }

            //Resolve SharedSecret Key using the Montgomery Elliptical Curve Operations...
            var sharedSecretKey = MontgomeryOperations.ScalarMultiplication(
                n: privateKey,
                p: peerPublicKey,
                qSize: SharedKeySizeInBytes);

            //hashes like the NaCl paper says instead i.e. HSalsa(x,0)
            sharedSecretKey = Salsa20.HSalsa20(key: sharedSecretKey);

            return(sharedSecretKey);
        }
Example #5
0
        static void Main(string[] args)
        {
            Console.WriteLine("Hashing devices found ::");
            foreach (var AcceleratorDevice in AcceleratorDevice.All)
            {
                Console.WriteLine($"  {AcceleratorDevice}");
            }

            Console.WriteLine("");

            if (args == null || args.Length == 0)
            {
                throw new ArgumentException("No arguments supplied");
            }

            IHash hash;

            switch (args[0].ToLowerInvariant())
            {
            case "salsa":
                hash = new Salsa20();
                break;

            case "jenkins":
                hash = new Jenkins96();
                break;

            case "benchmark":
                BenchmarkJenkins(args);
                return;

            case "wordlist":
                hash = new Wordlist();
                break;

            case "variation":
                hash = new VarientGen();
                break;

            case "mix":
                hash = new MixMatch();
                break;

            case "markov":
                hash = new MarkovChain();
                break;

            default:
                throw new ArgumentException("Invalid hash type");
            }

            // override console exit event
            CleanExitHandler.Attach();

            hash.LoadParameters(args);
            hash.Start();

            Console.ReadLine();
        }
Example #6
0
 private static void TestColumnRound(uint[] input, uint[] output)
 {
     uint[] result = Salsa20.ColumnRound(input);
     for (int i = 0; i < 16; i++)
     {
         Assert.AreEqual(output[i], result[i]);
     }
 }
Example #7
0
 private static void TestQuarterRound(uint[] input, uint[] output)
 {
     uint[] result = Salsa20.QuarterRound(input);
     for (int i = 0; i < 4; i++)
     {
         Assert.AreEqual(output[i], result[i]);
     }
 }
Example #8
0
        public static int CryptoStreamXor(byte[] C, byte[] M, int Mlen, byte[] N, int Noffset, byte[] K)
        {
            byte[] inv   = new byte[16];
            byte[] block = new byte[64];

            int coffset = 0;
            int moffset = 0;

            if (Mlen == 0)
            {
                return(0);
            }

            for (int i = 0; i < 8; ++i)
            {
                inv[i] = N[Noffset + i];
            }

            for (int i = 8; i < 16; ++i)
            {
                inv[i] = 0;
            }

            while (Mlen >= 64)
            {
                Salsa20.CryptoCore(block, inv, K, Xsalsa20.sigma);

                for (int i = 0; i < 64; ++i)
                {
                    C[coffset + i] = (byte)(M[moffset + i] ^ block[i]);
                }

                int u = 1;

                for (int i = 8; i < 16; ++i)
                {
                    u     += inv[i] & 0xff;
                    inv[i] = (byte)u;
                    u      = (int)((uint)u >> 8);
                }

                Mlen    -= 64;
                coffset += 64;
                moffset += 64;
            }

            if (Mlen != 0)
            {
                Salsa20.CryptoCore(block, inv, K, Xsalsa20.sigma);

                for (int i = 0; i < Mlen; ++i)
                {
                    C[coffset + i] = (byte)(M[moffset + i] ^ block[i]);
                }
            }

            return(0);
        }
Example #9
0
        private void ParallelTest()
        {
            CSPPrng rng = new CSPPrng();

            byte[] key  = rng.GetBytes(32);
            byte[] iv   = rng.GetBytes(8);
            byte[] data = rng.GetBytes(2048);
            byte[] enc  = new byte[2048];
            byte[] dec  = new byte[2048];
            byte[] enc2 = new byte[2048];
            byte[] dec2 = new byte[2048];
            rng.Dispose();

            using (Salsa20 salsa = new Salsa20(10))
            {
                // encrypt linear
                salsa.Initialize(new KeyParams(key, iv));
                salsa.IsParallel = false;
                salsa.Transform(data, enc);

                // encrypt parallel
                salsa.Initialize(new KeyParams(key, iv));
                salsa.IsParallel        = true;
                salsa.ParallelBlockSize = 2048;
                salsa.Transform(data, enc2);

                if (!Evaluate.AreEqual(enc, enc2))
                {
                    throw new Exception("Salsa20: Encrypted arrays are not equal!");
                }

                // decrypt linear
                salsa.Initialize(new KeyParams(key, iv));
                salsa.IsParallel = false;
                salsa.Transform(enc, dec);

                // decrypt parallel
                salsa.Initialize(new KeyParams(key, iv));
                salsa.IsParallel        = true;
                salsa.ParallelBlockSize = 2048;
                salsa.Transform(enc2, dec2);

                if (!Evaluate.AreEqual(dec, dec2))
                {
                    throw new Exception("Salsa20: Decrypted arrays are not equal!");
                }
                if (!Evaluate.AreEqual(dec, data))
                {
                    throw new Exception("Salsa20: Decrypted arrays are not equal!");
                }
                if (!Evaluate.AreEqual(dec2, data))
                {
                    throw new Exception("Salsa20: Decrypted arrays are not equal!");
                }
            }
        }
Example #10
0
 public void CreateDecryptorInvalid()
 {
     using (SymmetricAlgorithm salsa20 = new Salsa20())
     {
         Assert.Throws <ArgumentNullException>(() => salsa20.CreateDecryptor(null, new byte[8]));
         Assert.Throws <ArgumentNullException>(() => salsa20.CreateDecryptor(new byte[16], null));
         Assert.Throws <CryptographicException>(() => salsa20.CreateDecryptor(new byte[15], new byte[8]));
         Assert.Throws <CryptographicException>(() => salsa20.CreateDecryptor(new byte[16], new byte[7]));
     }
 }
 public void CreateEncryptorInvalid()
 {
     using (SymmetricAlgorithm salsa20 = new Salsa20())
     {
         Assert.Throws<ArgumentNullException>(() => salsa20.CreateEncryptor(null, new byte[8]));
         Assert.Throws<ArgumentNullException>(() => salsa20.CreateEncryptor(new byte[16], null));
         Assert.Throws<CryptographicException>(() => salsa20.CreateEncryptor(new byte[15], new byte[8]));
         Assert.Throws<CryptographicException>(() => salsa20.CreateEncryptor(new byte[16], new byte[7]));
     }
 }
Example #12
0
        public static byte[] DecryptSalsa20(byte[] input, string key)
        {
            byte[] initKey = SHA256.Create().ComputeHash(Encoding.UTF8.GetBytes(key));
            byte[] initVec = SHA256.Create().ComputeHash(Encoding.UTF8.GetBytes(key).Reverse().ToArray());
            initKey = initKey.Crop(32);
            initVec = initVec.Crop(8);
            var enc = new Salsa20().CreateDecryptor(initKey, initVec);

            byte[] output = enc.TransformFinalBlock(input, 0, input.Length);
            return(output);
        }
Example #13
0
        public void IV()
        {
            using (SymmetricAlgorithm salsa20 = new Salsa20())
            {
                Assert.Throws <ArgumentNullException>(() => salsa20.IV  = null);
                Assert.Throws <CryptographicException>(() => salsa20.IV = new byte[9]);

                byte[] iv = new byte[] { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07 };
                salsa20.IV = iv;
                CollectionAssert.AreEqual(iv, salsa20.IV);
            }
        }
Example #14
0
        public void CryptoTransform()
        {
            using (SymmetricAlgorithm salsa20 = new Salsa20())
                using (ICryptoTransform transform = salsa20.CreateEncryptor(new byte[16], new byte[8]))
                {
                    Assert.AreEqual(salsa20.BlockSize / 8, transform.InputBlockSize);
                    Assert.AreEqual(salsa20.BlockSize / 8, transform.OutputBlockSize);

                    Assert.IsFalse(transform.CanReuseTransform);
                    Assert.IsTrue(transform.CanTransformMultipleBlocks);
                }
        }
 public void GenerateRandom()
 {
     byte[] rng = new byte[Program.RNG_COUNT * Program.INT_SIZE];
     using (SymmetricAlgorithm salsa20 = new Salsa20())
         using (ICryptoTransform encrypt = salsa20.CreateEncryptor(Guid.NewGuid().ToByteArray(),
                                                                   Guid.NewGuid().ToByteArray().Take(8).ToArray()))
             using (MemoryStream streamInput = new MemoryStream(rng, false))
                 using (CryptoStream streamEncrypted = new CryptoStream(streamInput, encrypt, CryptoStreamMode.Read))
                 {
                     streamEncrypted.ReadAsync(rng).GetAwaiter().GetResult();
                 }
 }
        private byte[] DoSalsa20(byte[] iv, byte[] key, byte[] data)
        {
            Salsa20 s = new Salsa20();

            ICryptoTransform enc = s.CreateEncryptor(key, iv);

            byte[] result = new byte[32];

            enc.TransformBlock(data, 0, data.Length, result, 0);

            return(result);
        }
        public void CryptoTransform()
        {
            using (SymmetricAlgorithm salsa20 = new Salsa20())
            using (ICryptoTransform transform = salsa20.CreateEncryptor(new byte[16], new byte[8]))
            {
                Assert.AreEqual(salsa20.BlockSize / 8, transform.InputBlockSize);
                Assert.AreEqual(salsa20.BlockSize / 8, transform.OutputBlockSize);

                Assert.IsFalse(transform.CanReuseTransform);
                Assert.IsTrue(transform.CanTransformMultipleBlocks);
            }
        }
Example #18
0
        public static void Crypt(CryptVerbs options)
        {
            if (!File.Exists(options.InputPath))
            {
                Console.WriteLine("[X] File to encrypt does not exist.");
                return;
            }

            byte[] input = File.ReadAllBytes(options.InputPath);
            if (!string.IsNullOrEmpty(options.Salsa20KeyEncrypt))
            {
                byte[] keyBytes = MiscUtils.StringToByteArray(options.Salsa20KeyEncrypt);
                using SymmetricAlgorithm salsa20 = new Salsa20();
                byte[] dataKey = new byte[8];

                Console.WriteLine("[:] Encrypting..");
                using var decrypt = salsa20.CreateDecryptor(keyBytes, dataKey);
                decrypt.TransformBlock(input, 0, input.Length, input, 0);
            }
            else if (!string.IsNullOrEmpty(options.Salsa20KeyDecrypt))
            {
                byte[] keyBytes = MiscUtils.StringToByteArray(options.Salsa20KeyDecrypt);
                using SymmetricAlgorithm salsa20 = new Salsa20();
                byte[] dataKey = new byte[8];

                Console.WriteLine("[:] Decrypting..");
                using var encrypt = salsa20.CreateEncryptor(keyBytes, dataKey);
                encrypt.TransformBlock(input, 0, input.Length, input, 0);
            }
            else
            {
                Keyset[] keysets = CheckKeys();
                if (keysets is null)
                {
                    return;
                }

                Keyset keys = keysets.Where(e => e.GameCode.Equals(options.GameCode, StringComparison.OrdinalIgnoreCase)).FirstOrDefault();
                if (keys is null)
                {
                    Console.WriteLine($"Keyset with GameCode '{options.GameCode}' does not exist in the keyset file.");
                    return;
                }

                Console.WriteLine("[!] Crypting..");
                keys.CryptData(input, 0);
            }

            Console.WriteLine($"[:] Saving file as {options.OutputPath}..");
            File.WriteAllBytes(options.OutputPath, input);
            Console.WriteLine("[/] Done.");
        }
Example #19
0
        static byte[] Decrypt(byte[] encrypted, string key)
        {
            using (SymmetricAlgorithm salsa20 = new Salsa20())
            {
                var    dataKey   = new byte[8];
                var    keyBytes  = Encoding.UTF8.GetBytes(key);
                byte[] decrypted = new byte[encrypted.Length];
                using (var decrypt = salsa20.CreateDecryptor(keyBytes, dataKey))
                    decrypt.TransformBlock(encrypted, 0, encrypted.Length, decrypted, 0);

                return(decrypted);
            }
        }
Example #20
0
        static byte[] Encrypt(byte[] input, string key)
        {
            using (SymmetricAlgorithm salsa20 = new Salsa20())
            {
                var dataKey  = new byte[8];
                var keyBytes = Encoding.UTF8.GetBytes(key);

                byte[] encrypted = new byte[input.Length];
                using (var encrypt = salsa20.CreateEncryptor(keyBytes, dataKey))
                    encrypt.TransformBlock(input, 0, input.Length, encrypted, 0);

                return(encrypted);
            }
        }
Example #21
0
        public void Rounds()
        {
            using (Salsa20 salsa20 = new Salsa20())
            {
                Assert.AreEqual(20, salsa20.Rounds);

                salsa20.Rounds = 12;
                Assert.AreEqual(12, salsa20.Rounds);

                salsa20.Rounds = 8;
                Assert.AreEqual(8, salsa20.Rounds);

                Assert.Throws <ArgumentOutOfRangeException>(() => salsa20.Rounds = 16);
            }
        }
        public void Dispose()
        {
            using (SymmetricAlgorithm salsa20 = new Salsa20())
            using (ICryptoTransform transform = salsa20.CreateEncryptor(new byte[16], new byte[8]))
            {
                transform.Dispose();
                transform.Dispose();

                Assert.Throws<ObjectDisposedException>(() => transform.TransformBlock(new byte[1], 0, 1, new byte[1], 0));
                Assert.Throws<ObjectDisposedException>(() => transform.TransformFinalBlock(new byte[1], 0, 1));

                ((IDisposable)salsa20).Dispose();
                ((IDisposable)salsa20).Dispose();
            }
        }
Example #23
0
        public void Salsa20Test()
        {
            var inputStr  = @"
				7e879a21 4f3ec986 7ca940e6 41718f26 baee555b 8c61c1b5 0df84611 6dcd3b1d
				ee24f319 df9b3d85 14121e4b 5ac5aa32 76021d29 09c74829 edebc68d b8b8c25e"                .Clean();
            var outputStr = @"
				a41f859c 6608cc99 3b81cacb 020cef05	044b2181 a2fd337d fd7b1c63 96682f29
				b4393168 e3c9e6bc fe6bc5b7 a06d96ba	e424cc10 2c91745c 24ad673d c7618f81"                    .Clean();

            var input = Encoders.Hex.GetBytes(inputStr);

            Salsa20.Compute(input);

            CollectionAssert.AreEqual(input, Encoders.Hex.GetBytes(outputStr));
        }
Example #24
0
        public void Dispose()
        {
            using (SymmetricAlgorithm salsa20 = new Salsa20())
                using (ICryptoTransform transform = salsa20.CreateEncryptor(new byte[16], new byte[8]))
                {
                    transform.Dispose();
                    transform.Dispose();

                    Assert.Throws <ObjectDisposedException>(() => transform.TransformBlock(new byte[1], 0, 1, new byte[1], 0));
                    Assert.Throws <ObjectDisposedException>(() => transform.TransformFinalBlock(new byte[1], 0, 1));

                    ((IDisposable)salsa20).Dispose();
                    ((IDisposable)salsa20).Dispose();
                }
        }
Example #25
0
        public void BlockSize()
        {
            using (SymmetricAlgorithm salsa20 = new Salsa20())
            {
                Assert.AreEqual(512, salsa20.BlockSize);

                KeySizes[] sizes = salsa20.LegalBlockSizes;
                Assert.AreEqual(1, sizes.Length);
                Assert.AreEqual(512, sizes[0].MinSize);
                Assert.AreEqual(512, sizes[0].MaxSize);
                Assert.AreEqual(0, sizes[0].SkipSize);

                Assert.Throws <CryptographicException>(() => salsa20.BlockSize = 128);
            }
        }
        public void BlockSize()
        {
            using (SymmetricAlgorithm salsa20 = new Salsa20())
            {
                Assert.AreEqual(512, salsa20.BlockSize);

                KeySizes[] sizes = salsa20.LegalBlockSizes;
                Assert.AreEqual(1, sizes.Length);
                Assert.AreEqual(512, sizes[0].MinSize);
                Assert.AreEqual(512, sizes[0].MaxSize);
                Assert.AreEqual(0, sizes[0].SkipSize);

                Assert.Throws<CryptographicException>(() => salsa20.BlockSize = 128);
            }
        }
Example #27
0
        public void TransformFinalBlock()
        {
            using (SymmetricAlgorithm salsa20 = new Salsa20())
                using (ICryptoTransform transform = salsa20.CreateEncryptor(new byte[16], new byte[8]))
                {
                    byte[] aby0 = new byte[0];
                    byte[] aby1 = new byte[1];

                    Assert.Throws <ArgumentNullException>(() => transform.TransformFinalBlock(null, 0, 0));
                    Assert.Throws <ArgumentOutOfRangeException>(() => transform.TransformFinalBlock(aby0, -1, 0));
                    Assert.Throws <ArgumentOutOfRangeException>(() => transform.TransformFinalBlock(aby0, 1, 0));
                    Assert.Throws <ArgumentOutOfRangeException>(() => transform.TransformFinalBlock(aby1, 0, -1));
                    Assert.Throws <ArgumentOutOfRangeException>(() => transform.TransformFinalBlock(aby1, 0, 2));
                    Assert.Throws <ArgumentOutOfRangeException>(() => transform.TransformFinalBlock(aby1, 1, 1));
                }
        }
Example #28
0
        private byte[] SalsaA(byte[] Key, byte[] Vector, byte[] Data)
        {
            int len = Data.Length;
            int ct = 0;
            byte[] output = new byte[len];

            using (Salsa20 salsa = new Salsa20())
            {
                salsa.Init(Key, Vector);

                while (ct < len)
                {
                    salsa.Transform(Data, ct, 64, output, ct);
                    ct += 64;
                }
            }

            return output;
        }
Example #29
0
        public static byte[] DecryptFile(string name, byte[] data, string decryptionKeyName)
        {
            byte[] key = new byte[16];

            using (BinaryReader reader = new BinaryReader(new FileStream(decryptionKeyName + ".ak", FileMode.Open)))
            {
                key = reader.ReadBytes(16);
            }

            byte[] IV = name.ToByteArray();

            Array.Copy(IV, 8, IV, 0, 8);
            Array.Resize(ref IV, 8);

            using (var salsa = new Salsa20())
            {
                var decryptor = salsa.CreateDecryptor(key, IV);
                return(decryptor.TransformFinalBlock(data, 0, data.Length));
            }
        }
Example #30
0
        private byte[] SalsaA(byte[] Key, byte[] Vector, byte[] Data)
        {
            int len = Data.Length;
            int ct  = 0;

            byte[] output = new byte[len];

            using (Salsa20 salsa = new Salsa20())
            {
                salsa.Init(Key, Vector);

                while (ct < len)
                {
                    salsa.Transform(Data, ct, 64, output, ct);
                    ct += 64;
                }
            }

            return(output);
        }
Example #31
0
        public void EcryptTestVector131072(string strComment, int rounds, string key, string iv, string strOutput0_63, string strOutput65472_65535, string strOutput65536_65599, string strOutput131008_131071)
        {
            byte[] output;

            // use the Salsa20 transform directly
            using (SymmetricAlgorithm salsa20 = new Salsa20()
            {
                Rounds = rounds
            })
                using (ICryptoTransform encrypt = salsa20.CreateEncryptor(ToBytes(key), ToBytes(iv)))
                {
                    // input is all zeroes
                    byte[] input = new byte[131072];
                    output = encrypt.TransformFinalBlock(input, 0, input.Length);
                }

            CollectionAssert.AreEqual(ToBytes(strOutput0_63), output.Skip(0).Take(64).ToList());
            CollectionAssert.AreEqual(ToBytes(strOutput65472_65535), output.Skip(65472).Take(64).ToList());
            CollectionAssert.AreEqual(ToBytes(strOutput65536_65599), output.Skip(65536).Take(64).ToList());
            CollectionAssert.AreEqual(ToBytes(strOutput131008_131071), output.Skip(131008).Take(64).ToList());
        }
Example #32
0
        static void Main(string[] args)
        {
            Console.WriteLine("Hashing devices found ::");
            foreach (var AcceleratorDevice in AcceleratorDevice.All)
            {
                Console.WriteLine($"  {AcceleratorDevice}");
            }

            Console.WriteLine("");

            if (args == null || args.Length == 0)
            {
                throw new ArgumentException("No arguments supplied");
            }

            IHash hash;

            switch (args[0].ToLowerInvariant())
            {
            case "salsa":
                hash = new Salsa20();
                break;

            case "jenkins":
                hash = new Jenkins96();
                break;

            case "benchmark":
                BenchmarkJenkins(args);
                return;

            default:
                throw new ArgumentException("Invalid hash type");
            }

            hash.LoadParameters(args);
            hash.Start();
        }
Example #33
0
        public void EcryptTestVector512(string strComment, int rounds, string key, string iv, string strOutput0_63, string strOutput192_255, string strOutput256_319, string strOutput448_511)
        {
            const int c_nSize = 512;

            byte[] output = new byte[c_nSize];

            // encrypt by using CryptoStream
            using (SymmetricAlgorithm salsa20 = new Salsa20()
            {
                Rounds = rounds
            })
                using (ICryptoTransform encrypt = salsa20.CreateEncryptor(ToBytes(key), ToBytes(iv)))
                    using (MemoryStream streamInput = new MemoryStream(new byte[c_nSize], false))
                        using (CryptoStream streamEncrypted = new CryptoStream(streamInput, encrypt, CryptoStreamMode.Read))
                        {
                            streamEncrypted.Read(output, 0, output.Length);
                        }

            CollectionAssert.AreEqual(ToBytes(strOutput0_63), output.Skip(0).Take(64).ToList());
            CollectionAssert.AreEqual(ToBytes(strOutput192_255), output.Skip(192).Take(64).ToList());
            CollectionAssert.AreEqual(ToBytes(strOutput256_319), output.Skip(256).Take(64).ToList());
            CollectionAssert.AreEqual(ToBytes(strOutput448_511), output.Skip(448).Take(64).ToList());
        }
Example #34
0
        private void VectorTest(int Rounds, byte[] Key, byte[] Vector, byte[] Input, byte[] Output)
        {
            byte[] outBytes = new byte[Input.Length];

            using (Salsa20 salsa = new Salsa20(Rounds))
            {
                salsa.Initialize(new KeyParams(Key, Vector));
                salsa.Transform(Input, 0, outBytes, 0, Input.Length);

                if (Evaluate.AreEqual(outBytes, Output) == false)
                {
                    throw new Exception("Salsa20: Encrypted arrays are not equal! Expected: " + HexConverter.ToString(Output) + " Received: " + HexConverter.ToString(outBytes));
                }

                salsa.Initialize(new KeyParams(Key, Vector));
                salsa.Transform(Output, 0, outBytes, 0, Output.Length);

                if (Evaluate.AreEqual(outBytes, Input) == false)
                {
                    throw new Exception("Salsa20: Decrypted arrays are not equal! Expected: " + HexConverter.ToString(Input) + " Received: " + HexConverter.ToString(outBytes));
                }
            }
        }
Example #35
0
        public void Key()
        {
            using (SymmetricAlgorithm salsa20 = new Salsa20())
            {
                KeySizes[] sizes = salsa20.LegalKeySizes;
                Assert.AreEqual(1, sizes.Length);
                Assert.AreEqual(128, sizes[0].MinSize);
                Assert.AreEqual(256, sizes[0].MaxSize);
                Assert.AreEqual(128, sizes[0].SkipSize);

                Assert.Throws <ArgumentNullException>(() => salsa20.Key  = null);
                Assert.Throws <CryptographicException>(() => salsa20.Key = new byte[8]);

                byte[] key16 = new byte[] { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f };
                salsa20.Key = key16;
                CollectionAssert.AreEqual(key16, salsa20.Key);

                byte[] key32 = new byte[] { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
                                            0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f };
                salsa20.Key = key32;
                CollectionAssert.AreEqual(key32, salsa20.Key);
            }
        }
        public void EncryptDecrypt()
        {
            // generate data to encrypt
            byte[] input;
            using (MemoryStream stream = new MemoryStream())
            using (BinaryWriter writer = new BinaryWriter(stream))
            {
                for (short value = -1024; value <= 1023; value++)
                    writer.Write(value);
                writer.Flush();

                input = stream.ToArray();
            }

            using (SymmetricAlgorithm salsa20 = new Salsa20())
            {
                byte[] encrypted = new byte[input.Length];
                using (ICryptoTransform encrypt = salsa20.CreateEncryptor())
                    encrypt.TransformBlock(input, 0, input.Length, encrypted, 0);

                byte[] decrypted = new byte[input.Length];
                using (ICryptoTransform decrypt = salsa20.CreateDecryptor())
                    decrypt.TransformBlock(encrypted, 0, encrypted.Length, decrypted, 0);

                CollectionAssert.AreEqual(input, decrypted);
            }
        }
        public void EcryptTestVector131072(string strComment, int rounds, string key, string iv, string strOutput0_63, string strOutput65472_65535, string strOutput65536_65599, string strOutput131008_131071)
        {
            byte[] output;

            // use the Salsa20 transform directly
            using (SymmetricAlgorithm salsa20 = new Salsa20() { Rounds = rounds })
            using (ICryptoTransform encrypt = salsa20.CreateEncryptor(ToBytes(key), ToBytes(iv)))
            {
                // input is all zeroes
                byte[] input = new byte[131072];
                output = encrypt.TransformFinalBlock(input, 0, input.Length);
            }

            CollectionAssert.AreEqual(ToBytes(strOutput0_63), output.Skip(0).Take(64).ToList());
            CollectionAssert.AreEqual(ToBytes(strOutput65472_65535), output.Skip(65472).Take(64).ToList());
            CollectionAssert.AreEqual(ToBytes(strOutput65536_65599), output.Skip(65536).Take(64).ToList());
            CollectionAssert.AreEqual(ToBytes(strOutput131008_131071), output.Skip(131008).Take(64).ToList());
        }
        public void EcryptTestVector512(string strComment, int rounds, string key, string iv, string strOutput0_63, string strOutput192_255, string strOutput256_319, string strOutput448_511)
        {
            const int c_nSize = 512;
            byte[] output = new byte[c_nSize];

            // encrypt by using CryptoStream
            using (SymmetricAlgorithm salsa20 = new Salsa20() { Rounds = rounds })
            using (ICryptoTransform encrypt = salsa20.CreateEncryptor(ToBytes(key), ToBytes(iv)))
            using (MemoryStream streamInput = new MemoryStream(new byte[c_nSize], false))
            using (CryptoStream streamEncrypted = new CryptoStream(streamInput, encrypt, CryptoStreamMode.Read))
            {
                streamEncrypted.Read(output, 0, output.Length);
            }

            CollectionAssert.AreEqual(ToBytes(strOutput0_63), output.Skip(0).Take(64).ToList());
            CollectionAssert.AreEqual(ToBytes(strOutput192_255), output.Skip(192).Take(64).ToList());
            CollectionAssert.AreEqual(ToBytes(strOutput256_319), output.Skip(256).Take(64).ToList());
            CollectionAssert.AreEqual(ToBytes(strOutput448_511), output.Skip(448).Take(64).ToList());
        }
        public void IV()
        {
            using (SymmetricAlgorithm salsa20 = new Salsa20())
            {
                Assert.Throws<ArgumentNullException>(() => salsa20.IV = null);
                Assert.Throws<CryptographicException>(() => salsa20.IV = new byte[9]);

                byte[] iv = new byte[] { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07 };
                salsa20.IV = iv;
                CollectionAssert.AreEqual(iv, salsa20.IV);
            }
        }
        public void Key()
        {
            using (SymmetricAlgorithm salsa20 = new Salsa20())
            {
                KeySizes[] sizes = salsa20.LegalKeySizes;
                Assert.AreEqual(1, sizes.Length);
                Assert.AreEqual(128, sizes[0].MinSize);
                Assert.AreEqual(256, sizes[0].MaxSize);
                Assert.AreEqual(128, sizes[0].SkipSize);

                Assert.Throws<ArgumentNullException>(() => salsa20.Key = null);
                Assert.Throws<CryptographicException>(() => salsa20.Key = new byte[8]);

                byte[] key16 = new byte[] { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f };
                salsa20.Key = key16;
                CollectionAssert.AreEqual(key16, salsa20.Key);

                byte[] key32 = new byte[] { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
                    0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f };
                salsa20.Key = key32;
                CollectionAssert.AreEqual(key32, salsa20.Key);
            }
        }
        public void Rounds()
        {
            using (global::Salsa20.Core.Salsa20 salsa20 = new Salsa20())
            {
                Assert.AreEqual(20, salsa20.Rounds);

                salsa20.Rounds = 12;
                Assert.AreEqual(12, salsa20.Rounds);

                salsa20.Rounds = 8;
                Assert.AreEqual(8, salsa20.Rounds);

                Assert.Throws<ArgumentOutOfRangeException>(() => salsa20.Rounds = 16);
            }
        }
        public void TransformFinalBlock()
        {
            using (SymmetricAlgorithm salsa20 = new Salsa20())
            using (ICryptoTransform transform = salsa20.CreateEncryptor(new byte[16], new byte[8]))
            {
                byte[] aby0 = new byte[0];
                byte[] aby1 = new byte[1];

                Assert.Throws<ArgumentNullException>(() => transform.TransformFinalBlock(null, 0, 0));
                Assert.Throws<ArgumentOutOfRangeException>(() => transform.TransformFinalBlock(aby0, -1, 0));
                Assert.Throws<ArgumentOutOfRangeException>(() => transform.TransformFinalBlock(aby0, 1, 0));
                Assert.Throws<ArgumentOutOfRangeException>(() => transform.TransformFinalBlock(aby1, 0, -1));
                Assert.Throws<ArgumentOutOfRangeException>(() => transform.TransformFinalBlock(aby1, 0, 2));
                Assert.Throws<ArgumentOutOfRangeException>(() => transform.TransformFinalBlock(aby1, 1, 1));
            }
        }