Exemplo n.º 1
0
        /// <summary>
        /// SSH1 RSA challenge
        /// </summary>
        /// <param name="e">public exponent</param>
        /// <param name="n">public modulus</param>
        /// <param name="encryptedChallenge">encrypted challenge</param>
        /// <param name="sessionId">session id</param>
        /// <param name="responseType">response type</param>
        private void SSH1IRSAChallenge(BigInteger e, BigInteger n, BigInteger encryptedChallenge, byte[] sessionId, uint responseType)
        {
            if (responseType != 1)
            {
                SendFailure();
                return;
            }

            SSH1UserAuthKey key = SSH1FindKey(e, n);

            if (key == null)
            {
                SendFailure();
                return;
            }

            BigInteger challenge = key.decryptChallenge(encryptedChallenge);

            byte[] rawchallenge = RSAUtil.StripPKCS1Pad(challenge, 2).GetBytes();
            byte[] hash;
            using (var md5 = new MD5CryptoServiceProvider()) {
                md5.TransformBlock(rawchallenge, 0, rawchallenge.Length, rawchallenge, 0);
                md5.TransformFinalBlock(sessionId, 0, sessionId.Length);
                hash = md5.Hash;
            }

            Send(
                new OpenSSHAgentForwardingMessage(OpenSSHAgentForwardingMessageType.SSH_AGENT_RSA_RESPONSE)
                .Write(hash)
                );
        }
Exemplo n.º 2
0
        public void Try_GetKeyParameters_Test()
        {
            var path = "E:\\";
            var flag = RSAUtil.TryGetKeyParameters(path, true, out RSAParameters keyParameters);

            Assert.AreEqual(flag, true);
        }
Exemplo n.º 3
0
        public static string cerEncrypt(string md5SignStr, string cerPath)
        {
            string signature = RSAUtil.Base64Encoder(RSAUtil.RSAEncrypt(RSAUtil.getPublicKeyXmlFromCer(cerPath).PublicKey.Key.ToXmlString(false),
                                                                        RSAUtil.getBytesFromString(md5SignStr, Encoding.UTF8)));

            return(signature);
        }
Exemplo n.º 4
0
        public static string sign(string encryptStr, string prvPath, string prvPws)
        {
            //string sign = RSAUtil.Base64Encoder(RSAUtil.CreateSignWithPrivateKey(RSAUtil.getBytesFromString(encryptStr, Encoding.UTF8),RSAUtil.getPrivateKeyXmlFromPFX(prvPath, prvPws)));//测试环境
            string sign = RSAUtil.Base64Encoder(RSAUtil.CreateSignWithPrivateKeyBySHA256(RSAUtil.getBytesFromString(encryptStr, Encoding.UTF8), RSAUtil.getPrivateKeyXmlFromPFX(prvPath, prvPws)));//生产环境

            return(sign);
        }
Exemplo n.º 5
0
        public ZZXDictionary getSystemParams <T>(IZZXRequest <T> request) where T : ZZXResponse
        {
            string apiVersion = null;

            if (!string.IsNullOrEmpty(request.GetApiVersion()))
            {
                apiVersion = request.GetApiVersion();
            }
            else
            {
                apiVersion = Version;
            }
            ZZXDictionary sysParams = new ZZXDictionary();

            sysParams.Add(METHOD, request.GetApiName());
            sysParams.Add(VERSION, apiVersion);
            sysParams.Add(ChANNELID, _channelId);
            sysParams.Add(SIGNTYPE, _singType);
            sysParams.Add(PARAMS, request.GetParams());
            var d = sysParams.OrderBy(p => p.Key).ToDictionary(p => p.Key, o => o.Value); //签名需要先排序下 中子星文档要求
            // 添加签名参数
            var build = WebUtils.BuildQuery(d, false, _charset);                          //  这个签名没问题

            sysParams.Add(SIGN, RSAUtil.Sign(WebUtils.BuildQuery(d, false, _charset), _privateKey, _charset));
            return(sysParams);
        }
Exemplo n.º 6
0
        public void GeneratePkcs1KeySuccess()
        {
            var result = RSAUtil.GenerateRSA2KeysWithPKCS1();

            Assert.NotNull(result.Key);
            Assert.NotNull(result.Value);
        }
