public void RsaHelperCreateSymmetricKeyShouldSucceed()
 {
     var directory = TestContext.DeploymentDirectory;
     var helper = new RsaHelper(Path.Combine(directory, "TestCertificate.pfx"), CertificatePassword);
     var keySet = helper.CreateNewAesSymmetricKeyset();
     keySet.Should().NotBeNull("Because encryption failed");
 }
        public void RsaHelperDecryptedStringShouldMatchOriginalValue()
        {
            var directory = TestContext.DeploymentDirectory;
            var helper = new RsaHelper(Path.Combine(directory, "TestCertificate.pfx"), CertificatePassword);
            var result = helper.RsaEncryptString(TestString);

            var decryptedValue = helper.RsaDecryptToString(result);
            decryptedValue.ShouldBeEquivalentTo(TestString, "Because the rsa decryption failed.");
        }
        public void RsaHelperEncryptStringShouldSucceed()
        {
            var directory = TestContext.DeploymentDirectory;
            var helper = new RsaHelper(Path.Combine(directory, "TestCertificate.pfx"), CertificatePassword);
            var result = helper.RsaEncryptString(TestString);

            Assert.IsNotNull(result);
            Assert.IsTrue(result.Length > 0);
        }
Beispiel #4
0
        /// <summary>
        /// 使用服务端公钥初始化<see cref="ClientCryptoDelegatingHandler"/>类的新实例
        /// </summary>
        /// <param name="publicKey">服务端公钥</param>
        /// <param name="hashType">签名哈希类型,必须为MD5或SHA1</param>
        public ClientCryptoDelegatingHandler(string publicKey, string hashType = "MD5")
        {
            publicKey.CheckNotNullOrEmpty("publicKey");
            hashType.CheckNotNullOrEmpty("hashType");
            hashType = hashType.ToUpper();
            hashType.Required(str => hashType == "MD5" || hashType == "SHA1", Resources.Http_Security_RSA_Sign_HashType);
            RsaHelper rsa = new RsaHelper();

            _cryptor         = new CommunicationCryptor(rsa.PrivateKey, publicKey, hashType);
            _clientPublicKey = rsa.PublicKey;
        }
Beispiel #5
0
        /// <summary>
        ///     Rsa加密
        /// </summary>
        private static string RsaSign(string value, string key, Encoding encoding, RsaType type)
        {
            if (string.IsNullOrWhiteSpace(value) || string.IsNullOrWhiteSpace(key))
            {
                return(string.Empty);
            }

            var rsa = new RsaHelper(type, encoding, key);

            return(rsa.Sign(value));
        }
Beispiel #6
0
        /// <summary>
        ///     Rsa验签
        /// </summary>
        private static bool RsaVerify(string value, string publicKey, string sign, Encoding encoding, RsaType type)
        {
            if (string.IsNullOrWhiteSpace(value) || string.IsNullOrWhiteSpace(publicKey) ||
                string.IsNullOrWhiteSpace(sign))
            {
                return(false);
            }

            var rsa = new RsaHelper(type, encoding, publicKey, publicKey);

            return(rsa.Verify(value, sign));
        }
Beispiel #7
0
        public void EncryptWithPrivateKeyTest()
        {
            int data = 1112;

            (string, string)keyTuple = RsaHelper.GetKey();
            string publicKey          = keyTuple.Item1;
            string privateKey         = keyTuple.Item2;
            string encryptWithPublic  = RsaHelper.EncryptWithPrivateKey(data, privateKey);
            int    decryptWithPrivate = RsaHelper.DecryptWithPublicKeyAndDeserialize <int>(encryptWithPublic, publicKey);

            Debug.WriteLine(decryptWithPrivate);
            Assert.IsTrue(decryptWithPrivate == data);
        }
        public void Sign_Test()
        {
            string    source = "admin";
            RsaHelper rsa    = new RsaHelper();

            byte[] sourceBytes = source.ToBytes();
            byte[] signData    = rsa.SignData(sourceBytes);
            rsa.VerifyData(sourceBytes, signData).ShouldBeTrue();

            string signStr = rsa.SignData(source);

            rsa.VerifyData(source, signStr).ShouldBeTrue();
        }
        public void TestRsaEncryptAndDecrypt()
        {
            string _data               = "I am union guy."
            , _dataEncrypted           = ""
            , _dataDecrypted           = "";
            RsaKeyPair   _rsaKeyPair   = new RsaKeyPair();
            RsaKeyFormat _rsaKeyFormat = RsaKeyFormat.PEM;

            _dataEncrypted = RsaHelper.Encrypt(_rsaKeyFormat, _rsaKeyPair.PublicKey_PEM, _data);
            _dataDecrypted = RsaHelper.Decrypt(_rsaKeyFormat, _rsaKeyPair.PrivateKey_PEM, _dataEncrypted);

            Assert.AreEqual(_data, _dataDecrypted, string.Format("Data = {0}, DataEncrypted = {1}, DataDecrypted = {2}", _data, _dataEncrypted, _dataDecrypted));
        }
