Exemplo n.º 1
0
        public override void ImportParameters(RSAParameters parameters)
        {
            try
            {
                // http://developer.android.com/reference/java/security/KeyFactory.html

                // X:\jsc.svn\core\ScriptCoreLibJava\java\security\interfaces\RSAPublicKey.cs
                // https://gist.github.com/manzke/1068441
                // http://stackoverflow.com/questions/11410770/java-load-rsa-public-key-from-file

                // https://sites.google.com/a/jsc-solutions.net/backlog/knowledge-base/2014/201408/20140829
                // https://sites.google.com/a/jsc-solutions.net/backlog/knowledge-base/2015/201503/20150323
                // X:\jsc.svn\examples\javascript\Test\TestWebCryptoKeyExport\TestWebCryptoKeyExport\ApplicationWebService.cs
                // tested by ?

                var rsa = KeyFactory.getInstance("RSA");


                var rsaModulusBytes = parameters.Modulus;

                #region firstByte
                var firstByte = rsaModulusBytes[0];
                if (firstByte != 0)
                {
                    // jvm likes a leading 0 ?

                    rsaModulusBytes = new byte[parameters.Modulus.Length + 1];

                    Array.Copy(
                        parameters.Modulus,
                        0,

                        rsaModulusBytes,
                        1,

                        parameters.Modulus.Length
                        );
                }
                #endregion

                var Modulus  = new BigInteger((sbyte[])(object)rsaModulusBytes);
                var Exponent = new BigInteger((sbyte[])(object)parameters.Exponent);

                //Console.WriteLine("RSACryptoServiceProvider.ImportParameters " + new { m = parameters.Modulus.Length, e = parameters.Exponent.Length });

                var s = new RSAPublicKeySpec(Modulus, Exponent);

                this.InternalRSAPublicKey = (RSAPublicKey)rsa.generatePublic(s);
                this.InternalParameters   = parameters;
            }
            catch
            {
                throw;
            }
        }
Exemplo n.º 2
0
        public override byte[] HostKeyMD5FingerPrint()
        {
            SSH1DataWriter wr = new SSH1DataWriter();
            //RSA only for SSH1
            RSAPublicKey rsa = (RSAPublicKey)_hostkey;

            wr.WriteBigInteger(rsa.Exponent);
            wr.WriteBigInteger(rsa.Modulus);

            return(new MD5CryptoServiceProvider().ComputeHash(wr.ToByteArray()));
        }
Exemplo n.º 3
0
        // ctor()?
        public __RSACryptoServiceProvider(int dwKeySize, CspParameters parameters)
        {
            // what if ctor is here for import instead of gen?
            // X:\jsc.svn\examples\java\hybrid\JVMCLRRSACryptoServiceProviderExport\JVMCLRRSACryptoServiceProviderExport\Program.cs

            // If this is not a random container we generate, create it eagerly
            // in the constructor so we can report any errors now.

            //  Environment.GetCompatibilityFlag(CompatibilityFlag.EagerlyGenerateRandomAsymmKeys)
            //    GetKeyPair();


            // We only attempt to generate a random key on desktop runtimes because the CoreCLR
            // RSA surface area is limited to simply verifying signatures.  Since generating a
            // random key to verify signatures will always lead to failure (unless we happend to
            // win the lottery and randomly generate the signing key ...), there is no need
            // to add this functionality to CoreCLR at this point.

            // ? what

            this.dwKeySize  = dwKeySize;
            this.parameters = parameters;

            // when would we want to delay key gen?
            // lets gen it early.

            // X:\jsc.svn\examples\javascript\appengine\Test\TestCryptoKeyGenerate\TestCryptoKeyGenerate\ApplicationWebService.cs

            try
            {
                // it works.
                // can we now wrap rsa for all platforms
                // and use it as a generic nuget?

                var sw = Stopwatch.StartNew();
                Console.WriteLine("RSACryptoServiceProvider before generateKeyPair " + new { dwKeySize });

                var keyGen = KeyPairGenerator.getInstance("RSA");

                keyGen.initialize(dwKeySize);

                this.InternalKeyPair      = keyGen.generateKeyPair();
                this.InternalRSAPublicKey = (RSAPublicKey)this.InternalKeyPair.getPublic();

                Console.WriteLine("RSACryptoServiceProvider after generateKeyPair " + new { sw.ElapsedMilliseconds });

                //before generateKeyPair { { ElapsedMilliseconds = 2 } }
                //after generateKeyPair { { ElapsedMilliseconds = 1130 } }
            }
            catch
            {
                throw;
            }
        }
Exemplo n.º 4
0
        public void TestPKICertificate()
        {
            byte[] rawdata = new byte[8001];
            new Random().NextBytes(rawdata);

            byte[] cypher;
            using (RSAPublicKey publicKey = new RSAPublicKey(TestCertPublicKey()))
                cypher = publicKey.Encrypt(rawdata);

            using (RSAPrivateKey privateKey = new RSAPrivateKey(TestCertPrivateKey()))
                Assert.AreEqual(rawdata, privateKey.Decrypt(cypher));
        }