Exemplo n.º 7
0
        /// <summary>
        /// 功能描述:RUI的参数
        /// </summary>
        /// <param name="parameter">参数</param>
        /// <param name="key">加密字段</param>
        /// <returns></returns>
        public string ProcessingRUI(Dictionary <string, string> parameter, string key)
        {
            RulePayBehavior PayBehavior = new RulePayBehavior();

            //得到异步通知地址
            string async_url = parameter["async_notify_url"].ToString();

            parameter["amount"] = (decimal.Parse(parameter["amount"]) * 100).ToString("F0");

            //删除异步地址和同步地址 进行签名
            parameter.Remove("async_notify_url");
            parameter.Remove("notify_url");
            //得到一个字符串
            string ascdict = PayBehavior.GetParamsStr(parameter);

            //java 私钥转.net xml
            string xmlprivateKey = RSAExtensions.ConvertToXmlPrivateKey(key);

            //私钥加密
            string sign = RSAUtil.PrivateKeyEncrypt(xmlprivateKey, ascdict);

            //添加 同步地址 异步地址 签名

            parameter.Add("notify_url", async_url);
            parameter.Add("async_notify_url", async_url);

            parameter.Add("sign", Utils.UrlEncode(sign));
            string jsontext = PayBehavior.GetParamsStr(parameter);

            //string jsontext = JsonHelper.SerializeObject(parameter);

            return(jsontext);
        }
Exemplo n.º 8
0
        /// <summary>
        /// 功能描述:赤的参数
        /// </summary>
        /// <param name="parameter">参数</param>
        /// <param name="key">加密字段</param>
        /// <returns></returns>
        public string ProcessingXF(Dictionary <string, string> parameter, string key)
        {
            RulePayBehavior PayBehavior = new RulePayBehavior();

            Dictionary <String, string> newpram = new Dictionary <string, string>();



            string ascdict = JsonHelper.SerializeObject(parameter);

            //////java 私钥转.net xml
            string xmlprivateKey = RSAExtensions.RSAPublicKeyJava2DotNet(key);

            //私钥加密
            string sign = RSAUtil.Encrypt(key, Encoding.UTF8.GetBytes(ascdict));

            //添加 同步地址 异步地址 签名

            newpram.Add("merchantNo", "9900000000000111");
            newpram.Add("keyType", "1");
            newpram.Add("agentNo", "10000034");
            newpram.Add("data", sign);


            //string jsontext = PayBehavior.GetParamsStr(newpram);
            string jsontext = JsonHelper.SerializeObject(newpram);

            return(jsontext);
        }
        private async Task <bool> Save()
        {
            var appName     = txtAppName.Text.Trim();
            var appPassword = RSAUtil.Encrypt(txtAppPassword.Text.Trim(), _publicKey);

            using (var db = new SqliteDbContext())
            {
                if (_appPwdId > 0)
                {
                    CurrentSelectAppPwd.AppName    = appName;
                    CurrentSelectAppPwd.Password   = appPassword;
                    CurrentSelectAppPwd.ModifyTime = DateTime.UtcNow;
                    db.AppPasswords.Update(CurrentSelectAppPwd);
                }
                else
                {
                    db.AppPasswords.Add(new AppPassword
                    {
                        AppName    = appName,
                        Password   = appPassword,
                        CreateTime = DateTime.UtcNow,
                        ModifyTime = DateTime.UtcNow
                    });
                }

                return(await db.SaveChangesAsync() > 0);
            }
        }
Exemplo n.º 10
0
        public void genEncryptData(string data, string cerPath, string pfxPath, string password, out string encryptData, out string sign, out string encryptKey)
        {
            encryptData = "";
            encryptKey  = "";
            sign        = "";
            try
            {
                // 加载公私钥
                X509Certificate2 publicKeyInfo  = DataCertificate.GetCertFromCerFile(cerPath);
                X509Certificate2 privateKeyInfo = DataCertificate.GetCertificateFromPfxFile(pfxPath, password);

                string platPublicKey = publicKeyInfo.PublicKey.Key.ToXmlString(false);

                string merchantPublicKey  = privateKeyInfo.PublicKey.Key.ToXmlString(false); // 公钥
                string merchantPrivateKey = privateKeyInfo.PrivateKey.ToXmlString(true);     // 私钥

                //byte[] plainBytes = Encoding.UTF8.GetBytes(data);
                //生成AESKEY
                string aesKey = ComUtils.CreateRandomString(16);
                //报文加密
                encryptData = Base64.EncodeBase64(Encoding.UTF8, AESUtil.Encrypt(data, aesKey));
                //生成签名
                sign = Base64.EncodeBase64(Encoding.UTF8, RSAUtil.RSAEncrypt(merchantPrivateKey, data));
                //AESKEY加密
                encryptKey = Base64.EncodeBase64(Encoding.UTF8, AESUtil.Encrypt(data, platPublicKey));
            }
            catch (Exception e)
            {
                log.Write(e, MsgType.Error);
            }
        }