Beispiel #10
0
 private KeyValuePair <string, object> GetRequester()
 {
     return(new("requester", new
     {
         did = _ownIdCoreConfiguration.DID,
         pubKey = RsaHelper.ExportPublicKeyToPkcsFormattedString(_ownIdCoreConfiguration
                                                                 .JwtSignCredentials),
         name = Localize(_ownIdCoreConfiguration.Name),
         icon = _ownIdCoreConfiguration.Icon,
         description = Localize(_ownIdCoreConfiguration.Description),
         overwriteFields = _ownIdCoreConfiguration.OverwriteFields
     }));
 }
Beispiel #11
0
        public void Test_RsaHelper_Encrypt_Decrypt()
        {
            string s = @"已评估过类似方案,上海和融25版本做过类似改动,但需求有差异。
和融做此需求时改动量比较大,且与252版本跨系列了,参考价值降低。";

            byte[] bb = Encoding.UTF8.GetBytes(s);

            byte[] b1 = RsaHelper.Encrypt(bb, s_certName);
            byte[] b2 = RsaHelper.Decrypt(b1, s_certName);

            string s2 = Encoding.UTF8.GetString(b2);

            Assert.AreEqual(s, s2);
        }
        public void Encrypt_Decrypt_Test()
        {
            string    source = "admin";
            RsaHelper rsa    = new RsaHelper();

            //byte[]
            byte[] sourceBytes = source.ToBytes();
            byte[] enBytes     = rsa.Encrypt(sourceBytes);
            rsa.Decrypt(enBytes).ShouldBe(sourceBytes);

            //string
            string enstr = rsa.Encrypt(source);

            rsa.Decrypt(enstr).ShouldBe(source);
        }
Beispiel #13
0
        private Decrypt GetDecryptResult(string requestData, object Data)
        {
            var       decrypt = Utils.GetDecrypt(requestData);
            RsaHelper rsa     = new RsaHelper(null, Utils.RsaPubKey(decrypt.isdefault));
            var       aesKv   = Utils.AesKV();

            AESHelper aes = new AESHelper($"{aesKv}{aesKv}", aesKv);

            return(new Decrypt
            {
                secret = rsa.Encrypt(aesKv),
                encryption = aes.Encrypt(JsonHelper.Serialize(Data)),
                isdefault = decrypt.isdefault
            });
        }
Beispiel #14
0
        //校验票据(数据库数据匹配)
        private bool ValidateTicket(string userKeyId, string time, string signature)
        {
            if (string.IsNullOrEmpty(userKeyId))
            {
                return(false);
            }
            var user = UserService.GetUserByKeyId(userKeyId);

            if (user == null)
            {
                return(false);
            }
            string result = RsaHelper.computeSignature(userKeyId, time, user.UserAccessKey);

            return(result == signature);
        }
