Exemplo n.º 1
43
        private void ParallelTest()
        {
            CSPRng rng = new CSPRng();
            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];
            rng.Dispose();

            using (ChaCha chacha = new ChaCha(10))
            {
                // encrypt linear
                chacha.Initialize(new KeyParams(key, iv));
                chacha.IsParallel = false;
                chacha.Transform(data, enc);
                // decrypt parallel
                chacha.Initialize(new KeyParams(key, iv));
                chacha.IsParallel = true;
                chacha.ParallelBlockSize = 2048;
                chacha.Transform(enc, dec);
            }

            if (!Compare.AreEqual(data, dec))
                throw new Exception("ChaCha: Decrypted arrays are not equal!");
        }
Exemplo n.º 2
0
        private void TestCompression()
        {
            Compress cmp = new Compress();
            MemoryStream cstm;

            /*string folder = @"C:\Tests\Compression Test";
            cstm = cmp.CompressArchive(folder);
            cstm.Position = 0;
            cmp.DeCompressArchive(cstm, folder + @"\Out");*/

            byte[] data = new CSPRng().GetBytes(1000);
            cstm = cmp.CompressStream(new MemoryStream(data));
            cstm.Position = 0;
            MemoryStream cmp2 = cmp.DeCompressStream(cstm);
            cmp2.Position = 0;

            if (!Compare.AreEqual(data, cmp2.ToArray()))
                throw new Exception("CompressionTest: decompressed array is not equal!");

            cmp.CompressionFormat = Compress.CompressionFormats.GZip;
            cstm = cmp.CompressStream(new MemoryStream(data));
            cstm.Position = 0;
            cmp2 = cmp.DeCompressStream(cstm);
            cmp2.Position = 0;

            if (!Compare.AreEqual(data, cmp2.ToArray()))
                throw new Exception("CompressionTest: decompressed array is not equal!");
        }
Exemplo n.º 3
0
        private void DigestTest()
        {
            CSPRng rng = new CSPRng();
            NTRUParameters param = (NTRUParameters)NTRUParamSets.EES1087EP2.DeepCopy();

            for (int i = 0; i < 3; i++)
            {
                if (i == 0)
                    param.Digest = Digests.Blake512;//blake512
                else if (i == 1)
                    param.Digest = Digests.Keccak512;//keccak512
                else
                    param.Digest = Digests.Skein512;//skein512

                NTRUKeyPair kp;
                using (NTRUKeyGenerator kg = new NTRUKeyGenerator(param))
                    kp = (NTRUKeyPair)kg.GenerateKeyPair();

                using (NTRUEncrypt ntru = new NTRUEncrypt(param))
                {
                    byte[] plainText = rng.GetBytes(32);
                    ntru.Initialize(kp.PublicKey);
                    byte[] encrypted = ntru.Encrypt(plainText);
                    ntru.Initialize(kp);
                    byte[] decrypted = ntru.Decrypt(encrypted);

                    if (!Compare.AreEqual(plainText, decrypted))
                        throw new Exception("NtruEncryptTest: digest test failed!");
                }
            }
        }
Exemplo n.º 4
0
        static double Decrypt(int Iterations, MPKCParameters Param)
        {
            MPKCKeyGenerator mkgen = new MPKCKeyGenerator(Param);
            IAsymmetricKeyPair akp = mkgen.GenerateKeyPair();
            byte[] ptext = new CSPRng().GetBytes(64);
            byte[] rtext = new byte[64];
            byte[] ctext;
            Stopwatch runTimer = new Stopwatch();

            using (MPKCEncrypt mpe = new MPKCEncrypt(Param))
            {
                mpe.Initialize(akp.PublicKey);
                ctext = mpe.Encrypt(ptext);
                mpe.Initialize(akp.PrivateKey);

                runTimer.Start();
                for (int i = 0; i < Iterations; i++)
                    rtext = mpe.Decrypt(ctext);
                runTimer.Stop();
            }

            //if (!Compare.AreEqual(ptext, rtext))
            //    throw new Exception("Encryption test: decryption failure!");

            return runTimer.Elapsed.TotalMilliseconds;
        }