Exemplo n.º 11
0
        static void generatorsign()
        {
            //用我的私钥和公钥用来测试接口编写

            string privateKey  = Cfg.Get("privateKey");
            string publicKey   = Cfg.Get("publicKey");
            string myPublicKey = Cfg.Get("myPublicKey");
            string charset     = "UTF-8";

            var dic = new Dictionary <string, object>();

            dic["channelId"] = "3";
            dic["method"]    = "loanApplyResultNotify";
            //dic["params"] = new { loanId = "20170915174747000008" };
            var loanapplyresult = new LoanApplyResult()
            {
                LoanId        = "2019125514515",
                Result        = 1,
                Commissions   = 10000,
                Reason        = "没有拒绝",
                LoanAmount    = 1000000,
                LoanTerm      = 12,
                PaymentOption = 1,
                Orders        = new List <ResultOrder>()
                {
                    new ResultOrder()
                    {
                        SourceOrderId = "12345", LoanAmount = 5000
                    },
                    new ResultOrder()
                    {
                        SourceOrderId = "12346", LoanAmount = 5000
                    }
                }
            };

            var loantttttstring = JsonConvert.SerializeObject(loanapplyresult);

            dic["params"]   = loantttttstring;
            dic["signType"] = "RSA2";
            dic["ver"]      = "1.0";
            //dic["statusCode"] = "900";
            //dic["errMsg"] = "签名校验失败";
            var d    = dic.OrderBy(p => p.Key).ToDictionary(p => p.Key, o => o.Value);
            var text = WebUtils.BuildQuery(d, false, charset);

            //要组装成一个对象?
            JObject jb = new JObject();

            foreach (var key in dic.Keys)
            {
                jb.Add(new JProperty(key, dic[key]));
            }

            var tt = JsonConvert.SerializeObject(jb);
            var s  = RSAUtil.Sign(text, privateKey, charset);

            Console.WriteLine($"签名:{s}");
        }
Exemplo n.º 12
0
        public void EncryptAndDecrypt_ShouldSuccess()
        {
            string plainText        = "test";
            var    cipher           = RSAUtil.Encrypt(plainText, _publicKey);
            var    decryptPlainText = RSAUtil.Decrypt(cipher, _privateKey);

            Assert.Equal(plainText, decryptPlainText);
        }
Exemplo n.º 13
0
        public T Execute <T>(IZZXRequest <T> request) where T : ZZXResponse
        {
            if (string.IsNullOrEmpty(_charset))
            {
                _charset = "UTF-8";
            }
            ZZXDictionary sysParams = getSystemParams(request);
            string        body;

            //这里要组装成对象
            JObject jb = new JObject();

            foreach (var key in sysParams.Keys)
            {
                //params 这个要转回问题
                if (key == "params")
                {
                    jb.Add(new JProperty(key, JsonConvert.DeserializeObject(sysParams[key].ToString())));
                }
                else
                {
                    jb.Add(new JProperty(key, sysParams[key]));
                }
            }
            var tt     = JsonConvert.SerializeObject(jb);
            var encode = HttpUtility.UrlEncode(tt);//传递的时候进行url编码

            body = _webUtils.DoPost(_serverUrl, encode, _charset);
            string bizResponse = body;
            T      rsp         = null;

            //再这里转换出来然后验签
            ZZXDictionary dic     = new ZZXDictionary();
            JObject       jObject = JsonConvert.DeserializeObject(bizResponse) as JObject;

            if (jObject != null)
            {
                //去掉 statuscode errmsg  sign 三个键值对 排序组合成待签名字符串
                if (jObject["sign"] != null)
                {
                    var sign = jObject["sign"].ToString();
                    dic.Add("method", jObject["method"].ToString());
                    dic.Add("ver", jObject["ver"].ToString());
                    dic.Add("channelId", jObject["channelId"].ToString());
                    dic.Add("signType", jObject["signType"].ToString());
                    if (jObject["params"] != null)
                    {
                        dic.Add("params", JsonConvert.SerializeObject(jObject["params"]));
                    }
                    var d = dic.OrderBy(p => p.Key).ToDictionary(p => p.Key, o => o.Value);
                    var s = WebUtils.BuildQuery(d, false, _charset);
                    RSAUtil.VerifySign(s, sign, _publicKey, _charset);
                }
            }

            rsp = JsonConvert.DeserializeObject <T>(bizResponse);
            return(rsp);
        }
Exemplo n.º 14
0
        protected virtual HandshakeParam createHandShakeParam(string randomKey)
        {
            HandshakeParam param = new HandshakeParam();
            string         randomKeyEncrypted = RSAUtil.EncryptByPublicKey(randomKey, publicKey);

            param.app_key = this.AppKey;
            param.data    = randomKeyEncrypted;
            return(param);
        }