Exemplo n.º 5
0
        /**
         * Encrypt message Tab
         */
        private void buttonEncryptChoosePublicKey_Click(object sender, EventArgs e)
        {
            OpenFileDialog openFileDialog = new OpenFileDialog();

            openFileDialog.Title            = "Choose public key";
            openFileDialog.Filter           = "Public key (*.public)|*.public";
            openFileDialog.InitialDirectory = AppDomain.CurrentDomain.BaseDirectory;
            if (openFileDialog.ShowDialog() == DialogResult.OK)
            {
                labelEncryptPublicKeyFile.Text = Path.GetFileName(openFileDialog.FileName);
                publicKey = RSAPublicKey.LoadFromFile(openFileDialog.FileName);
            }
        }
Exemplo n.º 6
0
        public static void TestClassInit(TestContext context)
        {
            _rsaProvider = new RSACryptoServiceProvider();

            string publicKeyXml  = _rsaProvider.ToXmlString(false);
            string privateKeyXml = _rsaProvider.ToXmlString(true);

            _rsaPublicXml  = publicKeyXml;
            _rsaPrivateXml = privateKeyXml;

            _rsaPublic  = RSAPublicKey.FromXmlString(publicKeyXml);
            _rsaPrivate = RSAPrivateKey.FromXmlString(privateKeyXml);
        }
Exemplo n.º 7
0
        void SendClientKeyExchangeRSA(RSAPublicKey pkey)
        {
            byte[] pms = new byte[48];
            IO.Enc16be(Version, pms, 0);
            RNG.GetBytes(pms, 2, pms.Length - 2);
            byte[]       epms = RSA.Encrypt(pkey, pms);
            MemoryStream ms   =
                StartHandshakeMessage(SSL.CLIENT_KEY_EXCHANGE);

            IO.Write16(ms, epms.Length);
            ms.Write(epms, 0, epms.Length);
            EndHandshakeMessage(ms);
            ComputeMaster(pms);
        }
Exemplo n.º 8
0
        public override string DumpHostKeyInKnownHostsStyle()
        {
            StringBuilder bld = new StringBuilder();

            bld.Append("ssh1 ");
            SSH1DataWriter wr = new SSH1DataWriter();
            //RSA only for SSH1
            RSAPublicKey rsa = (RSAPublicKey)_hostkey;

            wr.WriteBigInteger(rsa.Exponent);
            wr.WriteBigInteger(rsa.Modulus);
            bld.Append(Encoding.ASCII.GetString(Base64.Encode(wr.ToByteArray())));
            return(bld.ToString());
        }
Exemplo n.º 9
0
        public string DumpHostKeyInKnownHostsStyle()
        {
            StringBuilder bld = new StringBuilder();

            bld.Append("ssh1 ");
            SSH1DataWriter wr = new SSH1DataWriter();
            //RSA only for SSH1
            RSAPublicKey rsa = (RSAPublicKey)_hostkey;

            wr.Write(rsa.Exponent);
            wr.Write(rsa.Modulus);
            byte[] tmpdata = Base64.Encode(wr.ToByteArray());
            bld.Append(Encoding.UTF8.GetString(tmpdata, 0, tmpdata.Length));
            return(bld.ToString());
        }
Exemplo n.º 10
0
        public static Dictionary <CertificationAuthorityReference, RSAPublicKey> LoadGen1RSAPublicKeys()
        {
            Assembly assembly = typeof(Validator).GetTypeInfo().Assembly;
            string   name     = assembly.FullName.Split(',')[0] + ".EC_PK.bin";
            var      reader   = new BinaryReader(assembly.GetManifestResourceStream(name));

            var certificationAuthorityReference = new CertificationAuthorityReference(reader);
            var rsaPublicKey = new RSAPublicKey(reader);

            var rsaPublicKeys = new Dictionary <CertificationAuthorityReference, RSAPublicKey>();

            rsaPublicKeys.Add(certificationAuthorityReference, rsaPublicKey);

            return(rsaPublicKeys);
        }
Exemplo n.º 11
0
            /// <summary>
            /// Constructor
            /// </summary>
            /// <param name="hostName">host name</param>
            /// <param name="portNumber">port number</param>
            /// <param name="hostKey">host key</param>
            public SSH2HostKeyInformationProvider(string hostName, int portNumber, PublicKey hostKey)
            {
                HostName   = hostName;
                PortNumber = portNumber;

                _hostKey = hostKey;

                _knownHostsString =
                    new Lazy <string>(
                        () => {
                    // Poderosa known_hosts format
                    return(new StringBuilder()
                           .Append(SSH2Util.PublicKeyAlgorithmName(_hostKey.Algorithm))
                           .Append(' ')
                           .Append(Encoding.ASCII.GetString(Base64.Encode(_encodedHostKey.Value)))
                           .ToString());
                },
                        false
                        );

                _encodedHostKey =
                    new Lazy <byte[]>(
                        () => {
                    SSH2PayloadImageBuilder image = new SSH2PayloadImageBuilder(0x10000);
                    image.WriteString(SSH2Util.PublicKeyAlgorithmName(_hostKey.Algorithm));
                    if (_hostKey is RSAPublicKey)
                    {
                        RSAPublicKey rsa = (RSAPublicKey)_hostKey;
                        image.WriteBigInteger(rsa.Exponent);
                        image.WriteBigInteger(rsa.Modulus);
                    }
                    else if (_hostKey is DSAPublicKey)
                    {
                        DSAPublicKey dsa = (DSAPublicKey)_hostKey;
                        image.WriteBigInteger(dsa.P);
                        image.WriteBigInteger(dsa.Q);
                        image.WriteBigInteger(dsa.G);
                        image.WriteBigInteger(dsa.Y);
                    }
                    else
                    {
                        throw new SSHException("Host key algorithm is unsupported");
                    }
                    return(image.GetBytes());
                },
                        false
                        );
            }