Exemplo n.º 5
0
        private string CreateTempFile(int Size)
        {
            string path = Path.GetTempFileName();
            byte[] data = new CSPRng().GetBytes(Size);

            File.WriteAllBytes(path, data);

            return path;
        }
        /** tests mult(IntegerPolynomial) and mult(BigIntPolynomial) */
        private void MultTest()
        {
            CSPRng rng = new CSPRng();
            SparseTernaryPolynomial p1 = SparseTernaryPolynomial.GenerateRandom(1000, 500, 500, rng);
            IntegerPolynomial p2 = PolynomialGeneratorForTesting.generateRandom(1000);

            IntegerPolynomial prod1 = p1.Multiply(p2);
            prod1 = p1.Multiply(p2);
            IntegerPolynomial prod2 = p1.Multiply(p2);

            if (!Compare.Equals(prod1, prod2))
                throw new Exception("SparseTernaryPolynomial multiplication test failed!");

            BigIntPolynomial p3 = new BigIntPolynomial(p2);
            BigIntPolynomial prod3 = p1.Multiply(p3);

            if (!Compare.Equals(new BigIntPolynomial(prod1), prod3))
                throw new Exception("SparseTernaryPolynomial multiplication test failed!");
        }
Exemplo n.º 7
0
        /// <summary>
        /// Tests the SecureRandom access methods and return ranges
        /// </summary>
        /// <returns>Status</returns>
        public string Test()
        {
            try
            {
                SecRandTest();

                RandRangeTest(new BBSG(), 10);
                OnProgress(new TestEventArgs("Passed BBSG threshhold tests.."));
                RandRangeTest(new CCG(), 10);
                OnProgress(new TestEventArgs("Passed CCG threshhold tests.."));
                RandRangeTest(new CSPRng());
                OnProgress(new TestEventArgs("Passed CSPRng threshhold tests.."));
                RandRangeTest(new CTRPrng());
                OnProgress(new TestEventArgs("Passed CTRPrng threshhold tests.."));
                RandRangeTest(new DGCPrng());
                OnProgress(new TestEventArgs("Passed DGCPrng threshhold tests.."));
                RandRangeTest(new MODEXPG(), 10);
                OnProgress(new TestEventArgs("Passed MODEXPG threshhold tests.."));
                RandRangeTest(new QCG1(), 10);
                OnProgress(new TestEventArgs("Passed QCG1 threshhold tests.."));
                RandRangeTest(new QCG2(), 10);
                OnProgress(new TestEventArgs("Passed QCG2 threshhold tests.."));
                RandRangeTest(new SP20Prng(), 10);
                OnProgress(new TestEventArgs("Passed SP20Prng threshhold tests.."));

                byte[] pass, salt;
                CSPRng rand = new CSPRng();
                pass = rand.GetBytes(23);
                salt = rand.GetBytes(256);
                rand.Dispose();
                RandRangeTest(new PBPRng(new SHA512(), pass, salt));
                OnProgress(new TestEventArgs("Passed PBPRng threshhold tests.."));
                return SUCCESS;
            }
            catch (Exception Ex)
            {
                string message = Ex.Message == null ? "" : Ex.Message;
                throw new Exception(FAILURE + message);
            }
        }
        /// <summary>
        /// Test the validity of the BigDecimalPolynomial implementation
        /// </summary>
        /// 
        /// <returns>State</returns>
        public string Test()
        {
            try
            {
                BigDecimalPolynomial a = CreateBigDecimalPolynomial(new int[] { 4, -1, 9, 2, 1, -5, 12, -7, 0, -9, 5 });
                BigIntPolynomial b = new BigIntPolynomial(new IntegerPolynomial(new int[] { -6, 0, 0, 13, 3, -2, -4, 10, 11, 2, -1 }));
                BigDecimalPolynomial c = a.Multiply(b);
                if(!Compare.AreEqual(c.Coeffs, CreateBigDecimalPolynomial(new int[] { 2, -189, 77, 124, -29, 0, -75, 124, -49, 267, 34 }).Coeffs))
                    throw new Exception("The BigDecimalPolynomial test failed!");
                // multiply a polynomial by its inverse modulo 2048 and check that the result is 1
                IntegerPolynomial d, dInv;
                CSPRng rng = new CSPRng();

                do
                {
                    d = DenseTernaryPolynomial.GenerateRandom(1001, 333, 334, rng);
                    dInv = d.InvertFq(2048);
                } while (dInv == null);

                d.Mod(2048);
                BigDecimalPolynomial e = CreateBigDecimalPolynomial(d.Coeffs);
                BigIntPolynomial f = new BigIntPolynomial(dInv);
                IntegerPolynomial g = new IntegerPolynomial(e.Multiply(f).Round());
                g.ModPositive(2048);

                if (!g.EqualsOne())
                    throw new Exception("The BigDecimalPolynomial test failed!");
                OnProgress(new TestEventArgs("Passed BigDecimalPolynomial tests"));

                return SUCCESS;
            }
            catch (Exception Ex)
            {
                string message = Ex.Message == null ? "" : Ex.Message;
                throw new Exception(FAILURE + message);
            }
        }
        /// <summary>
        /// Test the validity of the DenseTernaryPolynomial implementation
        /// </summary>
        /// 
        /// <returns>State</returns>
        public string Test()
        {
            try
            {
                CheckTernarity(PolynomialGeneratorForTesting.generateRandom(1499));

                CSPRng rng = new CSPRng();
                for (int i = 0; i < 10; i++)
                {
                    int N = rng.Next(2000) + 10;
                    int numOnes = rng.Next(N);
                    int numNegOnes = rng.Next(N - numOnes);
                    CheckTernarity(DenseTernaryPolynomial.GenerateRandom(N, numOnes, numNegOnes, rng));
                }
                OnProgress(new TestEventArgs("Passed DenseTernaryPolynomial Ternarity"));

                return SUCCESS;
            }
            catch (Exception Ex)
            {
                string message = Ex.Message == null ? "" : Ex.Message;
                throw new Exception(FAILURE + message);
            }
        }