Exemplo n.º 15
0
        public void SetFactory(string url, string version, long partner, string sign_type = "MD5")
        {
            _partner    = partner;
            _version    = version;
            _privateKey = CacheManager.Instance.LoginUser.PrivateKey;
            _rsa        = RSAUtil.FromPrivateKey(_privateKey);

            this.Url = $"http://{url}/gateway?version={version}&partner={partner}";
        }
Exemplo n.º 16
0
 public void Test2()
 {
     for (int i = 0; i < 100; i++)
     {
         var key = RSAUtil.GetRASKey();
         Assert.IsTrue(Base64Util.IsBase64OrEmpty(key.PublicKey));
         Assert.IsTrue(Base64Util.IsBase64OrEmpty(key.PrivateKey));
     }
 }
Exemplo n.º 17
0
        public void TestRSA()
        {
            String pubKey = @"MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCG/iIZZzb16PxKqslkDMYa4tVFb3IVPBpLj4BgHQmDfe843sG4gkJIPXCm7+t6QxIbfDfynBpqZJLvu0c6E7TqlCtynBIlRFOBZrQVNEFkaanR2Kln3vd3CIidR571UstOC32XDyqAQNlvjD19zeIDVfmLa0Q+Or0zaxY99QwBHwIDAQAB";
            String mi     = @"QU5vDnQ1ukj8GsauokFlgcB/g61U882tj82wHGrrqHEnvaga+4cXjML9RhjpZtKqwDGZTCujsmpynDk4qek6IGOQ/oxdWLwV4ZNjfa/oqA8OFDothVUT8wpqCu9kOYHrTdGybmXD0dB2Iy1/AMQTAgPNNXXiRXdvsz9xWYTV6z8=";

            // 用公钥解密
            string m = RSAUtil.DecryptByPublicKey(mi, pubKey);

            Assert.IsTrue(m == "1234567890123456");
        }
Exemplo n.º 18
0
 private void CreateOrEditAppPassword_Load(object sender, EventArgs e)
 {
     if (_appPwdId > 0)
     {
         using (var db = new SqliteDbContext())
         {
             CurrentSelectAppPwd = db.AppPasswords.FirstOrDefault(p => p.ID == _appPwdId);
             txtAppName.Text     = CurrentSelectAppPwd.AppName;
             txtAppPassword.Text = RSAUtil.Decrypt(CurrentSelectAppPwd.Password, _privateKey);
         }
     }
 }