Beispiel #15
0
        public async Task bili_login()
        {
            var login = new Hashtable
            {
                { "sdk_type", 1 },
                { "isRoot", 0 },
                { "sign", "" },
                { "merchant_id", Constant.MerchantId },
                { "dp", "1920*1080" },
                { "uid", 0 },
                { "support_abis", "x86,armeabi-v7a" },
                { "platform_type", 3 },
                { "operators", 2 },
                { "model", "MIX 2" },
                { "udid", "agltXWQCYANmAjIBfQF9" },
                { "net", 4 },
                { "app_id", Constant.AppId },
                { "game_id", Constant.AppId },
                { "timestamp", FgoHelper.get_timestamp_fgo() },
                { "ver", Constant.GameVersion },
                { "c", 0 },
                { "server_id", Constant.ServerId },
                { "version", 1 },
                { "domain_switch_count", 0 },
                { "pf_ver", "8.0.0" },
                { "user_id", UserName },
                { "domain", "p.biligame.com" },
                { "original_domain", "" },
                { "sdk_log_type", 1 },
                { "sdk_ver", "1.6.7.1" },
                { "pwd", RsaHelper.RSAEncrypt(Token + Password, RSAKey) },
                { "channel_id", 1 }
            };

            GetSign(login);

            var jo = JObject.Parse(await Network.HttpPostAsync("http://p.biligame.com/api/client/login", login));

            if (!jo["code"].ToString().Equals("0"))
            {
                throw new Exception("pwd_error");
            }

            uid        = jo["uid"].ToString();
            access_key = jo["access_key"].ToString();
        }
Beispiel #16
0
        static RsaKeyManager()
        {
            logger.InfoFormat("{0:D3}.{1}", ++numberIndex, MethodBase.GetCurrentMethod().Name);

            var webRootDir = HttpRuntime.AppDomainAppPath;
            var appDataDir = Path.Combine(webRootDir, "App_Data");

            if (!Directory.Exists(appDataDir))
            {
                Directory.CreateDirectory(appDataDir);
            }
            string xmlPrivateKey = null, xmlPublicKey = null;
            var    xmlPrivateKeyXmlDocument = new XmlDocument();
            var    xmlPublicKeyXmlDocument  = new XmlDocument();
            var    privateKeyFile           = Path.Combine(appDataDir, "RsaPrivateKey.xml");
            var    publicKeyFile            = Path.Combine(appDataDir, "RsaPublicKey.xml");

            if (File.Exists(privateKeyFile))
            {
                xmlPrivateKeyXmlDocument.Load(privateKeyFile);
                xmlPrivateKey = xmlPrivateKeyXmlDocument.OuterXml;
            }
            if (File.Exists(publicKeyFile))
            {
                xmlPublicKeyXmlDocument.Load(publicKeyFile);
                xmlPublicKey = xmlPublicKeyXmlDocument.OuterXml;
            }
            if (string.IsNullOrEmpty(xmlPrivateKey) || string.IsNullOrEmpty(xmlPublicKey))
            {
                var rsaKeySize     = ConfigurationManager.AppSettings["RsaKeySize"];
                var isParseSuccess = int.TryParse(rsaKeySize, out var result);
                if (isParseSuccess && result > 0)
                {
                    keySize = result;
                }
                RsaHelper.GenerateKey(keySize, out xmlPrivateKey, out xmlPublicKey);
                xmlPrivateKeyXmlDocument.InnerXml = xmlPrivateKey;
                xmlPrivateKeyXmlDocument.Save(privateKeyFile);
                xmlPublicKeyXmlDocument.InnerXml = xmlPublicKey;
                xmlPublicKeyXmlDocument.Save(publicKeyFile);
            }
            XmlPrivateKey = xmlPrivateKey;
            XmlPublicKey  = xmlPublicKey;
            PemPublicKey  = RsaHelper.Xml2Pem(xmlPublicKey);
        }
