Beispiel #1
0
        // Generates keys for RSA signing
        public IxianKeyPair generateKeys(int keySize, bool skip_header = false)
        {
            KeyPair kp = null;

            try
            {
                KeyPairGenerator kpg = KeyPairGenerator.GetInstance("RSA");
                kpg.Initialize(keySize);
                kp = kpg.GenKeyPair();
                IxianKeyPair ixi_kp = new IxianKeyPair();
                ixi_kp.privateKeyBytes = rsaKeyToBytes(kp, true, skip_header);
                ixi_kp.publicKeyBytes  = rsaKeyToBytes(kp, false, skip_header);

                byte[] plain = Encoding.UTF8.GetBytes("Plain text string");
                if (!testKeys(plain, ixi_kp))
                {
                    return(null);
                }
                return(ixi_kp);
            }
            catch (Exception e)
            {
                Logging.warn(string.Format("Exception while generating signature keys: {0}", e.ToString()));
                return(null);
            }
        }
Beispiel #2
0
        public bool testKeys(byte[] plain, IxianKeyPair key_pair)
        {
            Logging.info("Testing generated keys.");
            // Try if RSACryptoServiceProvider considers them a valid key
            if (rsaKeyFromBytes(key_pair.privateKeyBytes) == null)
            {
                Logging.warn("RSA key is considered invalid by RSACryptoServiceProvider!");
                return(false);
            }

            byte[] encrypted = encryptWithRSA(plain, key_pair.publicKeyBytes);
            byte[] signature = getSignature(plain, key_pair.privateKeyBytes);

            if (!decryptWithRSA(encrypted, key_pair.privateKeyBytes).SequenceEqual(plain))
            {
                Logging.warn(string.Format("Error decrypting data while testing keys."));
                return(false);
            }

            if (!verifySignature(plain, key_pair.publicKeyBytes, signature))
            {
                Logging.warn(string.Format("Error verifying signature while testing keys."));
                return(false);
            }


            return(true);
        }
Beispiel #3
0
        public static void BenchmarkKeyGeneration(int num_iterations, int key_size, string output_file = "")
        {
            StreamWriter output = null;

            if (output_file != "")
            {
                output = File.CreateText(output_file);
            }
            // Testing some key generation features
            Logging.info("Preparing entropy to benchmark key generation speed...");
            byte[] entropy = getNewRandomSeed(1024 * 1024);
            IXICore.CryptoKey.KeyDerivation kd = new IXICore.CryptoKey.KeyDerivation(entropy);
            CryptoManager.initLib();
            Logging.info(String.Format("Starting key generation. Iterations: {0}", num_iterations));
            List <TimeSpan> generationTimes = new List <TimeSpan>();

            for (int i = 0; i < num_iterations; i++)
            {
                DateTime start = DateTime.Now;
                Logging.info(String.Format("Generating key {0}...", i));
                IxianKeyPair kp             = kd.deriveKey(i, key_size, 65537);
                TimeSpan     generationTime = DateTime.Now - start;
                bool         success        = CryptoManager.lib.testKeys(Encoding.Unicode.GetBytes("TEST TEST"), kp);
                double       key_entropy    = calculateBytestreamEntropy(kp.privateKeyBytes);
                if (success && output != null)
                {
                    RSACryptoServiceProvider rsaCSP = rsaKeyFromBytes(kp.privateKeyBytes);
                    RSAParameters            rsaP   = rsaCSP.ExportParameters(true);
                    BigInteger n = new BigInteger(rsaP.Modulus);
                    output.WriteLine(String.Format("{0}|{1}", n.ToString(), key_entropy));
                }
                Logging.info(String.Format("Key generated. ({0:0.00} ms)",
                                           generationTime.TotalMilliseconds));
                generationTimes.Add(generationTime);
                Logging.info(String.Format("Key test: {0}", success ? "success" : "failure"));
                Logging.info(String.Format("Key entropy: {0}", key_entropy));
            }
            if (output != null)
            {
                output.Flush();
                output.Close();
            }
            Logging.info(String.Format("Average time to generate a key: {0:0.00} ms", generationTimes.Average(x => x.TotalMilliseconds)));
            Logging.info(String.Format("Maximum time to generate a key: {0:0.00} ms", generationTimes.Max().TotalMilliseconds));
            return;
        }
Beispiel #4
0
        // Generates keys for RSA signing
        public IxianKeyPair generateKeys(int keySize, bool skip_header = false)
        {
            try
            {
                IxianKeyPair             kp  = new IxianKeyPair();
                RSACryptoServiceProvider rsa = new RSACryptoServiceProvider(keySize);
                kp.privateKeyBytes = rsaKeyToBytes(rsa, true, skip_header);
                kp.publicKeyBytes  = rsaKeyToBytes(rsa, false, skip_header);

                byte[] plain = Encoding.UTF8.GetBytes("Plain text string");
                if (!testKeys(plain, kp))
                {
                    return(null);
                }
                return(kp);
            }
            catch (Exception e)
            {
                Logging.warn(string.Format("Exception while generating signature keys: {0}", e.ToString()));
                return(null);
            }
        }