Exemplo n.º 19
0
        static void signzzxtest()
        {
            string privateKey  = Cfg.Get("privateKey");
            string publicKey   = Cfg.Get("publicKey");
            string myPublicKey = Cfg.Get("myPublicKey");
            string charset     = "UTF-8";

            var dic = new Dictionary <string, object>();

            dic["channelId"] = "3";
            dic["method"]    = "loanApply";
            //dic["params"] = new { loanId = "20170915174747000008" };
            dic["params"]   = JsonConvert.DeserializeObject(JsonConvert.SerializeObject(new { loanId = "20170915174747000008" }));
            dic["signType"] = "RSA2";
            dic["ver"]      = "1.0";
            //dic["statusCode"] = "900";
            //dic["errMsg"] = "签名校验失败";
            //          //var text = "channelId=3&method=loanApply&params=\"{\"loanId\":\"20170915172722000007\"}\"&signType = RSA2 & ver = 1.0";
            var d    = dic.OrderBy(p => p.Key).ToDictionary(p => p.Key, o => o.Value);
            var text = WebUtils.BuildQuery(d, false, charset);

            //要组装成一个对象?
            JObject jb = new JObject();

            foreach (var key in dic.Keys)
            {
                jb.Add(new JProperty(key, dic[key]));
            }

            var tt = JsonConvert.SerializeObject(jb);

            //          var sss = "YtaXroGTrMptqZPQW8/Cz1ZrMGqL8s4V8JBYQr2LHh0j0WC+BP5NSZxVljBxsrBvv9vyH6l8ODX/1mT8AmYbxptbYW7RGJ0Of87CMJFrmTHb9f9nRFs3j7dNUw6PfSRuT1ItqHXAbEoUO8ZSm278yILIkpdTRJO1EjvdFH25ILs=";
            //          //"YtaXroGTrMptqZPQW8/Cz1ZrMGqL8s4V8JBYQr2LHh0j0WC+BP5NSZxVljBxsrBvv9vyH6l8ODX/1mT8AmYbxptbYW7RGJ0Of87CMJFrmTHb9f9nRFs3j7dNUw6PfSRuT1ItqHXAbEoUO8ZSm278yILIkpdTRJO1EjvdFH25ILs="
            //             //oOzbzpanqMkEqib40YcnDaw7eb296ORiEE37Ysz/XpJVeJtvqAsZ5yIseXFMsXRjJZ1yCyknuspZ5qoglIDhHkgPn/S2UBnR1f/JuyCHifxW7tJgu1CpbFdHZ7BFHwGmxb97Jx0pOYKaVKW14bTZgnLKepBStT4SjhFeX7LUPoE=
            ////var s = RSAUtil.Encrypt(text, privateKey, charset);

            //var text = "channelId=3&method=loanApply&params={\"loanId\":\"20170918151253000014\"}&signType=RSA2&ver=1.0";
            var sss = "YtaXroGTrMptqZPQW8/Cz1ZrMGqL8s4V8JBYQr2LHh0j0WC+BP5NSZxVljBxsrBvv9vyH6l8ODX/1mT8AmYbxptbYW7RGJ0Of87CMJFrmTHb9f9nRFs3j7dNUw6PfSRuT1ItqHXAbEoUO8ZSm278yILIkpdTRJO1EjvdFH25ILs=";
            //"oOzbzpanqMkEqib40YcnDaw7eb296ORiEE37Ysz/XpJVeJtvqAsZ5yIseXFMsXRjJZ1yCyknuspZ5qoglIDhHkgPn/S2UBnR1f/JuyCHifxW7tJgu1CpbFdHZ7BFHwGmxb97Jx0pOYKaVKW14bTZgnLKepBStT4SjhFeX7LUPoE="
            var t = RSAUtil.Verify(text, sss, publicKey, charset);

            Console.WriteLine($"对方验签:{t}");


            var res = "{\"statusCode\":200,\"errMsg\":\"success\",\"method\":\"loanApply\",\"ver\":\"1.0\",\"channelId\":\"3\",\"signType\":\"RSA2\",\"sign\":\"LzQ7rhhoCcn3in6J0kArQak+J0zBzFOEtiDaLNAMDpctdQYK9aEUNUlhK5hZJ9ExP+miq1AXr9EMNya1aZxibPh/MdKYnr9vaNHQk7hpUbycE9bxP1cdrFB9VgLOLQyAf8HF0njTGSK/ozCxzqrhqtT1Y+9WcQbRs7h+yLyfoFA=\",\"params\":{\"loanId\":\"20170918144652000012\"}}";

            var des_dic = JsonConvert.DeserializeObject <IDictionary <string, object> >(res);

            Console.WriteLine(des_dic);
        }
Exemplo n.º 20
0
        /// <summary>
        /// 注册
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public LoginResponse Signup(LoginRequest model)
        {
            AssertUtil.CheckIsNullOrEmpty <SpException>(model.code, "账号不能为空", "");
            AssertUtil.CheckIsNullOrEmpty <SpException>(model.password, "密码不能为空", "");

            return(Broker.ExecuteTransaction(() =>
            {
                if (!model.code.Contains("@"))
                {
                    return new LoginResponse(false, "注册失败,请使用邮箱作为账号");
                }

                var vertification = new MailVertificationService(Broker).GetDataByMailAdress(model.code);
                if (vertification != null)
                {
                    return new LoginResponse(false, "激活邮件已发送,请前往邮件激活账号,请勿重复注册", LoginMesageLevel.Warning);
                }

                var id = Guid.NewGuid().ToString();
                model.password = RSAUtil.Decrypt(model.password, model.publicKey);
                var data = new mail_vertification()
                {
                    Id = id,
                    name = "账号激活邮件",
                    content = $@"你好,<br/><br/>
请在两小时内点击该<a href=""{ SystemConfig.Config.Protocol }://{SystemConfig.Config.Domain}/api/MailVertification/ActivateUser?id={id}"">链接</a>激活,失效请重新登录注册
",
                    expire_time = DateTime.Now.AddHours(2),
                    is_active = false,
                    login_request = JsonConvert.SerializeObject(model),
                    mail_address = model.code,
                    mail_type = MailType.Activation.ToString()
                };
                Broker.Create(data);

                // 返回登录结果、用户信息、用户验证票据信息
                return new LoginResponse()
                {
                    result = false,
                    message = $"已向{data.mail_address}发送激活邮件,请在两个小时内激活",
                    level = LoginMesageLevel.Warning.ToString()
                };
            }));
        }
