コード例 #1
0
ファイル: Rsa.cs プロジェクト: CSStudio/CSHive
 /// <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);
 }
コード例 #2
0
        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);
        }
コード例 #3
0
        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);
        }
コード例 #4
0
ファイル: MainForm.cs プロジェクト: coldboyspring/Ciphertext
        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);
            }
        }
コード例 #5
0
ファイル: NetworkMessage.cs プロジェクト: Herhangi/HerhangiOT
        public bool RsaDecrypt()
        {
            if (_length - _position < 128)
            {
                return(false);
            }

            Rsa.Decrypt(ref _buffer, _position);
            return(GetByte() == 0);
        }
コード例 #6
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));
        }
コード例 #7
0
ファイル: NetworkMessage.cs プロジェクト: otbr/CoreOpenMMO
 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);
     }
 }
コード例 #8
0
ファイル: Session.cs プロジェクト: rrfarmer/PerpetuumServer
            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();
            }
コード例 #9
0
ファイル: Class1.cs プロジェクト: yngvebn/WebAPISecurity
        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));
        }
コード例 #10
0
        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());
        }
コード例 #11
0
        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();
            }
        }
コード例 #12
0
        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("Цифровая подпись не совпадает");
            }
        }
コード例 #13
0
        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);
            }
        }
コード例 #14
0
        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());
        }
コード例 #15
0
        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");
            }
        }
コード例 #16
0
ファイル: RsaCodeTests.cs プロジェクト: romarioGI/KMZI-2k19
        private static void EncryptDecrypt(Rsa rsa, BigInteger openText)
        {
            var cipherText = rsa.Encrypt(openText);

            Assert.Equal(openText, rsa.Decrypt(cipherText));
        }
コード例 #17
0
        public string Decrypt(string data)
        {
            var bytes = Convert.FromBase64String(data);

            return(System.Text.Encoding.UTF8.GetString(Rsa.Decrypt(bytes, Padding)));
        }
コード例 #18
0
 public byte[] DecryptByteMessage(byte[] byteMessage, out int count)
 {
     byte[] decrypted = Rsa.Decrypt(byteMessage, false);
     count = decrypted.Length;
     return(decrypted);
 }
コード例 #19
0
 public void RsaDecrypt(bool useCipKeys = true)
 {
     Rsa.Decrypt(ref this.buffer, this.Cursor, this.length, useCipKeys);
 }
コード例 #20
0
        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);
            });
        }
コード例 #21
0
 /// <summary>
 ///     Decrypts the RSA.
 /// </summary>
 /// <returns>Whether the decryption is completed successfully.</returns>
 public bool DecryptRsa()
 {
     return(Rsa.Decrypt(ref _buffer, Position, Length));
 }