Exemplo n.º 10
0
        private bool MacTest3(byte[] IKm)
        {
            byte[] data = new CSPRng().GetBytes(33033);
            byte[] hash1;
            byte[] hash2;

            using (StreamMac mac1 = new StreamMac(new SHA512HMAC(IKm)))
            {
                mac1.Initialize(new MemoryStream(data));
                mac1.IsConcurrent = false;
                hash1 =  mac1.ComputeMac();
            }

            using (SHA512HMAC mac2 = new SHA512HMAC(IKm))
                hash2 = mac2.ComputeMac(data);

            return Compare.AreEqual(hash1, hash2);
        }
Exemplo n.º 11
0
        /// <remarks>
        /// 4 stage overwrite: random, reverse random, ones, zeros. 
        /// Last overwrite stage is zeros in Extract() method.
        /// </remarks>
        private void Erase(long Offset, long Length)
        {
            byte[] buffer =  new byte[Length];

            // get p-rand buffer
            using (CSPRng csp = new CSPRng())
                csp.GetBytes(buffer);

            // rand
            Overwrite(buffer, Offset, Length);
            // reverse rand
            Array.Reverse(buffer);
            Overwrite(buffer, Offset, Length);
            // ones
            for (int i = 0; i < buffer.Length; i++)
                buffer[i] = (byte)255;
            Overwrite(buffer, Offset, Length);
        }