Exemplo n.º 21
0
        //RSA authentication
        private void DoRSAChallengeResponse()
        {
            //read key
            SSH1UserAuthKey key = new SSH1UserAuthKey(_param.IdentityFile, _param.Password);
            SSH1DataWriter  w   = new SSH1DataWriter();

            w.WriteBigInteger(key.PublicModulus);
            SSH1Packet p = SSH1Packet.FromPlainPayload(PacketType.SSH_CMSG_AUTH_RSA, w.ToByteArray());

            p.WriteTo(_stream, _tCipher);
            TraceTransmissionEvent(PacketType.SSH_CMSG_AUTH_RSA, "RSA challenge-reponse");

            DataFragment   response = ReceivePacket();
            SSH1DataReader reader   = new SSH1DataReader(response);
            PacketType     pt       = reader.ReadPacketType();

            if (pt == PacketType.SSH_SMSG_FAILURE)
            {
                throw new SSHException(Strings.GetString("ServerRefusedRSA"));
            }
            else if (pt != PacketType.SSH_SMSG_AUTH_RSA_CHALLENGE)
            {
                throw new SSHException(String.Format(Strings.GetString("UnexpectedResponse"), pt));
            }
            TraceReceptionEvent(PacketType.SSH_SMSG_AUTH_RSA_CHALLENGE, "received challenge");

            //creating challenge
            BigInteger challenge = key.decryptChallenge(reader.ReadMPInt());

            byte[] rawchallenge = RSAUtil.StripPKCS1Pad(challenge, 2).getBytes();

            //building response
            MemoryStream bos = new MemoryStream();

            bos.Write(rawchallenge, 0, rawchallenge.Length); //!!mindtermでは頭が0かどうかで変なハンドリングがあった
            bos.Write(_sessionID, 0, _sessionID.Length);
            byte[] reply = new MD5CryptoServiceProvider().ComputeHash(bos.ToArray());

            w = new SSH1DataWriter();
            w.Write(reply);
            p = SSH1Packet.FromPlainPayload(PacketType.SSH_CMSG_AUTH_RSA_RESPONSE, w.ToByteArray());
            p.WriteTo(_stream, _tCipher);
            TraceReceptionEvent(PacketType.SSH_CMSG_AUTH_RSA_RESPONSE, "received response");
        }
Exemplo n.º 22
0
        public void Test1()
        {
            var key = RSAUtil.GetRASKey();

            Console.WriteLine(key.PublicKey);
            Console.WriteLine(key.PrivateKey);
            string text = Guid.NewGuid().ToString();

            Assert.AreEqual(text, RSAUtil.DecryptString(RSAUtil.EncryptString(text, key.PrivateKey), key.PublicKey));
            text = new string(Enumerable.Repeat('a', 40).ToArray());
            Assert.AreEqual(40, text.Length);
            Assert.AreEqual(text, RSAUtil.DecryptString(RSAUtil.EncryptString(text, key.PrivateKey), key.PublicKey));
            text = new string(Enumerable.Repeat('a', 20).ToArray());
            Assert.AreEqual(20, text.Length);
            Assert.AreEqual(text, RSAUtil.DecryptString(RSAUtil.EncryptString(text, key.PrivateKey), key.PublicKey));
            text = new string(Enumerable.Repeat('啊', 20).ToArray());
            Assert.AreEqual(20, text.Length);
            Assert.AreEqual(text, RSAUtil.DecryptString(RSAUtil.EncryptString(text, key.PrivateKey), key.PublicKey));
        }
Exemplo n.º 23
0
        public void TestRSA()
        {
            string data = "hello";

            RSAUtil.GetKeyPairXMLText(out string publicKey, out string privateKey);

            // 加解密
            string encryptedText = RSAUtil.EncryptByXMLKey(data, publicKey);
            string result        = RSAUtil.DecryptByXMLKey(encryptedText, privateKey);

            Assert.AreEqual(data, result);

            // 签名验证
            string signature = RSAUtil.SignWithXML(data, privateKey);

            Console.WriteLine(signature);
            bool isValidSignature = RSAUtil.VerifyWithXML(data, signature, publicKey);

            Assert.IsTrue(isValidSignature);
        }
Exemplo n.º 24
0
        public static string GetTokenStr(Token token)
        {
            //
            using (MemoryStream ms = new MemoryStream())
            {
                using (BinaryWriter bw = new BinaryWriter(ms))
                {
                    //
                    bw.Write(token.UserID);
                    bw.Write(token.ExpireTime.Ticks);

                    byte[] data     = ms.ToArray();
                    byte[] signData = RSAUtil.SignData(data);

                    bw.Write(signData);

                    return(Convert.ToBase64String(ms.ToArray()));
                }
            }
        }
Exemplo n.º 25
0
        public void RSABenchmarkTest()
        {
            int           n        = 1000;
            List <string> messages = new List <string>();

            for (int i = 0; i < n; i++)
            {
                messages.Add(Guid.NewGuid().ToString());
            }
            var key = RSAUtil.GetRASKey();

            NTStopwatch.Start();
            foreach (var message in messages)
            {
                RSAUtil.EncryptString(message, key.PrivateKey);
            }
            var elapsedMilliseconds = NTStopwatch.Stop();

            Console.WriteLine(elapsedMilliseconds);
        }