Beispiel #17
0
        /// <summary>
        /// 初始化一个<see cref="ClientHttpCrypto"/>类型的新实例
        /// </summary>
        public ClientHttpCrypto(IServiceProvider provider)
        {
            _logger = provider.GetLogger(typeof(ClientHttpCrypto));
            OsharpOptions options = provider.GetOSharpOptions();

            if (options.HttpEncrypt?.Enabled == true)
            {
                HttpEncryptOptions httpEncrypt     = options.HttpEncrypt;
                string             clientPublicKey = httpEncrypt.ClientPublicKey;
                if (string.IsNullOrEmpty(clientPublicKey))
                {
                    throw new OsharpException("配置文件中HttpEncrypt节点的ClientPublicKey不能为空");
                }
                RsaHelper rsa = new RsaHelper();
                _encryptor = new TransmissionEncryptor(rsa.PrivateKey, httpEncrypt.ClientPublicKey);
                _publicKey = rsa.PublicKey;
            }
        }
        /// <summary>
        /// 添加 JWT 验证
        /// </summary>
        /// <param name="services"></param>
        /// <returns></returns>
        public static IServiceCollection AddJwt(this IServiceCollection services, out JwtIssuerOptions _tokenOptions)
        {
            _tokenOptions = new JwtIssuerOptions();
            var keyDir = PlatformServices.Default.Application.ApplicationBasePath;

            if (!RsaHelper.TryGetKeyParameters(keyDir, true, out RSAParameters keyParameters))
            {
                keyParameters = RsaHelper.CreateAndSaveKey(keyDir);
            }
            var key = new RsaSecurityKey(keyParameters);

            _tokenOptions.Key                = key;
            _tokenOptions.Issuer             = "qdcares_net";
            _tokenOptions.SigningCredentials = new SigningCredentials(_tokenOptions.Key, SecurityAlgorithms.RsaSha256Signature);

            services.AddSingleton <JwtIssuerOptions>(_tokenOptions);
            return(services);
        }
Beispiel #19
0
        public async Task InvokeAsyncTest()
        {
            HttpContext context = new DefaultHttpContext();

            context.Request.Body = new MemoryStream("test-request".ToBytes());
            RsaHelper rsa = new RsaHelper();

            context.Request.Headers.Add(HttpHeaderNames.ClientPublicKey, rsa.PublicKey);
            context.Response.Body = new MemoryStream();

            var middleware = ActivatorUtilities.CreateInstance <HostHttpCryptoMiddleware>(_provider,
                                                                                          new RequestDelegate(c =>
            {
                c.Response.Body = new MemoryStream("test-response".ToBytes());
                return(Task.CompletedTask);
            }));
            await middleware.InvokeAsync(context);
        }
Beispiel #20
0
        static void Main(string[] args)
        {
            Console.WriteLine("Hello World!");
            var keyList    = RsaKeyGenerator.Pkcs8Key(2048, true);
            var privateKey = keyList[0];
            var publicKey  = keyList[1];
            var str        = "我是原字符串";

            Console.WriteLine($"原字符串:{str}");
            str = RsaHelper.JavaRsaEncrypt(str, publicKey, RsaSignFormat.Hex);
            Console.WriteLine($"Rsa加密符串:{str}");
            str = RsaHelper.JavaRsaDecrypt(str, privateKey, RsaSignFormat.Hex);
            Console.WriteLine($"Rsa解密符串:{str}");
            var sign = RsaHelper.JavaRsaSign(str, privateKey, RsaSignFormat.Hex);

            Console.WriteLine($"Rsa签名:{sign}");
            Console.WriteLine($"Rsa验签:{RsaHelper.JavaRsaSignVerify(str, sign, publicKey, RsaSignFormat.Hex)}");
            Console.Read();
        }
Beispiel #21
0
        /// <summary>
        /// 加密要发送的数据,包含签名,AES加密,RSA加密AES密钥等步骤
        /// </summary>
        /// <param name="data">要加密的正文明文数据</param>
        /// <returns>已加密待发送的密文</returns>
        public string EncryptData(string data)
        {
            data.CheckNotNull("data");

            string separator = GetSeparator();
            //获取正文摘要
            string signData = RsaHelper.SignData(data, _ownPrivateKey);

            data = new[] { data, signData }.ExpandAndToString(separator);
            //使用AES加密 正文+摘要
            AesHelper aes = new AesHelper(true);

            data = aes.Encrypt(data);
            //RSA加密AES密钥
            byte[] keyBytes = aes.Key.ToBytes();
            string enDesKey = Convert.ToBase64String(RsaHelper.Encrypt(keyBytes, _facePublicKey));

            return(new[] { enDesKey, data }.ExpandAndToString(separator));
        }
