public static string DecryptToBase64(string private_key_xml, string raw, bool fOAEP) { RSAHelper rsa = new RSAHelper(); rsa.SetPrivateKey(private_key_xml); return(rsa.Decrypt(raw, fOAEP)); }
public void RSA_PEM_EncryptWithDecrypt() { string data = "hello word!";//"MD5", //data = "1234567890123456"; //data = "abcdefghildjfdfj"; //data = ".,keikdiodjkdfoj"; //data = " "; //data = "string decryptResult = RSAHelper.DecryptPEM(privateKeyPEM, encryptResult)"; string encryptResult = RSAHelper.EncryptPEM(publicKeyPEM, data); string decryptResult = RSAHelper.DecryptPEM(privateKeyPEM, encryptResult); Debug.Print(encryptResult); Debug.Print(decryptResult); Assert.IsTrue(data == decryptResult); //if(encryptResult.Length!=172) //{ // int a = 0; // int b = 0 / a; //} //if (data != decryptResult) //{ // int a = 0; // int b = 0 / a; //} }
/// <summary>编码密码,在传输中保护安全,一般使用RSA加密</summary> /// <param name="username"></param> /// <param name="password"></param> /// <returns></returns> protected virtual String EncodePassword(String username, String password) { if (password.IsNullOrEmpty()) { return(password); } var key = SecurityKey; if (!key.IsNullOrEmpty()) { var name = ""; var p = key.IndexOf('$'); if (p >= 0) { name = key.Substring(0, p); key = key.Substring(p + 1); } // RSA公钥加密 var pass = RSAHelper.Encrypt(password.GetBytes(), key).ToBase64(); password = $"$rsa${name}${pass}"; } return(password); }
public string GetToken(CurrentUserModel userModel) { //string jtiCustom = Guid.NewGuid().ToString();//用来标识 Token var claims = new[] { new Claim(ClaimTypes.Name, userModel.Name), new Claim("EMail", userModel.EMail), new Claim("Account", userModel.Account), new Claim("Age", userModel.Age.ToString()), new Claim("Id", userModel.Id.ToString()), new Claim("Mobile", userModel.Mobile), new Claim(ClaimTypes.Role, userModel.Role), //new Claim("Role", userModel.Role),//这个不能角色授权 new Claim("Sex", userModel.Sex.ToString()) //各种信息拼装 }; string keyDir = Directory.GetCurrentDirectory(); if (RSAHelper.TryGetKeyParameters(keyDir, true, out RSAParameters keyParams) == false) { keyParams = RSAHelper.GenerateAndSaveKey(keyDir); } var credentials = new SigningCredentials(new RsaSecurityKey(keyParams), SecurityAlgorithms.RsaSha256Signature); var token = new JwtSecurityToken( issuer: this._JWTTokenOptions.Issuer, audience: this._JWTTokenOptions.Audience, claims: claims, expires: DateTime.Now.AddMinutes(60),//5分钟有效期 signingCredentials: credentials); var handler = new JwtSecurityTokenHandler(); string tokenString = handler.WriteToken(token); return(tokenString); }
public JsonResult GetOTP(string number) { ArrayList arrUserDetails = new ArrayList(); try { Random generator = new Random(); string OTP = generator.Next(0, 999999).ToString("D6"); var rsa = new RSAHelper(RSAType.RSA2, Encoding.UTF8, privateKey, publicKey); string Message = smsUrl + smsKey + "&senderid=" + senderId + "&route=" + route + "&number=" + number + "&message=" + message + OTP; bool isOTPSent = SendMessage.SendSMS(OTP, Message); //bool isOTPSent = true; if (isOTPSent == true) { arrUserDetails.Add(rsa.Encrypt(OTP)); } else { arrUserDetails.Add("SMS Not Sent"); } } catch (Exception ex) { objExceptionLoggingToSQL.LogAppException(ex.StackTrace); arrUserDetails.Add("ERROR"); } return(Json(arrUserDetails)); }
/// <summary> /// 加密 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void btnS_Click(object sender, EventArgs e) { string sk = txtSK.Text.Trim(); string str = txtContext.Text.Trim(); txtSed.Text = RSAHelper.EncryptString(str, sk); }
public void RSAHelper_Encrypt_By_Public_Decrypt_Success() { string input = "Hello, this is Shawn, I am learning about RSA by using BigInteger class"; var bytes = Encoding.UTF8.GetBytes(input); var resultBytes = RSAHelper.Encrypt(bytes, _rsaPublic); string result = Convert.ToBase64String(resultBytes); Debug.WriteLine("Encrypt by public key: "); Debug.WriteLine(result); EncDec ed = new EncDec(); string encryptedByED = ed.RSAEncrypt(_rsaPublicXml, input); Debug.WriteLine("WARNNING: Encrypt result are {0} equal between RSAHelper and EncDec class.", encryptedByED == result ? "" : " NOT ", ""); byte[] decryptBytes = RSAHelper.Decrypt(Convert.FromBase64String(result), _rsaPrivate); string resultDecrypted = Encoding.UTF8.GetString(decryptBytes, 0, decryptBytes.Length); Debug.WriteLine("Decrypt by public key: "); Debug.WriteLine(resultDecrypted); string resultED = ed.RSADecrypt(_rsaPrivateXml, encryptedByED); Assert.AreEqual(input, resultDecrypted); Assert.AreEqual(input, resultED); }
public void NHibernateTest() { //string filename = @"C:\Users\matt.shirilla\Documents\Visual Studio 2015\Projects\SIQ_Install_Report\ConsoleApplication1\resources\hibernate.cfg.xml"; //TODO Developer hack to get a hibernate file. Update for your test environment string filename = @"C:\Users\matt.shirilla\Documents\Visual Studio 2015\Projects\SIQ_Install_Report_5.0\ConsoleApplication1\resources\hibernate.cfg.xml"; Configuration config = new Configuration().Configure(filename); string connectionString = null; // Get the connection string from the NHibernate.config.xml connectionString = config.GetProperty(global::NHibernate.Cfg.Environment.ConnectionString); connectionString = connectionString.Replace("\r\n", "").Trim(); string[] splittedConnectionString = connectionString.Split(';'); connectionString = string.Empty; // Split the connection string and go over the it's properties foreach (string property in splittedConnectionString) { if (property.StartsWith("password", StringComparison.CurrentCultureIgnoreCase)) { string ttt = property.Replace("Password="******""); byte[] pkcs7ToDecrypt = System.Convert.FromBase64String(ttt); string result = RSAHelper.decryptStringPKCS7(pkcs7ToDecrypt); } } }
/// <summary> /// 微博密码加密 /// </summary> /// <param name="data"></param> /// <param name="password"></param> /// <returns></returns> private static string EncryptPassword(PreLoginResponseData data, string password) { RSAHelper rsa = new RSAHelper(); rsa.RSASetPublic(data.pubkey, "10001"); return(rsa.RSAEncrypt(data.servertime + "\t" + data.nonce + "\n" + password)); }
/// <summary>密码式,验证账号密码,并返回令牌</summary> /// <param name="username">账号</param> /// <param name="password">密码</param> /// <returns></returns> public async Task <TokenInfo> GetToken(String username, String password) { var client = GetClient(); var key = SecurityKey; if (!key.IsNullOrEmpty()) { var name = ""; var p = key.IndexOf('$'); if (p >= 0) { name = key.Substring(0, p); key = key.Substring(p + 1); } // RSA公钥加密 var pass = RSAHelper.Encrypt(password.GetBytes(), key).ToBase64(); password = $"$rsa${name}${pass}"; } return(await client.GetAsync <TokenInfo>("sso/token", new { grant_type = "password", client_id = AppId, client_secret = Secret, username, password })); }
public void LoadOrCreateConfig() { FileInfo config = new FileInfo(configFileName); if (config.Exists) { ReadConfig(); } else { Config = new ClientConfig(); RSAHelper tempRSA = new RSAHelper(); Config.RSAkeys = tempRSA.KeysXml; Config.MyID = Guid.NewGuid(); Config.MyPublicKey = tempRSA.MyPublicKey; Peer self = new Peer() { PeerID = Config.MyID, ChannelID = Guid.NewGuid(), PeerPublicKey = tempRSA.MyPublicKey }; Config.Peers = new List <Peer>(); Config.Peers.Add(self); WriteConfig(); } }
public async Task <bool> RestPasswordWithOldAsync(string connectId, string userName, string old, string @new) { var privateKey = await GetPrivateKeyAsync(connectId); if (privateKey is null) { return(false); } var pwdOld = RSAHelper.RSADecrypt(privateKey, old); if (string.IsNullOrEmpty(pwdOld)) { return(false); } var pwdNew = RSAHelper.RSADecrypt(privateKey, @new); if (string.IsNullOrEmpty(pwdNew)) { return(false); } var user = new AnfUser { UserName = userName }; var ok = await userManager.ChangePasswordAsync(user, pwdOld, pwdNew); return(ok.Succeeded); }
public async Task <string> LoginAsync(string connectId, string userName, string passwordHash) { var privateKey = await GetPrivateKeyAsync(connectId); if (privateKey is null) { return(null); } var val = RSAHelper.RSADecrypt(privateKey, passwordHash); if (string.IsNullOrEmpty(val)) { return(null); } var u = await userManager.FindByNameAsync(userName); var ok = await userManager.CheckPasswordAsync(u, val); if (ok) { var key = RedisKeyGenerator.Concat(RSAKey, connectId); await database.KeyDeleteAsync(key); var identity = new UserSnapshot { Email = u.Email, Id = u.Id, Name = u.NormalizedUserName }; var tk = await userIdentityService.SetIdentityAsync(identity); return(tk); } return(null); }
public static string EncryptToBase64(string public_key_xml, string raw, bool fOAEP) { RSAHelper rsa = new RSAHelper(); rsa.SetPublicKey(public_key_xml); return(rsa.Encrypt(raw, fOAEP)); }
internal void Decrypt_Data <ED>(ref ED encrytedData, ref SafeData safeData) where ED : IRequest { string desDecrypted = string.Empty; using (RSAHelper rsa = new RSAHelper(RSAType.RSA2, Encoding.UTF8, Globals.key_private, Globals.key_public)) { desDecrypted = rsa.Decrypt(safeData.Des); } using (RSAHelper rsa_partner = new RSAHelper(RSAType.RSA2, Encoding.UTF8, Globals.key_private, apiUser.PublicKey)) { if (rsa_partner.Verify(desDecrypted, safeData.Signature) == false) { throw new ApiException(CodeStatus.Signature_Not_Valid); } } using (DESParameters desParameters = JsonConvert.DeserializeObject <DESParameters>(desDecrypted)) { TripleDESHelper des = new TripleDESHelper(desParameters); string message = des.Decrypt(safeData.Data); encrytedData = JsonConvert.DeserializeObject <ED>(message); request.User_ID = apiUser.User_ID; encrytedData.SetBase(request); } chainLogger.Step(Tool.GetCurrentMethod()); Access_Authorization(); Save_Request(); }
private void btnCreateKeys_Click(object sender, EventArgs e) { StartTimer(true); //FillDdl(); // look for the selcted menu item var keySize = getKeySize(); //keySize = 512; if (keySize == 0) { StopTimer(true); MessageBox.Show("Please, selected a key size!"); return; } // conver the menu item key size (512, 1024, ....) and generate a key pair // attention! you can not use a different private key to decrypt an encrypted data // if you realize, we are saving the pair (public and private keys) //lblKeySizeValue.Text = keySize.ToString(); _rsa = new RSAHelper(keySize); txtPublicKey.Text = _rsa.PublicKey(); txtPrivateKey.Text = _rsa.PrivateKey(); StopTimer(true); }
internal SafeData Encrypt_Data <DD>(DD decryted_data) where DD : class { TripleDESHelper des = new TripleDESHelper(); using (RSAHelper rsa_partner = new RSAHelper(RSAType.RSA2, Encoding.UTF8, Globals.key_private, apiUser.PublicKey)) { response = JsonConvert.SerializeObject(decryted_data); #if DEBUG Console.Out.WriteLine(response); #endif string encryptedStr = des.Encrypt(response); string desPrms = des.GetParameters(); string desEncrypted = rsa_partner.Encrypt(desPrms); string signStr = rsa_partner.Sign(desPrms); bool signVerify = false; using (RSAHelper rsa = new RSAHelper(RSAType.RSA2, Encoding.UTF8, Globals.key_private, Globals.key_public)) { signVerify = rsa.Verify(desPrms, signStr); } using (SafeData sd = new SafeData()) { sd.Data = encryptedStr; sd.Signature = signStr; sd.Des = desEncrypted; chainLogger.Step(Tool.GetCurrentMethod()); return(sd); } } }
public static void ParseLisence() { string fileName = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "lisence"); if (File.Exists(fileName) == false) { IsLisenceFileExist = false; return; } IsLisenceFileExist = true; string resutl = ""; using (var fs = new FileStream(fileName, FileMode.Open)) { byte[] data = new byte[fs.Length]; fs.Read(data, 0, data.Length); resutl = Encoding.UTF8.GetString(data); } string json = RSAHelper.PublicKeyDecrypt(xmlPublicKey, resutl); object objLicense = JsonConvert.DeserializeObject(json); JObject jobj = objLicense as JObject; Type = jobj["Type"].ToString(); MachineNumber = jobj["MachineNumber"].ToString(); ExpiredDate = jobj["ExpiredDate"].ToString(); CreationDate = jobj["CreationDate"].ToString(); }
static public int GetPublicKey(IntPtr l) { try { #if DEBUG var method = System.Reflection.MethodBase.GetCurrentMethod(); string methodName = GetMethodName(method); #if UNITY_5_5_OR_NEWER UnityEngine.Profiling.Profiler.BeginSample(methodName); #else Profiler.BeginSample(methodName); #endif #endif RSAHelper self = (RSAHelper)checkSelf(l); var ret = self.GetPublicKey(); pushValue(l, true); pushValue(l, ret); return(2); } catch (Exception e) { return(error(l, e)); } #if DEBUG finally { #if UNITY_5_5_OR_NEWER UnityEngine.Profiling.Profiler.EndSample(); #else Profiler.EndSample(); #endif } #endif }
public override void OnAuthorization(AuthorizationContext filterContext) { HttpRequestBase Request = filterContext.RequestContext.HttpContext.Request; NameValueCollection parameters = new NameValueCollection() { Request.Form, Request.QueryString }; string sign = parameters["sign"]; parameters.Remove("sign"); List <string> paramlist = new List <string>(); foreach (var item in parameters.AllKeys.OrderBy(k => k)) { paramlist.Add(item + "=" + HttpUtility.UrlDecode(parameters[item])); } string presignstr = string.Join("&", paramlist); string digest = RSAHelper.DecryptString(sign, ConfigurationManager.AppSettings[PrivateKey]); if (Sha1.Compute(presignstr) != digest) { ContentResult result = new ContentResult(); result.Content = "Sign Error."; filterContext.Result = result; } }
public static HttpResponseMessage GetResponse(dynamic request, IHeaderDictionary headers, HttpMethod httpMethod, PathString path) { ApiSafeData CriptoSafeData = new ApiSafeData() { Data = TripleDESHelper.Encrypt(JsonSerializer.Serialize(request), out string desParameters), Des = RSAHelper.Encrypt(desParameters, Env.RfiPublicKey), Signature = RSAHelper.Sign(desParameters, Env.PartnerPrivateKey) }; if (String.IsNullOrEmpty(Env.CertificateFilePath)) { using (var clientHandler = new HttpClientHandler() { ServerCertificateCustomValidationCallback = (sender, cert, chain, sslPolicyErrors) => { return(true); } }) { return(Resend(headers, httpMethod, clientHandler, CriptoSafeData, path)); } } else { using (var clientHandler = new HttpClientHandler { ClientCertificateOptions = ClientCertificateOption.Manual, SslProtocols = SslProtocols.Tls12, ClientCertificates = { new X509Certificate2(Env.CertificateFilePath) } }) { return(Resend(headers, httpMethod, clientHandler, CriptoSafeData, path)); } } }
public void TestPrivatePem() { var key = @"-----BEGIN RSA PRIVATE KEY----- MIICXQIBAAKBgQDpsDr+W45aFHIkvotZaGK/THlFFpuZfUtghhWkHAm3H7yvL42J 4xHrTr6IeUDCl4eKe6qiIgvYSNoL3u4SERGOeYmV1F+cocu9IMGnNoicbh1zVW6e 8/iGT3xaYQizJoVuWA/TC/zdds2ihCJfHDBDsouOCXecPapyWCGQNsH5sQIDAQAB AoGBAM/JbFs4y5WbMncrmjpQj+UrOXVOCeLrvrc/4kQ+zgCvTpWywbaGWiuRo+cz cXrVQ6bGGU362e9hr8f4XFViKemDL4SmJbgSDa1K71i+/LnnzF6sjiDBFQ/jA9SK 4PYrY7a3IkeBQnJmknanykugyQ1xmCjbuh556fOeRPaHnhx1AkEA/flrxJSy1Z+n Y1RPgDOeDqyG6MhwU1Jl0yJ1sw3Or4qGRXhjTeGsCrKqV0/ajqdkDEM7FNkqnmsB +vPd116J6wJBAOuNY3oOWvy2fQ32mj6XV+S2vcG1osEUaEuWvEgkGqJ9co6100Qp j15036AQEEDqbjdqS0ShfeRSwevTJZIap9MCQCeMGDDjKrnDA5CfB0YiQ4FrchJ7 a6o90WdAHW3FP6LsAh59MZFmC6Ea0xWHdLPz8stKCMAlVNKYPRWztZ6ctQMCQQC8 iWbeAy+ApvBhhMjg4HJRdpNbwO6MbLEuD3CUrZFEDfTrlU2MeVdv20xC6ZiY3Qtq /4FPZZNGdZcSEuc3km5RAkApGkZmWetNwDJMcUJbSBrQMFfrQObqMPBPe+gEniQq Ttwu1OULHlmUg9eW31wRI2uiXcFCJMHuro6iOQ1VJ4Qs -----END RSA PRIVATE KEY-----"; var p = RSAHelper.ReadPem(key); var rsa = new RSACryptoServiceProvider(); rsa.ImportParameters(p); var pubKey = rsa.ToXmlString(true); Assert.Equal("<RSAKeyValue><Modulus>6bA6/luOWhRyJL6LWWhiv0x5RRabmX1LYIYVpBwJtx+8ry+NieMR606+iHlAwpeHinuqoiIL2EjaC97uEhERjnmJldRfnKHLvSDBpzaInG4dc1VunvP4hk98WmEIsyaFblgP0wv83XbNooQiXxwwQ7KLjgl3nD2qclghkDbB+bE=</Modulus><Exponent>AQAB</Exponent><P>/flrxJSy1Z+nY1RPgDOeDqyG6MhwU1Jl0yJ1sw3Or4qGRXhjTeGsCrKqV0/ajqdkDEM7FNkqnmsB+vPd116J6w==</P><Q>641jeg5a/LZ9DfaaPpdX5La9wbWiwRRoS5a8SCQaon1yjrXTRCmPXnTfoBAQQOpuN2pLRKF95FLB69Mlkhqn0w==</Q><DP>J4wYMOMqucMDkJ8HRiJDgWtyEntrqj3RZ0AdbcU/ouwCHn0xkWYLoRrTFYd0s/Pyy0oIwCVU0pg9FbO1npy1Aw==</DP><DQ>vIlm3gMvgKbwYYTI4OByUXaTW8DujGyxLg9wlK2RRA3065VNjHlXb9tMQumYmN0Lav+BT2WTRnWXEhLnN5JuUQ==</DQ><InverseQ>KRpGZlnrTcAyTHFCW0ga0DBX60Dm6jDwT3voBJ4kKk7cLtTlCx5ZlIPXlt9cESNrol3BQiTB7q6OojkNVSeELA==</InverseQ><D>z8lsWzjLlZsydyuaOlCP5Ss5dU4J4uu+tz/iRD7OAK9OlbLBtoZaK5Gj5zNxetVDpsYZTfrZ72Gvx/hcVWIp6YMvhKYluBINrUrvWL78uefMXqyOIMEVD+MD1Irg9itjtrciR4FCcmaSdqfKS6DJDXGYKNu6Hnnp855E9oeeHHU=</D></RSAKeyValue>", pubKey); var sign = rsa.SignData("NewLife".GetBytes(), MD5.Create()); Assert.Equal("WfMouV+yZ0EmATNiFVsgMIsMzx1sS7zSKcOZ1FmSiUnkq7nB4wEKcketdakn859/pTWZ31l8XF1+GelhdNHjwjuQmsawdTW+imnn5Z1J+XzhNgxdnpJ6O1txcE8oHKCTd2bS2Yv55Mezu4Ih9BbX0JovSnFCsGMxLS6afYQqXUU=", sign.ToBase64()); }
private string modifyPwd(ParamModifyPlayerPwd p) { RSAHelper rsa = new RSAHelper(); rsa.init(); Dictionary <string, object> data = new Dictionary <string, object>(); data["n1"] = p.m_playerAcc; string old = Tool.getMD5Hash(p.m_oldPwd); data["n2"] = AESHelper.AESEncrypt(old, AES_KEY); string newPwd = Tool.getMD5Hash(p.m_newPwd); data["n3"] = AESHelper.AESEncrypt(newPwd, AES_KEY); string jsonstr = JsonHelper.ConvertToStr(data); string md5 = AESHelper.MD5Encrypt(jsonstr + AES_KEY); string urlstr = Convert.ToBase64String(Encoding.Default.GetBytes(jsonstr)); string fmt = CONST.URL_MODIFY_PLAYER_PWD; string aspx = string.Format(fmt, urlstr, md5); var ret = HttpPost.Get(new Uri(aspx)); if (ret != null) { string retStr = Encoding.UTF8.GetString(ret); return(retStr); } return(""); }
//对注册密钥文件进行解密 public static bool DecryptRegKey(string file) { try { string regMsg = EncryptHelper.FileDecrypt(file); string[] regList = regMsg.Split(new String[] { getCpu }, StringSplitOptions.RemoveEmptyEntries); string mNum = RSAHelper.DecryptString(regList[0]); if (mNum == getMNum()) { Com = RSAHelper.DecryptString(regList[1]); Usr = RSAHelper.DecryptString(regList[2]); return(true); } else { MessageBox.Show("注册密钥机器码不正确!"); return(false); } } catch (Exception ex) { MessageBox.Show("解析注册密钥文件失败!\n" + ex.Message); return(false); } }
public ActionResult VerifyOTP(string OTP, string HashCode, string OrderedItems, string username, string userPhone, string userEmail, string address, string restaurant) { ArrayList arrStatus = new ArrayList(); var rsa = new RSAHelper(RSAType.RSA2, Encoding.UTF8, privateKey, publicKey); Enduser VerifyOTP = new Enduser { OTP = rsa.Decrypt(HashCode) }; if (VerifyOTP.OTP == OTP) { // Insertion to tables and generation of order id code will go here.. var OrderId = CreateNewOrder(OrderedItems, username, userPhone, userEmail, address, 1, "", restaurant);// delivery mode is 1(COD) and paymentID is blank if (OrderId != Guid.Empty) { return(Json(OrderId)); } else { return(Json("00000000-0000-0000-0000-000000000000")); } } else { return(Json("Error")); } }
/// <summary> /// Begins the handshake process on the specified <see cref="Socket"/> /// </summary> /// <param name="decryptor">This will be set to a <see cref="EncryptionProvider"/> that has been initialized with the negotiated (local) decryption key</param> /// <param name="encryptor">This will be set to a <see cref="EncryptionProvider"/> that has been initialized with the negotiated (remote) encryption key</param> /// <param name="privRSA">The <see cref="RSAHelper"/> to use to securely negotiate encryption / decryption keys</param> /// <param name="netStream">The already opened <see cref="NetworkStream"/> to use while shaking hands</param> /// <param name="s">The socket to handshake on</param> /// <param name="readLock">The object used to lock read access to the stream to one thread</param> /// <param name="writeLock">The object used to lock write access to the stream to one thread</param> /// <returns></returns> public bool Handshake(Stream netStream, Socket s, RSAHelper privRSA, out EncryptionProvider encryptor, out EncryptionProvider decryptor, ref object readLock, ref object writeLock) { RSAHelper pubRSA; encryptor = null; decryptor = null; try { lock (readLock) { lock (writeLock) { this.ownerComponent.LogInformation("[{0}] -> [{1}]: Exchanging RSA Public Keys", s.LocalEndPoint, s.RemoteEndPoint); ExchangePubKey(netStream, privRSA, out pubRSA); this.ownerComponent.LogInformation("[{0}] -> [{1}]: Negotiating Session Keys", s.LocalEndPoint, s.RemoteEndPoint); NegotiateSessionKeys(netStream, out decryptor, out encryptor, pubRSA, privRSA); this.ownerComponent.LogInformation("[{0}] -> [{1}]: Verifying Connection...", s.LocalEndPoint, s.RemoteEndPoint); bool succes = VerifySessionKeys(netStream, encryptor, decryptor); this.ownerComponent.LogInformation("[{0}] -> [{1}]: {2}", s.LocalEndPoint, s.RemoteEndPoint, succes ? "Success" : "Error"); return(succes); } } } catch (Exception e) { this.ownerComponent.LogException(e, System.Reflection.MethodBase.GetCurrentMethod()); return(false); } }
public void BouncyCastleSignVerify() { publicKeyJava = @"MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAiRpgGZSOYKG36k6f56D0bHHOQZubt344qgRAVrSmw0udQCV8YsN/qpjlVAeT3gpQ1kKf7YvuR3KylXu0/ckvwya7AYsfEGiRahZcH6uElfyLKcR/6PioMvNLDB2mxgfvZXRRqfxOss8Byb6SP1/xSHPwcJQUc/u5wiczEEWKwNyVRTkjKSIKp5iA+bjN9WGdscdBkNYxZTbbKwDJvzyouiniKR5kSa/6LUMmVDlqz1ZgGfj0WK+6He1o/QoR9s7o143+JjNEzLaLkaolyOBWiBaSYYcQzpdlbi4OOvpHVpVrZ00aJDo9Q2/Dui7orKoKRcCqVDizJd80n47Tf6uVEQIDAQAB"; privateKeyJava = @"MIIEvAIBADANBgkqhkiG9w0BAQEFAASCBKYwggSiAgEAAoIBAQCJGmAZlI5gobfqTp/noPRscc5Bm5u3fjiqBEBWtKbDS51AJXxiw3+qmOVUB5PeClDWQp/ti+5HcrKVe7T9yS/DJrsBix8QaJFqFlwfq4SV/IspxH/o+Kgy80sMHabGB+9ldFGp/E6yzwHJvpI/X/FIc/BwlBRz+7nCJzMQRYrA3JVFOSMpIgqnmID5uM31YZ2xx0GQ1jFlNtsrAMm/PKi6KeIpHmRJr/otQyZUOWrPVmAZ+PRYr7od7Wj9ChH2zujXjf4mM0TMtouRqiXI4FaIFpJhhxDOl2VuLg46+kdWlWtnTRokOj1Db8O6LuisqgpFwKpUOLMl3zSfjtN/q5URAgMBAAECggEAaLkfzIo/kqoUPEHgPGIiMS9gt5Zvg+JC0AK9Tj1g3+3C6Ht5nkrsGlf9W4kKNmE0y+RKGn12/VYr+KhsYCmrdOoBj7U/fh4RbLI1ne86MAKeHcI9XauJdpmFqnR/reXjw1/s/OV/C2+5Uutg9E2JlKkScDt7v/f4NMgSZgxoZtU0waPYj5ubhJfbvlWAGol6u0TRlklcfpuhlJAtD4WgAEQm0XmGEVkS3/eKO9vywexkM7YGV2IXqQgvdCVuCl0YGpW4v4qvVixC1b5KU+jgvcFUdHnIFfrEhtVw+byfj4sUfRFk9TCj3HwSsQNa0PnhZINKftnKJGQsP1bC43UgwQKBgQDb4wyA6UPlhR4C2jTn3RE3C87Pl6h8oYAgHzRBLvuDJctKZ3sB4AW+AJhd5Wgdhl6sr0TKPUP+UQicQhD2W8DEPT8Obo3FnCASxBIdJqyDXFL9fQ/g6WrTJ1Dojx1uAPfxWJQJsf6Fev//LbJxukQ1N2pFk/FZljYNtbWkZZqo6QKBgQCfnsBVlW27/ZL98MmlXLnIeDPqj2QtE2jAfyAP0GfaCq94QEyWYavPG9W+jPf114yebwYe4T9MUgVzLZKRFwHBKyBjKz2GgjQgC4s3v18XP/v3lS68E0mYfgiSIJ3X6CMf//RR00XX4fdBmvFxPjv85upgV5WK299gkiDkDvFx6QKBgFwBTtQJxq0c3AfZgdWavH9J44kdLhSoBtJp/BViMT8Y600Aq4mHUR/FY/u157Ci7q5Wz/PHWtHo2i93vV032xrBfcbuH0gWIZ14iRPFgN2eHeOPFrvHLzmW89W7PFcw9I35wEemQJdddgwx9L59b9jMjRz74DraDVgDNjPJh8MxAoGARyrczkvFlV/FvfsxrMze+Ia/fwFXxNE2jz0e6m4dH5ZMDe19OD9r/veGIWNw2ue0Bp+xturu8fRQAb577ry3R40W76BD2kkLPI5pD/3/Q7p/eS/Gmoxu79Kht6VbOvyBTK8uG517MnnJaDLRG5CH5oZ+UV47iqHlwoTkrUoMVKECgYB1MUZZfGFG0fP03O1zwUddUq7Z/y1MLA3fs+vDFTeM3WKGYy7C1e8/vPtNmyaD/UYBpS6FxKVBNx4+mItbJzlHE42eNR5qX0GXwWJfyBTs3DCW9NIAiOT+0dXRma2leS8mPsKzidbtnKVj+tFW2+0cPqWRgzTVAgd1Srm86S/92w=="; var algorithms = GetAlgorithms(); string data = "helo world!"; //int bbc = 0; foreach (var item in algorithms.Keys) { if (!item.ToString().Contains("RSA")) { continue; } if (item.ToString() == "SHA-512WITHRSA/PSS") { //注意SHA-512WITHRSA/PSS 对应的公私钥大小,不满足需求会报错的 key is too small } string signResult = RSAHelper.RSASignJavaBouncyCastle(data, privateKeyJava, item.ToString()); bool result = RSAHelper.VerifyJavaBouncyCastle(data, publicKeyJava, signResult, item.ToString()); Debug.Print(signResult); Assert.IsTrue(result); //if (!result) //{ // int a = 0; // int b = 0 / a; //} } }
private void btnBuildRSAStr_Click(object sender, EventArgs e) { var _key = RSAHelper.GetRASKey(); txtPublicString.Text = _key.PublicKey; txtPrivateString.Text = _key.PrivateKey; }
/// <summary> /// 生成用户的公钥,返回加密UserId的加密串 /// </summary> /// <param name="uid"></param> /// <param name="userType"></param> /// <returns></returns> public string CreatePublicKey(int uid, AuthUserType userType) { var encryptStr = Execute(db => { var authKey = db.AuthKeys.FirstOrDefault(u => u.UserId == uid && u.UserType == (int)userType); if (authKey != null) { return(RSAHelper.EncryptString(uid.ToString(), authKey.PublicKey)); } var keyPair = RSAHelper.GetRASKey(); authKey = new AuthKeys { UserId = uid, PublicKey = keyPair.PublicKey, PrivateKey = keyPair.PrivateKey, UserType = (int)userType, CreateTime = DateTime.Now }; db.AuthKeys.Add(authKey); db.SaveChanges(); return(RSAHelper.EncryptString(uid.ToString(), authKey.PublicKey)); }); CreateCache <AuthKeys>(); return(encryptStr); }
public OutputModel Post([FromBody] InputModel input) { OutputModel response = new OutputModel(); string inputData = RSAHelper.Decrypt(WebConfig.PrivateKey, input.Params); PointModel userPoint = JsonConvert.DeserializeObject <PointModel>(inputData); // 参数错误 if (userPoint == null) { response.Result = "params invalid"; response.Code = 403; return(response); } // 验证码 cache丢失 object currentX = CacheHelper.GetCache(userPoint.Token); if (currentX == null) { response.Result = "Cache lost"; response.Code = 404; return(response); } if (userPoint.x <= (int)currentX + 1 && userPoint.x >= (int)currentX - 1) { response.Code = 200; response.Result = "success"; } return(response); }