Exemplo n.º 26
0
        protected virtual void checkHandshakeResponse(string resp, string randomKey)
        {
            StringResponse result = JsonUtil.ParseObject <StringResponse>(resp);

            if (!result.IsSuccess())
            {
                throw new SystemException(result.msg);
            }

            string data   = result.data;
            string desStr = RSAUtil.DecryptByPublicKey(data, publicKey);

            string content = AESUtil.DecryptFromBase64String(desStr, randomKey);
            // 一致
            bool same = MD5Util.Encrypt(randomKey) == content;

            if (!same)
            {
                throw new SystemException("传输错误");
            }
        }
        public static void GetLoginToken()
        {
            string publicKeyJson = PostPublicKey();

            log.Debug($"大华获取公钥返回:{publicKeyJson}");
            var    loginPublicKey = JsonConvert.DeserializeObject <LoginPublicKey>(publicKeyJson);
            string publickey      = RSAUtil.RSAPublicKeyJava2DotNet(loginPublicKey.publicKey);

            //string publickey1 = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCmNBfRAvR3Eq5TlC8dp43LgNoyoRb6aMCSlLzlEM5ZJFtwLfiAi3wzPD3QXut0OazKnOLwNXfkWsIMMGsvpKR6C75HNUt8Rskd8d108pzCZv0p0sDLvIhVF1jjD4CPvfaA89o3W1DbDDfBevXBKn2lm27oKatySaFHq7CFZPnvGQIDAQAB";
            //string publickey = RSAUtil.RSAPublicKeyJava2DotNet(publickey1);

            string sign          = RSAUtil.RSAEncryptMore(publickey, "qazwsx123");
            string LoginUserJson = PostLogin(sign);

            log.Debug($"大华用户登录返回:{LoginUserJson}");

            //string dd = "{\"success\":\"true\",\"loginName\":\"system\",\"errMsg\":null,\"token\":\"4540963af0c057e6f4389a90019cb4a2\",\"id\":\"1\",\"cmsIp\":\"192.168.1.108\",\"cmsPort\":\"9000\",\"orgCode\":\"001\",\"publicKey\":\"MIICdgIBADANBgkqhkiG9w0BAQEFAASCAmAwggJcAgEAAoGBAJdvuhK0glofNSE+nvTZe4gL+v7ceM5zy91tk+NeDQM90l7HgW2z+5fvCwRww7EzAidR1ZSBhrciOs2SkxyPwfvBaaDaZpuu998AikrBjVl0S2GuDEOWP0Sh7BBrhlgnLB0xCTHV4bIrYVur6DRCwZgKTRV3ksq9yLPQHQAzdxqxAgMBAAECgYAf0FD+7P0VgcjfmxA50Barlhi8wgR/GsSRWBvhgDirnak8UB1Ytp78ZDOkUyxJZbXmHMMJ18w9XOuNlGVjcrAFpiStl/UN+ZjqpoEaEqqwb1EC1zMt84UDmKL1y0eUx7tNzvB/9eixCbKLrm+F5F0T0OAesZRZwiVgBhc+TSiLgQJBAP+ZQwBe4mUiZ2KzwNITylzvboM8Ny/kodgyxXE/FTMlmlNfZY3mYuuKY2AQs2ZJq3ec1LBiDuGQB29fq72oJkUCQQCXrJjRzLVMFfIyqvGxgYioXT+fBhkRXLweid7eXK43HEZIWVgi7j00w/qCX622Ly6B9ImiZG/gZwsRUf+9Ou99AkEAsEN2BCxq/gmSuGtzvqvtMtffI1uER1/pCJpCtM0nBoWY/oPcGdZWQ07FJzt9LD4DpFIgDp8g2gakSfb1Da6G7QJAPp5qZUufme8BlDuRF1jEQ8ZjytKorMtdezough0/a89HkP0Z7ynuqQc0OHkp7apjCBIedKYErl+8aQUykTxwvQJAU0POSC295Q8lBbtKX80TQmXtHuZLmVfO7O8fBUCI2oIMenxecrz9B4cNv2oOsSiUV2X7/9xXXYLan26wxEu0QQ\u003d\u003d\"}";
            var loginToken = JsonConvert.DeserializeObject <LoginPublicKey>(LoginUserJson);

            _token = loginToken.token;
        }