Beispiel #22
0
        public AjaxResCode RegQQ()
        {
            AjaxResCode res = new AjaxResCode();

            try
            {
                var    qqnumber  = this.QQNumber;
                string qqinfostr = this.ResultStr;

                myinfo my_info = DecryptByModel <myinfo>();
                if (my_info != null && qqnumber > 0)
                {
                    string[] rsa = RsaHelper.GenerateKeys();
                    HwPushCon = new HwPushContext();
                    HwPushCon.Hw_Users.Add(new Hw_Users
                    {
                        QQNumber      = qqnumber,
                        UserName      = my_info.result.nick,
                        PrivateKey    = rsa[0],
                        PublicKey     = rsa[1],
                        PrivateKeyMd5 = rsa[2],
                        PublicKeyMd5  = rsa[3],
                        QQInfo        = qqinfostr
                    });
                    HwPushCon.SaveChanges();

                    res.Data       = rsa[0];
                    res.Message    = "注册成功,生成Key";
                    res.ResultCode = 1;
                }
                else
                {
                    res.Data       = "";
                    res.Message    = "注册失败,无法生成Key";
                    res.ResultCode = 2;
                }
            }
            catch (Exception ee)
            {
                res.Message = ee.Message;
            }
            return(res);
        }
Beispiel #23
0
        static void Main(string[] args)
        {
            string content = "Mr@1234_$%!";
            RSAKey rsaKey  = RsaHelper.CreateRsaKey();

            WriteLine($"PrivateKey:{rsaKey.PrivateKey}");
            WriteLine();
            WriteLine($"PublicKey;{rsaKey.PublicKey}");
            WriteLine();

            WriteLine($"{content} 加密后:");
            string e = RsaHelper.RSAEncrypt(content, rsaKey.PublicKey);

            WriteLine(e);

            WriteLine($"解密后:{RsaHelper.RSADecrypt(e, rsaKey.PrivateKey)}");

            ReadKey();
        }
 /// <summary>
 /// 通过加密密文获取原文
 /// </summary>
 /// <param name="cipper">格式为md5(username){密文}{今天日期}</param>
 /// <param name="username"></param>
 /// <param name="cipperServices">获取密钥</param>
 /// <returns></returns>
 public static string FromCipperToString(this string cipper, string username, ICipperServices cipperServices)
 {
     try
     {
         string md5Str     = username.ToMd5();
         var    rsa        = new RsaHelper(RSAType.RSA2, Encoding.UTF8, cipperServices.PrivateKey, cipperServices.PublicKey);
         var    decryptStr = rsa.Decrypt(cipper);
         if (decryptStr == null || decryptStr.Length <= md5Str.Length ||
             DateTime.Now.ToString("yyyyMMdd") != decryptStr.Substring(0, 8) ||
             decryptStr.Substring(decryptStr.Length - md5Str.Length, md5Str.Length) != md5Str)
         {
             return(null);
         }
         return(decryptStr.Substring(8, decryptStr.Length - 8 - md5Str.Length));
     }
     catch (Exception)
     {
         throw new ActionStatusMessageException(ActionStatusMessage.Account.Auth.Invalid.CipperInvalid);
     }
 }