Exemplo n.º 12
0
    public static byte[] Encrypt(byte[] data, RSAPublicKey publicKey)
    {
        if (data == null)
        {
            throw new ArgumentNullException("data");
        }

        if (publicKey == null)
        {
            throw new ArgumentNullException("publicKey");
        }

        int blockSize = publicKey.Modulus.Length - 1;

        return(Compute(data, publicKey, blockSize));
    }
Exemplo n.º 13
0
        public static RSAKeyPair GenerateRSAKeyPair()
        {
            var p = BigIntegerRandomGenerator.GetBigRandomPrime();
            var q = BigIntegerRandomGenerator.GetBigRandomPrime();

            var n = BigInteger.Multiply(p, q);

            var eulerFuncValue = BigInteger.Multiply(p - 1, q - 1);

            var e = BigInteger.Pow(2, 16) + 1;

            while (true)
            {
                var gcd = BigInteger.GreatestCommonDivisor(eulerFuncValue, e);

                if (gcd != 1)
                {
                    _logger.Info("gcd(e, euler)={0}    Generating new random number", gcd);

                    e = BigIntegerRandomGenerator.GetBigRandomPrime();
                }
                else
                {
                    break;
                }
            }

            var d = ExtendedGCD.ModInverse(e, eulerFuncValue);

            _logger.Info("d={0}", d);

            /*
             * var checkRes = BigInteger.Multiply(d, e);
             *
             *
             * checkRes = BigInteger.Remainder(checkRes, eulerFuncValue);
             *
             * _logger.Info("Check: {0}", checkRes);
             */

            var publicKey  = new RSAPublicKey(n, e);
            var privateKey = new RSAPrivateKey(n, d);

            var keyPair = new RSAKeyPair(publicKey, privateKey);

            return(keyPair);
        }
Exemplo n.º 14
0
    public static byte[] Encrypt(byte[] data, RSAPublicKey publicKey)
    {
        if (data == null)
        {
            throw new ArgumentNullException("data");
        }

        if (publicKey == null)
        {
            throw new ArgumentNullException("publicKey");
        }

        BigInteger e = new BigInteger(publicKey.Exponent);
        BigInteger n = new BigInteger(publicKey.Modulus);

        int inputBlockMaxSize = publicKey.Modulus.Length - 1;
        int outputBlockSize   = publicKey.Modulus.Length + 1;

        using (MemoryStream stream = new MemoryStream()) {
            int inputBlockOffset  = 0;
            int outputBlockOffset = 0;

            int    lastInputBlockSize     = data.Length % inputBlockMaxSize;
            byte[] lastInputBlockSizeData = BitConverter.GetBytes(lastInputBlockSize);
            stream.Write(lastInputBlockSizeData, 0, lastInputBlockSizeData.Length);
            outputBlockOffset += lastInputBlockSizeData.Length;

            while (inputBlockOffset < data.Length)
            {
                int    inputBlockSize = Math.Min(inputBlockMaxSize, data.Length - inputBlockOffset);
                byte[] inputBlockData = new byte[inputBlockSize + 1];
                Buffer.BlockCopy(data, inputBlockOffset, inputBlockData, 0, inputBlockSize);
                inputBlockOffset += inputBlockSize;

                BigInteger mi = new BigInteger(inputBlockData);
                BigInteger ci = BigInteger.ModPow(mi, e, n);//ci = mi^e ( mod n )

                byte[] outputBlockData = ci.ToByteArray();
                stream.Write(outputBlockData, 0, outputBlockData.Length);
                outputBlockOffset += outputBlockSize;
                stream.Seek(outputBlockOffset, SeekOrigin.Begin);
            }

            stream.SetLength(outputBlockOffset);
            return(stream.ToArray());
        }
    }
Exemplo n.º 15
0
        public void TestPublicKeyExport()
        {
            RSAPublicKey pk  = new RSAPrivateKey().PublicKey;
            string       xml = pk.ToXml();

            RSAPublicKey copy = RSAPublicKey.FromXml(xml);

            Assert.AreEqual(xml, copy.ToXml());

            byte[] bytes = pk.ToArray();
            Assert.AreEqual(148, bytes.Length);

            copy = RSAPublicKey.FromBytes(bytes);
            Assert.AreEqual(bytes, copy.ToArray());

            copy = RSAPublicKey.FromParameters(pk.ExportParameters());
            Assert.AreEqual(bytes, copy.ToArray());
        }
Exemplo n.º 16
0
        /// <summary>
        /// Handles a public key request from another user
        /// </summary>
        /// <returns></returns>
        public RSAPublicKey RequestRSAPublicKey()
        {
            rsa = new RSA(this.PrimalityTestToUse, this.SecurityToken);

            rsa.KeyGeneration(KeySize);

            RSAPublicKey publicKey = rsa.PublicKey;

            this.nLabel.Text = publicKey.N.ToString();
            this.eLabel.Text = publicKey.E.ToString();

            RSAPrivateKey privateKey = rsa.PrivateKey;

            this.pLabel.Text   = privateKey.P.ToString();
            this.qLabel.Text   = privateKey.Q.ToString();
            this.dLabel.Text   = privateKey.D.ToString();
            this.phiLabel.Text = privateKey.Phi.ToString();

            return(publicKey);
        }