Exemplo n.º 28
0
        public void TestRSAWithPEM()
        {
            /**
             * RSA加密测试,RSA中的密钥对通过SSL工具生成,生成命令如下
             * 1 生成RSA私钥
             * > openssl genrsa -out rsa_private_key.pem 1024
             * 2.生成RSA公钥
             * > openssl rsa -in rsa_private_key.pem -pubout -out rsa_public_key.pem
             * 3. 将RSA私钥转换成PKCS8格式
             * > openssl pkcs8 -topk8 -inform PEM -in rsa_private_key.pem -outform PEM -nocrypt -out rsa_pub_pk8.pem
             */

            // rsa_pub_pk8.pem内容
            string privateKey = File.ReadAllText("PEM/rsa_pub_pk8.pem")
                                .Replace("-----BEGIN PRIVATE KEY-----", "")
                                .Replace("-----END PRIVATE KEY-----", "")
                                .Replace("\n", "");
            // rsa_public_key.pem内容
            string publicKey = File.ReadAllText("PEM/rsa_public_key.pem")
                               .Replace("-----BEGIN PUBLIC KEY-----", "")
                               .Replace("-----END PUBLIC KEY-----", "")
                               .Replace("\n", "");
            string plainText = "hello, world!";

            // 加解密
            string encryptedData = RSAUtil.EncryptWithPEM(plainText, publicKey);

            Console.WriteLine(encryptedData);
            string result = RSAUtil.DecryptWithPEM(encryptedData, privateKey);

            Assert.AreEqual(result, plainText);

            // 签名验签
            string signature = RSAUtil.SignWithPEM(plainText, privateKey);

            Console.WriteLine(signature);
            bool isValidSignature = RSAUtil.VerifyWithPEM(plainText, signature, publicKey);

            Assert.AreEqual(true, isValidSignature);
        }
Exemplo n.º 29
0
        //RSA authentication
        private void DoRSAChallengeResponse()
        {
            //read key
            SSH1UserAuthKey key = new SSH1UserAuthKey(_param.IdentityFile, _param.Password);
            SSH1DataWriter  w   = new SSH1DataWriter();

            w.Write(key.PublicModulus);
            SSH1Packet p = SSH1Packet.FromPlainPayload(PacketType.SSH_CMSG_AUTH_RSA, w.ToByteArray());

            p.WriteTo(_stream, _tCipher);

            p = ReceivePacket();
            if (p.Type == PacketType.SSH_SMSG_FAILURE)
            {
                throw new Exception(Strings.GetString("ServerRefusedRSA"));
            }
            else if (p.Type != PacketType.SSH_SMSG_AUTH_RSA_CHALLENGE)
            {
                throw new Exception(String.Format(Strings.GetString("UnexpectedResponse"), p.Type));
            }

            //creating challenge
            SSH1DataReader r         = new SSH1DataReader(p.Data);
            BigInteger     challenge = key.decryptChallenge(r.ReadMPInt());

            byte[] rawchallenge = RSAUtil.StripPKCS1Pad(challenge, 2).getBytes();

            //building response
            MemoryStream bos = new MemoryStream();

            bos.Write(rawchallenge, 0, rawchallenge.Length);             //!!mindtermでは頭が0かどうかで変なハンドリングがあった
            bos.Write(_sessionID, 0, _sessionID.Length);
            byte[] response = HashAlgorithmProvider.OpenAlgorithm(HashAlgorithmNames.Md5).HashData(bos.ToArray().AsBuffer()).ToArray();;

            w = new SSH1DataWriter();
            w.Write(response);
            p = SSH1Packet.FromPlainPayload(PacketType.SSH_CMSG_AUTH_RSA_RESPONSE, w.ToByteArray());
            p.WriteTo(_stream, _tCipher);
        }
Exemplo n.º 30
0
        static void signtest()
        {
            string privateKey  = Cfg.Get("privateKey");
            string publicKey   = Cfg.Get("publicKey");
            string myPublicKey = Cfg.Get("myPublicKey");
            string charset     = "UTF-8";
            var    text        = "123";
            var    sss         = "qGv4v16jabQaVrfVwLGUup31xtuSoufwP77d0nsLV5jfGs7N12143gT0yf8ek1SQv1dtaZlliSxgyaga/Z3tUWAdaUGA8BBsBHYc1OLTzKFGHyMY1QLiokUe5xJ/lbZFuyr3L6uhGTCGqWbni/yinNEA7KEjhJVGuRXxv06s=";
            //var s = RSAUtil.Encrypt(text, privateKey, charset);

            var s = RSAUtil.Sign(text, privateKey, charset);

            Console.WriteLine($"签名:{s}");

            //用我的公钥来验下这个签

            var tt = RSAUtil.Verify(text, s, myPublicKey, charset);

            Console.WriteLine($"验签:{tt}");

            var t = RSAUtil.Verify(text, sss, publicKey, charset);

            Console.WriteLine($"对方验签:{t}");
        }