Beispiel #25
0
        public AuthorizationResultView Authorize(LoginUserCommand loginUserCommand)
        {
            var user = _identityQueryRepository.QueryAuthorizedUser(loginUserCommand.Login, loginUserCommand.Password).FirstOrDefault();

            var invalidCredentialsMessage = "Invalid user credentials";

            if (user == null)
            {
                throw new ValidationException(invalidCredentialsMessage);
            }

            var redirectUrl = GetRedirectUrl(user.Department);
            var secureToken = RsaHelper.CreateSecureToken(user, ConfigurationManager.AppSettings["publicKeyPath"]);

            return(new AuthorizationResultView()
            {
                AuthorizedUser = user,
                RedirectUrl = redirectUrl,
                Token = secureToken
            });
        }
        void SelectPhone(object[] x)
        {
            ComboBox    cmbBox   = x[0] as ComboBox;
            Button      phoneBtn = x[1] as Button;
            PasswordBox Psb      = x[2] as PasswordBox;

            Page     loginPage = x[3] as Page;
            CheckBox isKeepPwd = loginPage.FindName("IsKeepPwd") as CheckBox;

            isKeepPwd.IsChecked = true;

            List <WaterMarkTextBox> TextBox = DependencyObjectHelper.FindVisualChild <WaterMarkTextBox>(cmbBox);
            int index = JObjectHelper.GetStrNum(phoneBtn.Tag.ToString()) - 1;

            //cmbBox.Text = LocalUserInfo[index].Phone;
            TextBox[0].Text       = LocalUserInfo[index].Phone;
            cmbBox.IsDropDownOpen = false;
            string[] SplitStr = LocalUserInfo[index].Pwd.Split('*');
            string   _pwd     = RsaHelper.RSADecrypt(SplitStr[0], SplitStr[1]);

            Psb.Password = _pwd;
        }
Beispiel #27
0
        public void LoadKeys_CorruptedBase64_Exception()
        {
            FluentActions.Invoking(() =>
            {
                using var invalidPublicKey =
                          new StringReader(PublicKeyStartString +
                                           PublicBase64EncodedKey.Substring(1, PublicBase64EncodedKey.Length - 1) +
                                           PublicKeyEndString);
                RsaHelper.LoadKeys(invalidPublicKey);
            }).Should().Throw <FormatException>();

            FluentActions.Invoking(() =>
            {
                using var validPublicKey =
                          new StringReader(PublicKeyStartString + PublicBase64EncodedKey + PublicKeyEndString);
                using var invalidPrivateKey = new StringReader(PrivateKeyStartString +
                                                               PrivateBase64EncodedKey.Substring(1,
                                                                                                 PublicBase64EncodedKey.Length - 1) +
                                                               PrivateKeyEndString);
                RsaHelper.LoadKeys(validPublicKey, invalidPrivateKey);
            }).Should().Throw <FormatException>();
        }
Beispiel #28
0
        public void EncryptWithPublicKeyTest()
        {
            string data = "wjire";

            (string, string)keyTuple = RsaHelper.GetKey();
            string publicKey  = keyTuple.Item1;
            string privateKey = keyTuple.Item2;

            publicKey =
                @"-----BEGIN PUBLIC KEY-----
MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCaEfoLMVNOXb9s3D/dds2Y1rQN
5NA2G7cw8SZCvbwxP9+lJxLGu1F+671cuOTJ6NTVCTnhtGtCrmrws8TDay9bEoSH
D89595LLvHjWj8hqs9YsQem/w/9zfqtiQ1z0mlMAr7cQMA/UeGnHr+n3y1tvEoY8
DyiMYVCDfbWCTyr87QIDAQAB
-----END PUBLIC KEY-----";
            privateKey = @"-----BEGIN RSA PRIVATE KEY-----
MIICXAIBAAKBgQCaEfoLMVNOXb9s3D/dds2Y1rQN5NA2G7cw8SZCvbwxP9+lJxLG
u1F+671cuOTJ6NTVCTnhtGtCrmrws8TDay9bEoSHD89595LLvHjWj8hqs9YsQem/
w/9zfqtiQ1z0mlMAr7cQMA/UeGnHr+n3y1tvEoY8DyiMYVCDfbWCTyr87QIDAQAB
AoGAGVOwhvvUy00d6rH0zbMkmRCyXeup+TsVIjaCKPaHuTuGyDS5dscpiR5iQpvN
AGQF7f9WRIQkHby5AliK6pT0Hle1gAjZrk62h8wGHnYDOH7snOtmBjtrWxQmCpWm
59u4HJglQ3eiD/ko/viho0g0qPALLxzP+2Gku/OiCb26ZQECQQDpE20CImO9iVtd
J/w5wb6P5tC3IK+jc5wOiEr60f8jKow85vaGW7hl1lSxKd5hNZ3TUdqQdN7KPvev
KSQ5wtVDAkEAqTlIOSsEB/0+oeZm2QcWi3sdogjFUg+dqOL+i81tCepI+Rr6DbDj
KAi8twFWRBDhGnseIvgLtr+75KXGxTaqDwJBAOAz4Y5GCm/Oa2anCgd9CZRfUbJ2
7L1sfle0X3v6+VSYnyIOgmIoZK8Bh6KMRfB4pQMcIAUJhy5Bd/y0tLYjZwUCQC6y
jPihozIlMzRwJS98oj8JUWsWaoUzo/kn8sBXhuB2k36ScDB5AKZaiuEhcFHGKqgp
E27o7iqXDF2TVZ+0bwcCQGJlKxUb/n3KzYhyCYDnlN4XEN5vK2yhKVwSUFwsT5T6
DLePxokQLgeswPdmD67TxcSqZWF+VEx7Cq87a4sGtc8=
-----END RSA PRIVATE KEY-----";

            string encryptWithPublic  = RsaHelper.EncryptWithPublicKey(data, publicKey);
            string decryptWithPrivate = RsaHelper.DecryptWithPrivateKey(encryptWithPublic, privateKey);

            Debug.WriteLine(data);
            Debug.WriteLine(decryptWithPrivate);
            Assert.IsTrue(decryptWithPrivate == data);
        }