Exemplo n.º 12
0
        /// <summary>
        /// A PackageKey header structure. 
        /// </summary>
        /// 
        /// <param name="Authority">The <see cref="KeyAuthority">KeyAuthority</see> structure containing the key authorization schema.</param>
        /// <param name="Cipher">The <see cref="CipherDescription">CipherDescription</see> structure containing a complete description of the cipher instance.</param>
        /// <param name="SubKeyCount">The number of Key Sets contained in this key package file.</param>
        /// <param name="ExtensionKey">An array of random bytes used to encrypt a message file extension. A null value auto generates this field.</param>
        /// 
        /// <exception cref="CryptoProcessingException">Thrown if an invalid ExtensionKey is used</exception>
        public PackageKey(KeyAuthority Authority, CipherDescription Cipher, int SubKeyCount, byte[] ExtensionKey = null)
        {
            this.KeyPolicy = Authority.KeyPolicy;
            this.Authority = Authority;
            this.Description = Cipher;
            this.SubKeyCount = SubKeyCount;
            SubKeyPolicy = new long[SubKeyCount];
            SubKeyID = new byte[SubKeyCount][];

            // generate the subkey ids and set master policy
            for (int i = 0; i < SubKeyCount; i++)
            {
                SubKeyPolicy[i] = (long)Authority.KeyPolicy;
                SubKeyID[i] = Guid.NewGuid().ToByteArray();
            }

            if (ExtensionKey != null)
            {
                if (ExtensionKey.Length != 16)
                    throw new CryptoProcessingException("PackageKey:CTor", "Extension key must be exactly 16 bytes in length!", new ArgumentOutOfRangeException());

                this.ExtensionKey = ExtensionKey;
            }
            else
            {
                using (CSPRng rand = new CSPRng())
                    this.ExtensionKey = rand.GetBytes(16);
            }

            CreatedOn = DateTime.Now.Ticks;
        }
Exemplo n.º 13
0
        private void MacTests()
        {
            string path = CreateTempFile(117674);
            byte[] Ikm = new CSPRng().GetBytes(32);
            byte[] x1 = MacTest1(path, Ikm);
            byte[] y1 = MacTest2(path, Ikm);

            if (File.Exists(path))
                File.Delete(path);

            if ((Compare.AreEqual(x1, y1) == false))
                throw new Exception("Failed! Mac outputs are not equal");

            OnProgress(new TestEventArgs("Passed round 1 comparisons.."));

            path = CreateTempFile(69041);
            x1 = MacTest1(path, Ikm);
            y1 = MacTest2(path, Ikm);

            if (File.Exists(path))
                File.Delete(path);

            if ((Compare.AreEqual(x1, y1) == false))
                throw new Exception("Failed! Mac outputs are not equal");

            OnProgress(new TestEventArgs("Passed round 2 comparisons.."));

            path = CreateTempFile(65536);
            x1 = MacTest1(path, Ikm);
            y1 = MacTest2(path, Ikm);

            if (File.Exists(path))
                File.Delete(path);

            if ((Compare.AreEqual(x1, y1) == false))
                throw new Exception("Failed! Mac outputs are not equal");

            OnProgress(new TestEventArgs("Passed round 3 comparisons.."));

            if (!MacTest3(Ikm))
                throw new Exception("Failed! Mac outputs are not equal");

            OnProgress(new TestEventArgs("Passed round 4 comparisons.."));
        }
