/// <summary> /// 用私钥解密经加密后的Base64字符串 /// </summary> /// <param name="base64Source"></param> /// <param name="privateKey"></param> /// <returns></returns> public static string Decrypt(string base64Source, string privateKey) { var bs = Convert.FromBase64String(base64Source); var rsa = new Rsa(privateKey); var rst = rsa.Decrypt(bs); return Encoding.UTF8.GetString(rst); }
private void HandleClientKeyExchange(byte[] message) { var decryptedMessage = _rsa.Decrypt(message); var clientKeyExchange = _serializer.Deserialize <ClientKeyExchange>(decryptedMessage); var session = _sessionCache.Get(clientKeyExchange.SessionId); if (session == null) { // TODO: Send error } else { session.MasterSecret = TLS12.GetMasterSecret(clientKeyExchange.PreMasterSecret, session.ClientRandom, session.ServerRandom); var keys = TLS12.GetKeys(session.MasterSecret, session.ClientRandom, session.ServerRandom); session.ClientWriteMACKey = TLS12.GetClientWriteMACKey(keys); session.ServerWriteMACKey = TLS12.GetServerWriteMACKey(keys); session.ClientWriteKey = TLS12.GetClientWriteKey(keys); session.ServerWriteKey = TLS12.GetServerWriteKey(keys); session.IsAuthenticated = true; } var serverFinished = new ServerFinished { SessionId = session.Id }; var response = new SecurityLayerMessage { Type = SecurityMessageType.ServerFinished, Data = _serializer.Serialize <ServerFinished>(serverFinished) }; var responseBytes = _serializer.Serialize <SecurityLayerMessage>(response); Send(responseBytes); }
public void RSA_Encrypt_Decrypt_Test() { var keyPair = Rsa.CreateKeyPair(RSAKeySizes.Size1024); var testData = "Test Test Hello"; var encrypted = Rsa.Encrypt(keyPair.PublicKey, testData); var decrypted = Encoding.UTF8.GetString(Rsa.Decrypt(keyPair.PrivateKey, encrypted)); Assert.AreEqual(testData, decrypted); }
private void btnDecDecryption_Click(object sender, EventArgs e) { if (string.IsNullOrEmpty(txtDecModulus.Text) || string.IsNullOrEmpty(txtDecExponent.Text)) { MessageBox.Show("Yêu cầu nhập đủ các thông số đầu vào.", "Thiếu thông số đầu vào", MessageBoxButtons.OK, MessageBoxIcon.Warning); return; } try { RsaKey privateKey = new RsaKey { Modulus = Convert.ToInt64(txtDecModulus.Text), Exponent = Convert.ToInt64(txtDecExponent.Text) }; if (cckFileDecryption.Checked) { ofdFileEncryption.FileName = "Encrypt"; if (ofdFileEncryption.ShowDialog() == DialogResult.OK) { var input = readFileToBytes(ofdFileEncryption.FileName); var output = Rsa.Decrypt(input, privateKey); var fileExtention = Path.GetExtension(ofdFileEncryption.FileName); switch (fileExtention) { case ".txt": sfdSaveFile.Filter = "Text document (*.txt)|*.txt "; sfdSaveFile.FileName = "Decrypt.txt"; break; case ".doc": sfdSaveFile.Filter = "Word document (*.doc)|*.doc "; sfdSaveFile.FileName = "Decrypt.doc"; break; } if (sfdSaveFile.ShowDialog() == DialogResult.OK) { File.WriteAllBytes(sfdSaveFile.FileName, output); } } } else { if (string.IsNullOrEmpty(txtDecCipherText.Text)) { MessageBox.Show("Bạn chưa nhập thông điệp cần giải mã hóa.", "Thiếu thông số đầu vào", MessageBoxButtons.OK, MessageBoxIcon.Warning); return; } txtDecMessage.Text = Rsa.Decrypt(txtDecCipherText.Text, privateKey); } } catch (Exception ex) { MessageBox.Show(ex.Message, "Lỗi trong quá trình xử lý." + ex.Message, MessageBoxButtons.OK, MessageBoxIcon.Error); } }
public bool RsaDecrypt() { if (_length - _position < 128) { return(false); } Rsa.Decrypt(ref _buffer, _position); return(GetByte() == 0); }
public void SetEncryptedSessionKey(byte[] encryptedKey) { var key = _rsa.Decrypt(encryptedKey); if (key.Length != 32) { throw new Exception("Key's length isn't 256 bit"); } MemoryCache.Default.Add(_requestHelper.GetClientIp(), key, DateTime.Now.AddMinutes(5)); }
public void RsaDecrypt(bool useCipKeys = true, bool useRsa2 = false) { if (!useRsa2) { Rsa.Decrypt(ref _buffer, _position, _length, useCipKeys); } else { Rsa2.Decrypt(ref _buffer, _position, _length); } }
private void HandleRsaPacket(byte[] data) { var rsaData = new byte[data.Length - 4]; Buffer.BlockCopy(data, 4, rsaData, 0, data.Length - 4); var streamKey = Rsa.Decrypt(rsaData).ThrowIfNull(ErrorCodes.WTFErrorMedicalAttentionSuggested); _rc4 = new Rc4(streamKey); RsaKeyReceived(); }
public void CanEncryptAndDecryptAstring() { var rsaKeysMock = new Mock <IRsaKeys>(); rsaKeysMock.Setup(r => r.PublicKey).Returns(_publicKey); rsaKeysMock.Setup(r => r.PrivateKey).Returns(_privateKey); string toEncrypt = "yngve"; Rsa rsa = new Rsa(new HardCodedRsaKeys()); var encrypted = rsa.Encrypt(toEncrypt); Assert.That(rsa.Decrypt(encrypted), Is.EqualTo(toEncrypt)); }
public ActionResult Login(string user, string pwd, bool rm) { user = Rsa.Decrypt(base.Session["key"].ToString(), user); pwd = Rsa.Decrypt(base.Session["key"].ToString(), pwd); pwd = Md5.GetMd5String(pwd); DbUser user2 = base.helper.CreateWhere <DbUser>().Where(q => q.Enable).Where(q => q.UserName == user).Where(q => q.PassWord == pwd).FirstOrDefault(); if (user2 == null) { return(base.Error("用户名或密码错误!")); } base.Session["user"] = user2; return(base.Success()); }
void HandleDataReceived(IAsyncResult ar) { var sock = ar.AsyncState as Socket; try { int bytesRead = sock.EndReceive(ar); if (bytesRead > 0) { m_BufferReceivedSize += bytesRead; if (m_BufferReceivedSize == m_Buffer.Length) { //解Aes Key IV byte[] bytes; if (!Rsa.Decrypt(m_RsaKey, m_Buffer, out bytes)) { LogHelper.Error("Rsa Decrypt Error {0}", m_RsaKey); sock.Close(); return; } if (!AesKeyIV.Check(bytes)) { LogHelper.Error("Aes Key IV len error {0}", bytes.Length); sock.Close(); } else { var kiv = AesKeyIV.GenKeyIV(); AesKeyIV.SendAesKeyIVAes(sock, bytes, kiv); m_Handler.HandleAcceptConnected(sock, kiv); } } else { sock.BeginReceive(m_Buffer, m_BufferReceivedSize, m_Buffer.Length - m_BufferReceivedSize, SocketFlags.None, new AsyncCallback(HandleHeadReceived), sock); } } else { LogHelper.Error(SocketError.NoData.ToString()); sock.Close(); } } catch (Exception e) { LogHelper.Exception(e); sock.Close(); } }
private void Decrypt_Click(object sender, RoutedEventArgs e) { var list = output.Text.Split('*').Where(item => item != "").ToList(); var keys = key.Text.Split(':').Select(item => int.Parse(item)).ToArray(); var hash = rsa.Decrypt(list, keys[0], keys[1]); if (hash == input.Text.GetHashCode().ToString()) { MessageBox.Show("Цифровая подпись совпала"); } else { MessageBox.Show("Цифровая подпись не совпадает"); } }
public async Task SwapKeys(string publicKey) { string url = $"{baseUrl}/SwapKeys"; var result = await _httpService.PostApiResult(url, publicKey); if (String.IsNullOrEmpty(result)) { throw new NullReferenceException(); } else { var crypt = JsonConvert.DeserializeObject <string>(result).Split(","); Client.ServerKey = Rsa.Decrypt(crypt[0], Rsa.PrivateKey); Client.ServerIV = Rsa.Decrypt(crypt[1], Rsa.PrivateKey); } }
public byte[] GetSharedKey(string publicKey) { if (!IsBannerHandshake) { byte[] paddedPublicKeyAsBytes = HexToBytes(publicKey); if (IsInitiator) { Rsa.Decrypt(ref paddedPublicKeyAsBytes); } else { Rsa.Verify(ref paddedPublicKeyAsBytes); } publicKey = Encoding.Default.GetString(paddedPublicKeyAsBytes); } var unpaddedPublicKey = new BigInteger(publicKey, 10); return(unpaddedPublicKey.ModPow(DhPrivate, DhPrime).ToBytes()); }
public void Run(string raw) { const int byteSize = 2048 / 8; raw = raw + raw; Rsa.GenerateKey(byteSize, out var pk, out var sk); Utils.WriteByteArray(pk, "pk"); Utils.WriteByteArray(sk, "sk"); var e = Encoding.UTF8; Utils.WriteByteArray(e.GetBytes(raw), "raw"); var secret = Rsa.Encrypt(e.GetBytes(raw), pk); Utils.WriteByteArray(secret, "secret"); var real = Rsa.Decrypt(secret, pk, sk); Console.WriteLine("Real: " + e.GetString(real)); if (!raw.Equals(e.GetString(real))) { throw new Exception("Rsa Test Failed"); } }
private static void EncryptDecrypt(Rsa rsa, BigInteger openText) { var cipherText = rsa.Encrypt(openText); Assert.Equal(openText, rsa.Decrypt(cipherText)); }
public string Decrypt(string data) { var bytes = Convert.FromBase64String(data); return(System.Text.Encoding.UTF8.GetString(Rsa.Decrypt(bytes, Padding))); }
public byte[] DecryptByteMessage(byte[] byteMessage, out int count) { byte[] decrypted = Rsa.Decrypt(byteMessage, false); count = decrypted.Length; return(decrypted); }
public void RsaDecrypt(bool useCipKeys = true) { Rsa.Decrypt(ref this.buffer, this.Cursor, this.length, useCipKeys); }
internal void GenerateToken(IApplicationBuilder app) { app.Run(async context => { if (!context.Request.Method.Equals("POST") || !context.Request.HasFormContentType) { await BadRequest(context, "format not support!"); return; } var userIdentity = context.Request.Form["userIdentity"]; var password = context.Request.Form["password"]; var platform = context.Request.Form["platform"]; if (platform == "browser") { if (Rsa.Decrypt(userIdentity, _privateKey, out var outString1)) { userIdentity = outString1; } if (Rsa.Decrypt(password, _privateKey, out var outString2)) { password = outString2; } } else { if (Rsa.Decrypt(userIdentity, out var outString1)) { userIdentity = outString1; } if (Rsa.Decrypt(password, out var outString2)) { password = outString2; } } var identityUser = AuthRepository?.FindUser(userIdentity, password, _connString); if (identityUser == null) { await BadRequest(context, "Invalid user identity or password."); return; } var now = DateTime.UtcNow; var claims = new[] { new Claim(JwtRegisteredClaimNames.Sub, identityUser.UserIdentity), new Claim(JwtRegisteredClaimNames.UniqueName, identityUser.Password), new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()), new Claim(JwtRegisteredClaimNames.Iat, now.ToString(CultureInfo.InvariantCulture), ClaimValueTypes.Integer64) }; var jwt = new JwtSecurityToken(_option.Issuer, _option.Audience, claims, now, now.Add(_option.Expiration), _option.SigningCredentials); var encodedJwt = new JwtSecurityTokenHandler().WriteToken(jwt); var response = new { access_token = encodedJwt, expires_in = (int)_option.Expiration.TotalSeconds, }; // Serialize and return the response context.Response.ContentType = "application/json"; string responseStr = JsonConvert.SerializeObject(response, new JsonSerializerSettings { Formatting = Formatting.Indented }); await context.Response.WriteAsync(responseStr); }); }
/// <summary> /// Decrypts the RSA. /// </summary> /// <returns>Whether the decryption is completed successfully.</returns> public bool DecryptRsa() { return(Rsa.Decrypt(ref _buffer, Position, Length)); }