Exemplo n.º 17
0
        private void buttonEncrypt_Click(object sender, EventArgs e)
        {
            if (textBoxEncryptMessage.Text.Length == 0)
            {
                MessageBox.Show("Введите текст сообщения!", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            if (publicKey == null)
            {
                MessageBox.Show("Выберете открытый ключ!", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            textBoxEncryptedText.Text      = publicKey.Encrypt(textBoxEncryptMessage.Text);
            buttonEncryptSave.Enabled      = true;
            textBoxEncryptMessage.Text     = "";
            labelEncryptPublicKeyFile.Text = "";
            publicKey = null;
        }
Exemplo n.º 18
0
            public CertificateGen1(byte[] certificateData)
            {
                using (var reader = new CustomBinaryReader(new MemoryStream(certificateData)))
                {
                    this.profileIdentifier = Convert.ToInt32(reader.ReadByte());
                    this.certificationAuthorityReference = new CertificationAuthorityReference(reader);
                    this.holderAuthorisation             = reader.ReadBytes(7);

                    var timestamp = reader.ReadSInt32();
                    if (timestamp != 0xFFFFFFFF)
                    {
                        this.endOfValidity = DateTimeOffset.FromUnixTimeSeconds(timestamp);
                    }
                    else
                    {
                        this.endOfValidity = null;
                    };
                    this.holderReference = reader.ReadBytes(8);
                    this.publicKey       = new RSAPublicKey(reader);
                };
            }
Exemplo n.º 19
0
    public static byte[] Sign(byte[] data, RSAPublicKey publicKey, HashAlgorithm hash)
    {
        if (data == null)
        {
            throw new ArgumentNullException("data");
        }

        if (publicKey == null)
        {
            throw new ArgumentNullException("publicKey");
        }

        if (hash == null)
        {
            throw new ArgumentNullException("hash");
        }

        byte[] hashData  = hash.ComputeHash(data);
        byte[] signature = Encrypt(hashData, publicKey);
        return(signature);
    }
Exemplo n.º 20
0
        private void test2()
        {
            RSACryptoServiceProvider _rsa       = new RSACryptoServiceProvider();
            RSAParameters            parameters = _rsa.ExportParameters(true);
            string Exponent = BitConverter.ToString(parameters.Exponent);
            string Mosulus  = BitConverter.ToString(parameters.Modulus);
            string D        = BitConverter.ToString(parameters.D);

            string publicKey  = _rsa.ToXmlString(false);
            string privateKey = _rsa.ToXmlString(true);

            _rsa.Clear();


            RSAPublicKey  _publicKey  = RSAPublicKey.FromXmlString(publicKey);
            RSAPrivateKey _privateKey = RSAPrivateKey.FromXmlString(privateKey);

            string input = "这个极简单的 BigInteger 类的全部源程序代码可以在本随笔开头给出的 URL 中找到,只有五十多行。她是基于 10 进制的,内部使用一个 int[] 来存储,需要事先指定该数组的大小,不能动态增长,而且只能表示非负整数。";

            PublicKeyEncrypt(input, _publicKey, _privateKey);
            PublicKeySign(input, _publicKey, _privateKey);
        }
Exemplo n.º 21
0
        public void ServerKeyPassword(
            [Argument("site", "s", Description = "The root http address of the website copy.")]
            string site,
            [Argument("password", "p", Description = "The password to be used (obtained from CreateKeys).")]
            string passwordText)
        {
            HttpRequestUtil util = new HttpRequestUtil(new Uri(site, UriKind.Absolute));

            if (util.Post("/api/publish/set-password/", "application/binary", null, 0) == System.Net.HttpStatusCode.OK)
            {
                using (RSAPublicKey pk = RSAPublicKey.FromBytes(util.Content))
                {
                    byte[] passbytes = pk.Encrypt(Convert.FromBase64String(passwordText));
                    if (util.Post("/api/publish/set-password/", "application/binary", passbytes, passbytes.Length) == System.Net.HttpStatusCode.OK)
                    {
                        Console.WriteLine("Success.");
                        return;
                    }
                }
                Console.WriteLine("FAILURE: You need verify the key file or check the server and try again.");
            }
        }
Exemplo n.º 22
0
        public static RSAKey NetToJava(RSAKey rsakey)
        {

            //公钥  
            byte[] m = Base64.decodeBase64("mX/9zl8rflH5pLaP5P1Qd/9wXwNBSx7OpLlYDnGr7wD0njiDfPSUkgf9oF5NcvZwl24qdJ1SLmrgUtnr+yeXBNZNKaan1xXKISHdlHvbW5G8nJCJW6CuaHMkVw3Y7kwaIIlUdv09vxfjj0AoabttjbtF1kqETzbQ6fK3EN6sY5U=");
            byte[] e = Base64.decodeBase64("AQAB");
            BigInteger b1 = new BigInteger(1, m);
            BigInteger b2 = new BigInteger(1, e);
            //私钥  
            byte[] m1 = Base64.decodeBase64("3RgqP5YOYUXft8YOlDphyaCoof27MSfTD2eVCFVXB5hatrls1fSUcmUuWuGV970sS6KQZZtyWHQ5970sCzKFlq82He8Uoe0JM3axBvd6PbSGjulUJr62qNW5hgkIEfxSRYl8AQsbbusFtks4obfepsfE02cLmmZepnZAdIOWifE=");
            byte[] e1 = Base64.decodeBase64("QcSZdLbHakolxX4GAjPnuNmwsBdRIsss7o0qeQMh02GPwoEgDfkmW20bv+8Q9FPypEEkYQU/m25ffAFq453QvLegYYi8OvWN+dvgchQRdeb22d+s6xYGGN9DRcPFRE48INde8FBHf/lzVgToV75h1H7g+jB4hLmLeuIuHsB43/0=");
            BigInteger b11 = new BigInteger(1, m1);
            BigInteger b21 = new BigInteger(1, e1);
            //公钥  
            KeyFactory keyFactory = KeyFactory.getInstance("RSA");
            RSAPublicKeySpec keySpec = new RSAPublicKeySpec(b1, b2);
            RSAPublicKey pubKey = (RSAPublicKey)keyFactory.generatePublic(keySpec);
            //私钥  
            RSAPrivateKeySpec priKeySpec = new RSAPrivateKeySpec(b11, b21);
            RSAPrivateKey priKey = (RSAPrivateKey)keyFactory.generatePrivate(priKeySpec);

        }
Exemplo n.º 23
0
        private void PublicKeySign(string input, RSAPublicKey _publicKey, RSAPrivateKey _privateKey)
        {
            byte[]      inputData = Encoding.UTF8.GetBytes(input);
            SHA1Managed sha1      = new SHA1Managed();

            DateTime d1 = DateTime.Now;

            byte[]   signature = RSAManaged.Sign(inputData, _publicKey, sha1);
            TimeSpan t1        = DateTime.Now - d1;

            Console.WriteLine("公钥签名用时:{0}", t1);

            DateTime d2     = DateTime.Now;
            bool     result = RSAManaged.Verify(inputData, _privateKey, sha1, signature);
            TimeSpan t2     = DateTime.Now - d2;

            Console.WriteLine("私钥验证用时:{0}", t2);

            sha1.Clear();
            Console.WriteLine(string.Format("私钥验证结果:{0}", result));
            Console.WriteLine();
        }
Exemplo n.º 24
0
        public virtual unsafe void ImportRSAPublicKey(ReadOnlySpan <byte> source, out int bytesRead)
        {
            fixed(byte *ptr = &MemoryMarshal.GetReference(source))
            {
                using (MemoryManager <byte> manager = new PointerMemoryManager <byte>(ptr, source.Length))
                {
                    RSAPublicKey key = AsnSerializer.Deserialize <RSAPublicKey>(
                        manager.Memory,
                        AsnEncodingRules.BER,
                        out int localRead);

                    RSAParameters rsaParameters = new RSAParameters
                    {
                        Modulus  = key.Modulus.ToByteArray(isUnsigned: true, isBigEndian: true),
                        Exponent = key.PublicExponent.ToByteArray(isUnsigned: true, isBigEndian: true),
                    };

                    ImportParameters(rsaParameters);
                    bytesRead = localRead;
                }
            }
        }
Exemplo n.º 25
0
            public RSAKey(XmlReader reader)
            {
                _privateKey    = null;
                _hasPrivateKey = XmlConvert.ToBoolean(reader.GetAttribute("private") ?? "0");

                XmlReader subtree = reader.ReadSubtree();

                while (subtree.Read())
                {
                    if (subtree.LocalName == "public")
                    {
                        _publicHash = Hash.FromString(subtree.GetAttribute("hash"));
                        _publicKey  = RSAPublicKey.FromXml(subtree.ReadSubtree());
                    }
                    else if (subtree.LocalName == "private")
                    {
                        _privateHash      = Hash.FromString(subtree.GetAttribute("hash"));
                        _passwordRequired = XmlConvert.ToBoolean(subtree.GetAttribute("protected") ?? "0");
                        _privateBits      = Convert.FromBase64String(subtree.ReadElementString("private"));
                    }
                }
            }
Exemplo n.º 26
0
        public void TestSignAndVerifyHash()
        {
            byte[] data = new byte[100];
            new Random().NextBytes(data);

            foreach (HashAlgorithm ha in new HashAlgorithm[] { MD5.Create(), SHA1.Create(), SHA256.Create(), SHA384.Create(), SHA512.Create() })
            {
                Hash hash = Hash.FromBytes(ha.ComputeHash(data));
                Assert.AreEqual(CryptoConfig.MapNameToOID(ha.GetType().FullName), hash.AlgorithmOID);

                using (RSAPrivateKey key = new RSAPrivateKey())
                {
                    byte[] sig = key.SignHash(hash);

                    using (RSAPublicKey pub = key.PublicKey)
                    {
                        Assert.IsTrue(pub.VerifyHash(sig, Hash.FromBytes(ha.ComputeHash(data))));
                        data[0] = (byte)~data[0];
                        Assert.IsFalse(pub.VerifyHash(sig, Hash.FromBytes(ha.ComputeHash(data))));
                    }
                }
            }
        }
Exemplo n.º 27
0
        private void PublicKeyEncrypt(string input, RSAPublicKey _publicKey, RSAPrivateKey _privateKey)
        {
            byte[] inputData = Encoding.UTF8.GetBytes(input);

            DateTime d1 = DateTime.Now;

            byte[]   inputDateEnc = RSAManaged.Encrypt(inputData, _publicKey);
            TimeSpan t1           = DateTime.Now - d1;

            Console.WriteLine("公钥加密用时:{0}", t1);

            DateTime d2 = DateTime.Now;

            byte[]   inputDataDec = RSAManaged.Decrypt(inputDateEnc, _privateKey);
            TimeSpan t2           = DateTime.Now - d2;

            Console.WriteLine("私钥解密用时:{0}", t2);

            string inputDec = Encoding.UTF8.GetString(inputDataDec, 0, inputDataDec.Length);

            Console.WriteLine(string.Format("私钥解密结果:{0}", inputDec));
            Console.WriteLine();
        }
Exemplo n.º 28
0
    public static RSAPublicKey FromXmlString(string xmlString)
    {
        if (string.IsNullOrEmpty(xmlString))
        {
            return(null);
        }

        try {
            using (XmlReader reader = XmlReader.Create(new StringReader(xmlString))) {
                if (!reader.ReadToFollowing("RSAKeyValue"))
                {
                    return(null);
                }

                if (reader.LocalName != "Modulus" && !reader.ReadToFollowing("Modulus"))
                {
                    return(null);
                }
                string modulus = reader.ReadElementContentAsString();

                if (reader.LocalName != "Exponent" && !reader.ReadToFollowing("Exponent"))
                {
                    return(null);
                }
                string exponent = reader.ReadElementContentAsString();

                RSAPublicKey publicKey = new RSAPublicKey();
                publicKey.Modulus  = Convert.FromBase64String(modulus);
                publicKey.Exponent = Convert.FromBase64String(exponent);

                return(publicKey);
            }
        } catch {
            return(null);
        }
    }
Exemplo n.º 29
0
        public void DidDocumentWellFormedFromWalletTest()
        {
            NetworkInfo   networkInfo    = new NetworkInfo(bech32Hrp: "did:com:", lcdUrl: "");
            String        mnemonicString = "dash ordinary anxiety zone slot rail flavor tortoise guilt divert pet sound ostrich increase resist short ship lift town ice split payment round apology";
            List <String> mnemonic       = new List <String>(mnemonicString.Split(" ", StringSplitOptions.RemoveEmptyEntries));
            Wallet        wallet         = Wallet.derive(mnemonic, networkInfo);

            // Numbers are different from Dart version as BouncyCastle didn't like the Dart ones (namely 125 and 126)
            BigInteger   modulusVerification   = new BigInteger("8377", 10);
            BigInteger   exponentVerification  = new BigInteger("131", 10);
            RSAPublicKey rsaPubKeyVerification = new RSAPublicKey(new RsaKeyParameters(isPrivate: false, modulus: modulusVerification, exponent: exponentVerification));

            DidDocumentPublicKey verificationPubKey = new DidDocumentPublicKey(
                id: $"{wallet.bech32Address}#keys-1",
                type: "RsaVerificationKey2018",
                controller: wallet.bech32Address,
                publicKeyPem: rsaPubKeyVerification.getEncoded()
                );

            // Numbers are different from Dart version as BouncyCastle didn't like the Dart ones (namely 135 and 136)
            BigInteger   modulusSignature   = new BigInteger("8707", 10);
            BigInteger   exponentSignature  = new BigInteger("139", 10);
            RSAPublicKey rsaPubKeySignature = new RSAPublicKey(new RsaKeyParameters(isPrivate: false, modulus: modulusSignature, exponent: exponentSignature), keyType: "RsaSignatureKey2018");

            DidDocumentPublicKey signaturePubKey = new DidDocumentPublicKey(
                id: $"{wallet.bech32Address}#keys-2",
                type: "RsaSignatureKey2018",
                controller: wallet.bech32Address,
                publicKeyPem: rsaPubKeySignature.getEncoded()
                );

            DidDocumentProofSignatureContent proofSignatureContent = new DidDocumentProofSignatureContent(
                context: "https://www.w3.org/ns/did/v1",
                id: wallet.bech32Address,
                publicKeys: new List <DidDocumentPublicKey> {
                verificationPubKey, signaturePubKey
            }
                );


            DidDocumentProof expectedComputedProof = new DidDocumentProof(
                type: "EcdsaSecp256k1VerificationKey2019",
                timestamp: GenericUtils.getTimeStamp(), //*** Here we should have a ISO-8601 time stamp!
                proofPurpose: "authentication",
                controller: wallet.bech32Address,
                verificationMethod: wallet.bech32PublicKey,
                signatureValue: Convert.ToBase64String(
                    SignHelper.signSorted(proofSignatureContent.toJson(), wallet)
                    )
                );

            DidDocument expectedDidDocument = new DidDocument(
                context: "https://www.w3.org/ns/did/v1",
                id: wallet.bech32Address,
                publicKeys: new List <DidDocumentPublicKey> {
                verificationPubKey, signaturePubKey
            },
                proof: expectedComputedProof,
                service: new List <DidDocumentService>()
                );

            // This is only to be sure that timestampp is different
            System.Threading.Thread.Sleep(2000);

            DidDocument didDocument = DidDocumentHelper.fromWallet(wallet, new List <PublicKey> {
                rsaPubKeyVerification, rsaPubKeySignature
            });

            //This is the comparison class
            CompareLogic compareLogic = new CompareLogic();

            // Check it - we use compareNet objects here
            Assert.AreEqual(compareLogic.Compare(didDocument.context, expectedDidDocument.context).AreEqual, true);
            Assert.AreEqual(compareLogic.Compare(didDocument.id, expectedDidDocument.id).AreEqual, true);
            Assert.AreEqual(compareLogic.Compare(didDocument.publicKeys, expectedDidDocument.publicKeys).AreEqual, true);

            Assert.AreEqual(compareLogic.Compare(didDocument.proof.type, expectedDidDocument.proof.type).AreEqual, true);
            Assert.AreEqual(compareLogic.Compare(didDocument.proof.proofPurpose, expectedDidDocument.proof.proofPurpose).AreEqual, true);
            Assert.AreEqual(compareLogic.Compare(didDocument.proof.controller, expectedDidDocument.proof.controller).AreEqual, true);
            Assert.AreEqual(compareLogic.Compare(didDocument.proof.verificationMethod, expectedDidDocument.proof.verificationMethod).AreEqual, true);
            Assert.AreEqual(compareLogic.Compare(didDocument.proof.timestamp, expectedComputedProof.timestamp).AreEqual, false);
            // The difference depends on the "secureRandom" method used at the time of the signature.
            Assert.AreEqual(compareLogic.Compare(didDocument.proof.signatureValue, expectedDidDocument.proof.signatureValue).AreEqual, false);

            Assert.AreEqual(didDocument.proof.signatureValue.Length, expectedDidDocument.proof.signatureValue.Length);
            // WE also verify the json here

            Dictionary <String, Object> expectedDidDocumentJson = expectedDidDocument.toJson();
            Dictionary <String, Object> didDocumentJson         = didDocument.toJson();
            // Assert.AreEqual(compareLogic.Compare(expectedDidDocumentJson, didDocumentJson).AreEqual, true);
            // They cannot be equal because of time stamps
        }
Exemplo n.º 30
0
        private void SendSessionKey(byte[] session_key)
        {
            try {
                //step1 XOR with session_id
                byte[] working_data = new byte[session_key.Length];
                byte[] session_id   = CalcSessionID();
                Array.Copy(session_key, 0, working_data, 0, session_key.Length);
                for (int i = 0; i < session_id.Length; i++)
                {
                    working_data[i] ^= session_id[i];
                }

                //step2 decrypts with RSA
                RSAPublicKey  first_encryption;
                RSAPublicKey  second_encryption;
                SSHServerInfo si = _cInfo._serverinfo;
                int           first_key_bytelen, second_key_bytelen;
                if (si.server_key_bits < si.host_key_bits)
                {
                    first_encryption   = new RSAPublicKey(si.server_key_public_exponent, si.server_key_public_modulus);
                    second_encryption  = new RSAPublicKey(si.host_key_public_exponent, si.host_key_public_modulus);
                    first_key_bytelen  = (si.server_key_bits + 7) / 8;
                    second_key_bytelen = (si.host_key_bits + 7) / 8;
                }
                else
                {
                    first_encryption   = new RSAPublicKey(si.host_key_public_exponent, si.host_key_public_modulus);
                    second_encryption  = new RSAPublicKey(si.server_key_public_exponent, si.server_key_public_modulus);
                    first_key_bytelen  = (si.host_key_bits + 7) / 8;
                    second_key_bytelen = (si.server_key_bits + 7) / 8;
                }

                Rng        rng           = RngManager.GetSecureRng();
                BigInteger first_result  = RSAUtil.PKCS1PadType2(new BigInteger(working_data), first_key_bytelen, rng).modPow(first_encryption.Exponent, first_encryption.Modulus);
                BigInteger second_result = RSAUtil.PKCS1PadType2(first_result, second_key_bytelen, rng).modPow(second_encryption.Exponent, second_encryption.Modulus);

                //output
                SSH1DataWriter writer = new SSH1DataWriter();
                writer.WriteByte((byte)_cInfo._algorithmForTransmittion);
                writer.Write(si.anti_spoofing_cookie);
                writer.WriteBigInteger(second_result);
                writer.WriteInt32(0); //protocol flags

                //send
                TraceTransmissionEvent(PacketType.SSH_CMSG_SESSION_KEY, "sent encrypted session-keys");
                SSH1Packet packet = SSH1Packet.FromPlainPayload(PacketType.SSH_CMSG_SESSION_KEY, writer.ToByteArray());
                packet.WriteTo(_stream);

                _sessionID = session_id;
            }
            catch (Exception e) {
                if (e is IOException)
                {
                    throw (IOException)e;
                }
                else
                {
                    string t = e.StackTrace;
                    throw new SSHException(e.Message); //IOException以外はみなSSHExceptionにしてしまう
                }
            }
        }
        public override void ImportParameters(RSAParameters parameters)
        {
            try
            {
                //Console.WriteLine("enter ImportParameters " + new { parameters.Exponent, parameters.Modulus, parameters.D });

                // http://developer.android.com/reference/java/security/KeyFactory.html

                // X:\jsc.svn\core\ScriptCoreLibJava\java\security\interfaces\RSAPublicKey.cs
                // https://gist.github.com/manzke/1068441
                // http://stackoverflow.com/questions/11410770/java-load-rsa-public-key-from-file

                // https://sites.google.com/a/jsc-solutions.net/backlog/knowledge-base/2014/201408/20140829
                // https://sites.google.com/a/jsc-solutions.net/backlog/knowledge-base/2015/201503/20150323
                // X:\jsc.svn\examples\javascript\Test\TestWebCryptoKeyExport\TestWebCryptoKeyExport\ApplicationWebService.cs
                // tested by ?

                var xKeyFactory = KeyFactory.getInstance("RSA");


                var rsaModulusBytes = parameters.Modulus;

                #region firstByte Modulus
                var firstByte = rsaModulusBytes[0];
                if (firstByte != 0)
                {
                    // http://stackoverflow.com/questions/3970684/rsa-encryption-in-net-decryption-in-java-java-throws-modulus-not-positive
                    // jvm likes a leading 0 ?

                    rsaModulusBytes = new byte[parameters.Modulus.Length + 1];

                    Array.Copy(
                         parameters.Modulus,
                         0,

                         rsaModulusBytes,
                         1,

                         parameters.Modulus.Length
                     );
                }
                #endregion


                // https://msdn.microsoft.com/en-us/library/system.security.cryptography.rsaparameters(v=vs.110).aspx


                //Console.WriteLine("RSACryptoServiceProvider.ImportParameters " + new
                //{
                //    rsaModulusBytes = rsaModulusBytes.Length,
                //    rsaModulusBytes0 = rsaModulusBytes[0],
                //    rsaModulusBytes1 = rsaModulusBytes[1],
                //});


                // https://docs.oracle.com/javase/7/docs/api/java/security/spec/RSAPrivateKeySpec.html

                // http://www.herongyang.com/Cryptography/RSA-BigInteger-Convert-Byte-Sequences-to-Positive-Integers.html
                // https://docs.oracle.com/javase/7/docs/api/java/math/BigInteger.html#BigInteger(int,%20byte[])
                Func<byte[], BigInteger> f = bytes => new BigInteger(1, (sbyte[])(object)bytes);

                var modulus = f(rsaModulusBytes);

                //  http://www.jensign.com/JavaScience/dotnet/RSAdotnet4/
                //  in J#, the java.math.BigInteger constructor expects byte[] data to be in BIG-endian order, consistent with Java api usage

                // Z:\jsc.svn\examples\javascript\crypto\WebServiceAuthorityExperiment\WebServiceAuthorityExperiment\ApplicationWebService.cs
                // https://community.oracle.com/thread/1531315?start=0&tstart=0
                var xRSAPrivateKeySpec = new RSAPrivateCrtKeySpec(
                    modulus: modulus,

                    publicExponent: f(parameters.Exponent),
                    privateExponent: f(parameters.D),

                    primeP: f(parameters.P), // prime1
                    primeQ: f(parameters.Q), // prime2
                    primeExponentP: f(parameters.DP), // exponent1
                    primeExponentQ: f(parameters.DQ), // exponent2
                   crtCoefficient: f(parameters.InverseQ) // coefficient

                );

                var xRSAPublicKeySpec = new RSAPublicKeySpec(
                    modulus: f(rsaModulusBytes),

                    publicExponent: f(parameters.Exponent)
                );

                this.InternalRSAPrivateKey = (RSAPrivateCrtKey)xKeyFactory.generatePrivate(xRSAPrivateKeySpec);
                this.InternalRSAPublicKey = (RSAPublicKey)xKeyFactory.generatePublic(xRSAPublicKeySpec);

                this.InternalParameters = parameters;

                //Console.WriteLine("ImportParameters " + new { this.KeySize });
            }
            catch
            {
                throw;
            }
        }
        // ctor()?
        public __RSACryptoServiceProvider(int dwKeySize, CspParameters parameters)
        {


            // what if ctor is here for import instead of gen?
            // X:\jsc.svn\examples\java\hybrid\JVMCLRRSACryptoServiceProviderExport\JVMCLRRSACryptoServiceProviderExport\Program.cs

            // If this is not a random container we generate, create it eagerly 
            // in the constructor so we can report any errors now.

            //  Environment.GetCompatibilityFlag(CompatibilityFlag.EagerlyGenerateRandomAsymmKeys)
            //    GetKeyPair();


            // We only attempt to generate a random key on desktop runtimes because the CoreCLR
            // RSA surface area is limited to simply verifying signatures.  Since generating a
            // random key to verify signatures will always lead to failure (unless we happend to
            // win the lottery and randomly generate the signing key ...), there is no need
            // to add this functionality to CoreCLR at this point.

            // ? what

            this.dwKeySize = dwKeySize;
            this.parameters = parameters;

            // when would we want to delay key gen?
            // lets gen it early.

            // X:\jsc.svn\examples\javascript\appengine\Test\TestCryptoKeyGenerate\TestCryptoKeyGenerate\ApplicationWebService.cs

            try
            {
                // it works.
                // can we now wrap rsa for all platforms
                // and use it as a generic nuget?

                var sw = Stopwatch.StartNew();
                Console.WriteLine("RSACryptoServiceProvider before generateKeyPair " + new { dwKeySize });

                var keyGen = KeyPairGenerator.getInstance("RSA");

                keyGen.initialize(dwKeySize);

                this.InternalKeyPair = keyGen.generateKeyPair();
                this.InternalRSAPublicKey = (RSAPublicKey)this.InternalKeyPair.getPublic();
                this.InternalRSAPrivateKey = (RSAPrivateCrtKey)this.InternalKeyPair.getPrivate();

                Console.WriteLine("RSACryptoServiceProvider after generateKeyPair " + new { sw.ElapsedMilliseconds });

                //before generateKeyPair { { ElapsedMilliseconds = 2 } }
                //after generateKeyPair { { ElapsedMilliseconds = 1130 } }

            }
            catch
            {
                throw;
            }
        }