Exemplo n.º 14
0
        // tests key pair generation from a passphrase
        private void GenerateKeyPair()
        {
            NTRUParameters param = (NTRUParameters)NTRUParamSets.EES1087EP2FAST.DeepCopy();
            byte[] passphrase = Encoding.Unicode.GetBytes("password123");
            byte[] salt = new CSPRng().GetBytes(16);

            NTRUKeyPair kp1;
            using (NTRUKeyGenerator kg = new NTRUKeyGenerator(param, false)) // note: parallel must be turned off with passphrase prng
                kp1 = (NTRUKeyPair)kg.GenerateKeyPair(passphrase, salt);
            NTRUKeyPair kp2;
            using (NTRUKeyGenerator kg = new NTRUKeyGenerator(param, false))
                kp2 = (NTRUKeyPair)kg.GenerateKeyPair(passphrase, salt);

            NTRUEncrypt ntru = new NTRUEncrypt(param);
            NTRUEncrypt ntru2 = new NTRUEncrypt(NTRUParamSets.EES1087EP2FAST);

            if (!kp1.Equals(kp2))
                throw new Exception("NtruEncryptTest: key pair generation test failed!");

            salt = ntru.GenerateSalt();
            NTRUKeyPair kp3;
            using (NTRUKeyGenerator kg = new NTRUKeyGenerator(param, false))
                kp3 = (NTRUKeyPair)kg.GenerateKeyPair(passphrase, salt);

            if (!Compare.False(kp1.Equals(kp3)))
                throw new Exception("NtruEncryptTest: key pair generation test failed!");
        }
        private void FromToBinary()
        {
            CSPRng rng = new CSPRng();
            int N = 1000;
            SparseTernaryPolynomial poly1 = SparseTernaryPolynomial.GenerateRandom(N, 100, 101, rng);
            MemoryStream poly1Stream = new MemoryStream(poly1.ToBinary());
            SparseTernaryPolynomial poly2 = SparseTernaryPolynomial.FromBinary(poly1Stream, N);

            if (!Compare.Equals(poly1, poly2))
                throw new Exception("SparseTernaryPolynomial FromToBinary test failed!");
        }
        private void GenerateRandom()
        {
            CSPRng rng = new CSPRng();
            Verify(SparseTernaryPolynomial.GenerateRandom(743, 248, 248, rng));

            for (int i = 0; i < 10; i++)
            {
                int N = rng.Next(2000) + 10;
                int numOnes = rng.Next(N);
                int numNegOnes = rng.Next(N - numOnes);
                Verify(SparseTernaryPolynomial.GenerateRandom(N, numOnes, numNegOnes, rng));
            }
        }
        private void FromToBinary()
        {
            CSPRng rng = new CSPRng();
            ProductFormPolynomial p1 = ProductFormPolynomial.GenerateRandom(_N, _df1, _df2, _df3, _df3 - 1, rng);
            byte[] bin1 = p1.ToBinary();
            ProductFormPolynomial p2 = ProductFormPolynomial.FromBinary(bin1, _N);

            if (!Compare.Equals(p1, p2))
                throw new Exception("ProductFormPolynomial FromToBinary test failed!");
        }
        private void MultTest()
        {
            CSPRng rng = new CSPRng();
            ProductFormPolynomial p1 = ProductFormPolynomial.GenerateRandom(_N, _df1, _df2, _df3, _df3 - 1, rng);
            IntegerPolynomial p2 = PolynomialGeneratorForTesting.GenerateRandom(_N, _Q);
            IntegerPolynomial p3 = p1.Multiply(p2);
            IntegerPolynomial p4 = p1.ToIntegerPolynomial().Multiply(p2);

            if (!Compare.Equals(p3, p4))
                throw new Exception("ProductFormPolynomial multiplication test failed!");
        }
Exemplo n.º 19
0
        /// <summary>
        /// Get an open and randomly selected port number within a range
        /// </summary>
        /// 
        /// <param name="From">The minimum port number (default is 49152)</param>
        /// <param name="To">The maximum port number (default is 65535)</param>
        /// <returns>An open port number</returns>
        /// 
        /// <exception cref="CryptoSocketException">Thrown if the operation is in an error state</exception>
        public int NextOpenPort(int From = 49152, int To = 65535)
        {
            CSPRng rnd = new CSPRng();

            int port = -1;

            do
            {
                if (IsPortOpen((port = rnd.Next(From, To))))
                    break;

            } while (true);

            return port;
        }
Exemplo n.º 20
0
        static double Encrypt(int Iterations, MPKCParameters Param)
        {
            MPKCKeyGenerator mkgen = new MPKCKeyGenerator(Param);
            IAsymmetricKeyPair akp = mkgen.GenerateKeyPair();
            byte[] ptext = new CSPRng().GetBytes(64);
            byte[] ctext;
            Stopwatch runTimer = new Stopwatch();

            using (MPKCEncrypt mpe = new MPKCEncrypt(Param))
            {
                mpe.Initialize(akp.PublicKey);

                runTimer.Start();
                for (int i = 0; i < Iterations; i++)
                    ctext = mpe.Encrypt(ptext);
                runTimer.Stop();
            }

            return runTimer.Elapsed.TotalMilliseconds;
        }
Exemplo n.º 21
0
        private bool HashTest3()
        {
            byte[] data = new CSPRng().GetBytes(33033);
            byte[] hash1;
            byte[] hash2;

            using (StreamDigest dgt1 = new StreamDigest(new SHA512()))
            {
                dgt1.Initialize(new MemoryStream(data));
                // run concurrent mode
                dgt1.IsConcurrent = true;
                hash1 = dgt1.ComputeHash();
            }

            using (SHA512 dgt2 = new SHA512())
                hash2 = dgt2.ComputeHash(data);

            return Compare.AreEqual(hash1, hash2);
        }