Beispiel #29
0
        private static void Main(string[] args)
        {
            var rsaHelper = new RsaHelper();
            var keys      = rsaHelper.GenerateRsaKeys();

            Console.WriteLine("测试公钥加密,私钥解密>>>>>>>>>>>>>>>");
            Console.WriteLine("请输入要加密的字符串:");
            var text         = Console.ReadLine();
            var encryptedStr = rsaHelper.EncryptByPublicKey(text, keys.Item1);

            Console.WriteLine("公钥加密后密文是:{0}{1}", encryptedStr, Environment.NewLine);
            var source = rsaHelper.DecryptByPrivateKey(encryptedStr, keys.Item2);

            Console.WriteLine("通过私钥解密后的原文是:{0}", source);

            Console.WriteLine("{0}{1}", Environment.NewLine, Environment.NewLine);

            Console.WriteLine("测试私钥加密,公钥解密>>>>>>>>>>>>>>>");
            Console.WriteLine("请输入要加密的字符串:");
            text         = Console.ReadLine();
            encryptedStr = rsaHelper.EncryptByPrivateKey(text, keys.Item2);
            Console.WriteLine("私钥加密后密文是:{0}{1}", encryptedStr, Environment.NewLine);
            source = rsaHelper.DecryptByPublibKey(encryptedStr, keys.Item1);
            Console.WriteLine("通过公钥解密后的原文是:{0}", source);

            Console.WriteLine("{0}{1}", Environment.NewLine, Environment.NewLine);

            //测试公钥解密指定的ssh RSA
            Console.WriteLine("测试公钥解密(针对SSH生成的RSA密钥)>>>>>>>>>>>>>>>");
            source = @"i0s9lv0QuefmmXWkWxqIwJMcK1/uOjTTIpc0K2YWAwFGuMSbQ651Zfl4i7MY/Qi/vG8+J7SRyb3UWiS5CNP3M3MI2tC6l2CVAGv0godSMaeWbMqj9g17KwJr9r3EYtPvc8lRi8ec3qS8plkoPUCoz3PtsK LZ9hBlAXKD3f8qGDI=";
            var pubKey = @"MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCxtkuwBI6novN6IKoP3AUe7vQnT +3NqYy0SJqGTf4u5sWuKj6jwpvBSf17DoBGAXPVfzQjtl3xNymn/87c7qzDzollBH1dXAdg5olwp0tAUVEWDKuCgaFGjsqnrTYxTvOqTf1J08mIQf3Tngkw1WuNBdADUiBsTlgpO9k+ffIL4wIDAQAB";
            var result = rsaHelper.DecryptByPublicKeyOnly(source, pubKey);

            Console.WriteLine(result);

            Console.ReadKey();
        }