Beispiel #5
0
        private IxianKeyPair buildIxianKeyPair(byte[] rsa_key)
        {
            IxianKeyPair  kp        = new IxianKeyPair();
            AsnKeyParser  parser    = new AsnKeyParser(rsa_key);
            RSAParameters rsaParams = parser.ParseRSAPrivateKey();
            List <byte>   pubKey    = new List <byte>();

            pubKey.AddRange(BitConverter.GetBytes(rsaParams.Modulus.Length));
            pubKey.AddRange(rsaParams.Modulus);
            pubKey.AddRange(BitConverter.GetBytes(rsaParams.Exponent.Length));
            pubKey.AddRange(rsaParams.Exponent);
            kp.publicKeyBytes = pubKey.ToArray();
            kp.addressBytes   = (new Address(kp.publicKeyBytes)).address;

            List <byte> privKey = new List <byte>();

            privKey.AddRange(BitConverter.GetBytes(rsaParams.Modulus.Length));
            privKey.AddRange(rsaParams.Modulus);
            privKey.AddRange(BitConverter.GetBytes(rsaParams.Exponent.Length));
            privKey.AddRange(rsaParams.Exponent);
            privKey.AddRange(BitConverter.GetBytes(rsaParams.P.Length));
            privKey.AddRange(rsaParams.P);
            privKey.AddRange(BitConverter.GetBytes(rsaParams.Q.Length));
            privKey.AddRange(rsaParams.Q);
            privKey.AddRange(BitConverter.GetBytes(rsaParams.DP.Length));
            privKey.AddRange(rsaParams.DP);
            privKey.AddRange(BitConverter.GetBytes(rsaParams.DQ.Length));
            privKey.AddRange(rsaParams.DQ);
            privKey.AddRange(BitConverter.GetBytes(rsaParams.InverseQ.Length));
            privKey.AddRange(rsaParams.InverseQ);
            privKey.AddRange(BitConverter.GetBytes(rsaParams.D.Length));
            privKey.AddRange(rsaParams.D);
            kp.privateKeyBytes = privKey.ToArray();

            return(kp);
        }
Beispiel #6
0
        static bool runTests(string[] args)
        {
            Logging.log(LogSeverity.info, "Running Tests:");

            // Create a crypto lib
            CryptoLib    crypto_lib = new CryptoLib(new CryptoLibs.BouncyCastle());
            IxianKeyPair kp         = crypto_lib.generateKeys(CoreConfig.defaultRsaKeySize);

            Logging.log(LogSeverity.info, String.Format("Public Key base64: {0}", kp.publicKeyBytes));
            Logging.log(LogSeverity.info, String.Format("Private Key base64: {0}", kp.privateKeyBytes));


            /// ECDSA Signature test
            // Generate a new signature
            byte[] signature = crypto_lib.getSignature(Encoding.UTF8.GetBytes("Hello There!"), kp.publicKeyBytes);
            Logging.log(LogSeverity.info, String.Format("Signature: {0}", signature));

            // Verify the signature
            if (crypto_lib.verifySignature(Encoding.UTF8.GetBytes("Hello There!"), kp.publicKeyBytes, signature))
            {
                Logging.log(LogSeverity.info, "SIGNATURE IS VALID");
            }

            // Try a tamper test
            if (crypto_lib.verifySignature(Encoding.UTF8.GetBytes("Hello Tamper!"), kp.publicKeyBytes, signature))
            {
                Logging.log(LogSeverity.info, "SIGNATURE IS VALID AND MATCHES ORIGINAL TEXT");
            }
            else
            {
                Logging.log(LogSeverity.info, "TAMPERED SIGNATURE OR TEXT");
            }

            // Generate a new signature for the same text
            byte[] signature2 = crypto_lib.getSignature(Encoding.UTF8.GetBytes("Hello There!"), kp.privateKeyBytes);
            Logging.log(LogSeverity.info, String.Format("Signature Again: {0}", signature2));

            // Verify the signature again
            if (crypto_lib.verifySignature(Encoding.UTF8.GetBytes("Hello There!"), kp.publicKeyBytes, signature2))
            {
                Logging.log(LogSeverity.info, "SIGNATURE IS VALID");
            }



            Logging.log(LogSeverity.info, "-------------------------");

            // Generate a mnemonic hash from a 64 character string. If the result is always the same, it works correctly.
            Mnemonic mnemonic_addr = new Mnemonic(Wordlist.English, Encoding.ASCII.GetBytes("hahahahahahahahahahahahahahahahahahahahahahahahahahahahahahahaha"));

            Logging.log(LogSeverity.info, String.Format("Mnemonic Hashing Test: {0}", mnemonic_addr));
            Logging.log(LogSeverity.info, "-------------------------");


            // Create an address from the public key
            Address addr = new Address(kp.publicKeyBytes);

            Logging.log(LogSeverity.info, String.Format("Address generated from public key above: {0}", addr));
            Logging.log(LogSeverity.info, "-------------------------");


            // Testing sqlite wrapper
            var db = new SQLite.SQLiteConnection("storage.dat");

            // Testing internal data structures
            db.CreateTable <Block>();

            Block new_block = new Block();

            db.Insert(new_block);

            IEnumerable <Block> block_list = db.Query <Block>("select * from Block");

            if (block_list.OfType <Block>().Count() > 0)
            {
                Block first_block = block_list.FirstOrDefault();
                Logging.log(LogSeverity.info, String.Format("Stored genesis block num is: {0}", first_block.blockNum));
            }


            Logging.log(LogSeverity.info, "Tests completed successfully.\n\n");

            return(true);
        }