Beispiel #30
0
        public async Task Encrypte()
        {
            if (txtPublicKey.Text == "")
            {
                await GenerateKey();
            }
            byte[] value = await CheckEncrypte(txtSource.Text);

            if (value != null)
            {
                byte[] result    = null;
                string key       = txtPublicKey.Text;
                bool   oaep      = cbbPadding.SelectedIndex == 1;
                int    keyLength = KeyLength;
                await Task.Run(() =>
                               result = RsaHelper.Encrypte(
                                   value,
                                   key,
                                   keyLength,
                                   oaep));

                txtResult.Text = await GetString(result, BinaryOutputMode);
            }
        }
Beispiel #31
0
        public void Test_RsaHelper_Sign_Verify()
        {
            string s = @"
大家好:
为进一步规范ERP发版工作,加强研发质量管控,在2017年初,我们对ERP产品发版管理制度V1.1进行了优化,详细调整点如下:
1、结合公司《ERP产品全生命周期管控策略V4.0》,将孵化期产品和成长&成熟期产品的发版活动进行区分细化
2、新增定义《ERP研发质量标准v1.0》
3、结合公司《产品PMO管理机制v1.0》,修订《产品上市评估表》形成2017年版本
4、针对主项目和子项目协作问题,梳理形成《ERP发版-主项目工作清单v1.0》

经ERP353和云ERP1.0SP3发版前工作的试运行、各事业部核心角色的评审,最终经产品PMO的审核,现正式发布ERP产品发版管理制度V2.0,即日生效!
   
如对本管理制度有任何疑问,欢迎咨询各团队QA";

            byte[] data      = s.GetBytes();
            string signature = RsaHelper.Sign(data, s_certName);
            bool   ok        = RsaHelper.Verify(data, signature, s_publicKey);

            Assert.IsTrue(ok);

            // 随便改一下签名
            string signX = "abc" + signature.Substring(3);

            ok = RsaHelper.Verify(data, signX, s_publicKey);
            Assert.IsFalse(ok);


            // 随便修改下原始输入数据
            string s2 = "abc" + s;

            byte[] data2 = s2.GetBytes();
            string sign2 = RsaHelper.Sign(data2, s_certName);

            // 数据修改了,签名就肯定不一样
            Assert.AreNotEqual(signature, sign2);
        }
        public void RsaHelperBytesShouldSucceed()
        {
            var directory = TestContext.DeploymentDirectory;
            var helper = new RsaHelper(Path.Combine(directory, "TestCertificate.pfx"), CertificatePassword);

            var aes = new AesManaged();
            aes.GenerateIV();
            aes.GenerateKey();

            var originalKey = aes.Key;
            var originalIv = aes.IV;

            var encryptedKeyBytes = helper.RsaEncryptBytes(aes.Key);
            var encryptedIvBytes = helper.RsaEncryptBytes(aes.IV);

            encryptedIvBytes.Should().NotBeNull("IV failed to encrypt");
            encryptedKeyBytes.Should().NotBeNull("Key failed to encrypt");

            var decryptedKeyBytes = helper.RsaDecryptToBytes(encryptedKeyBytes);
            var decryptedIvBytes = helper.RsaDecryptToBytes(encryptedIvBytes);

            originalKey.ShouldBeEquivalentTo(decryptedKeyBytes);
            originalIv.ShouldBeEquivalentTo(decryptedIvBytes);
        }
 public void TestSetup()
 {
     var deploymentDirectory = TestContext.DeploymentDirectory;
     rsaHelper = new RsaHelper(Path.Combine(deploymentDirectory, "TestCertificate.pfx"), "test");
 }
Beispiel #34
0
 private void Main_Load(object sender, EventArgs e)
 {
     var rsas = RsaHelper.GenerateKeys();
 }
Beispiel #35
0
        /// <summary>
        /// Rsa 加密
        /// </summary>
        /// <param name="value">明文</param>
        /// <param name="publicKey">公钥</param>
        /// <param name="type">加密类型</param>
        /// <returns></returns>
        private static string RsaEncrypt(string value, string publicKey, RSAType type)
        {
            var rsa = new RsaHelper(type, Encoding.UTF8, publicKey: publicKey);

            return(rsa.Encrypt(value));
        }