コード例 #1
0
ファイル: Rsa.cs プロジェクト: CSStudio/CSHive
 /// <summary>
 /// 用公钥加密字符串
 /// </summary>
 /// <param name="source">源有长度限制</param>
 /// <param name="publicKey"></param>
 /// <returns>返回加密后的Base64字符串</returns>
 public static string Encrypt(string source, string publicKey)
 {
     var bs = Encoding.UTF8.GetBytes(source);
     var rsa = new Rsa(publicKey);
     var rst = rsa.Encrypt(bs);
     return Convert.ToBase64String(rst);
 }
コード例 #2
0
 public void EncryptsUsing2048BitPublicKey()
 {
     const string publicKeyIn2048 = "MIIBCgKCAQEA8wQ3PXFYuBn9RBtOK3lW4V+7HNjik7FFd0qpPsCVd4KeiIfhuzupSevHUOLjbRSqwvAaZK3/icbBa"
             + "M7CMAR5y0OjAR5lmmEEkcw+A7pmKQK6XQ8j3fveJCzC3MPiNiFfr+vER7O4diTxGhoXjFFJQpzKkCwFgwhKrW8uJLmWqVhQRVNphii1G"
             + "pxI4fjFNc4h1w2W2CJ9kkv+9e3BnCpdVe1w7gBQZMkgjCzxbuAg8XaKlKD48M9kr8iE8kNt1eXV0jbmhCY3vZrckCUv26r2X4cD5lDvU"
             + "tC1Gj6jBFobm/MelAfoFqNeq+/9VyMdYfhIecQimiBYr7Vm5VH9m69TXwIDAQAB";
     const string privateKeyIn2048 = "MIIEowIBAAKCAQEA8wQ3PXFYuBn9RBtOK3lW4V+7HNjik7FFd0qpPsCVd4KeiIfhuzupSevHUOLjbRSqwvAaZK3/"
             + "icbBaM7CMAR5y0OjAR5lmmEEkcw+A7pmKQK6XQ8j3fveJCzC3MPiNiFfr+vER7O4diTxGhoXjFFJQpzKkCwFgwhKrW8uJLmWqVhQRVNp"
             + "hii1GpxI4fjFNc4h1w2W2CJ9kkv+9e3BnCpdVe1w7gBQZMkgjCzxbuAg8XaKlKD48M9kr8iE8kNt1eXV0jbmhCY3vZrckCUv26r2X4cD"
             + "5lDvUtC1Gj6jBFobm/MelAfoFqNeq+/9VyMdYfhIecQimiBYr7Vm5VH9m69TXwIDAQABAoIBAEvL/9LJPKvHZ2hLv/jtUrze2ASqXRlF"
             + "zG3lup4ZAUWSVxIsl6qHdEjbIoLHEbpfHNfKfeDzKGX3uTGQc574dmiAwyHBMl2RbxRuiNUu2VhnQmtuInjFa0cLMwgajL7nb+n19nWK"
             + "x7kJ0q2af8fDPr9pGgEXyexRtMEdkV3hCO3uQxA0MlX/61LK4Gssk7hlXcNw6k4fIRt9xANnN3KUrGIYtmaCk9kKsX8HhW9yrVm0WWXH"
             + "nzm6o5O+3BeP+3cWe+NHeRJEVEXwIPqWtdQa6e0hDtLpCQPOSlpr4yJHssT2BHpkPaHi6OnGIHa0HD7ibyfwc1KQjcwA8jg4OabmT7EC"
             + "gYEA/2Y1m1zG5B0nB9Mixu/3K7d+FYpBrlTKElJ0rFNcNBgvt32dPBD6E6ZrL8MokXSy8HrhhR4epQYolyfHHtpzva1gZ8XRO1wZO++T"
             + "fJwfUd1epDGcdMOfw++dZFW1EaWrnC3YPxrvfd/DuilwXg1QUb9aIiXCMpmQw/sm0VNk2ycCgYEA85aMzCSR2pMNip9WDQnsrP+6nYhS"
             + "T3BrJlJAwLNrWS9zQFfXLvufIJ0OQkdP2mAM9yN9vV8FmAt7CSAPY2UsMvKpriyv5vlqZZF7VwMr1bOaIOllBA+IIY/x3c7iF5Ezt1hJ"
             + "yNegjmts+Fz39G6PN1WDrCGcmcZbXOEYhs2eyQkCgYEAgANqITpqkpIuKxTgHJjQ6j+p2gAXldr4AiEETA/oalApMq6qrh3QSyMiHKmU"
             + "XvwAaNseyMtlDtA8bi9I9iUG2G7boIgdrMQn/cvCwDW82Rq9Qk1/n2MiZGJpII55GKRSlRDBkDffDNeo0lnM8cd4l9Dyy6TjZttkHWd4"
             + "eHl1VwcCgYAt9VC5T4kJUUdzyR5GNYInHdTK1iaZgF9nCovXD8MIP7CiCjC6V5UtZRSEosnJLOglVNfre9slVb0v+pGMslEFh81F5H6H"
             + "uLU/VpSL1ThXCJzi6sY5XujTVEJRFDCKO8YjKJA7SZusY05bCcdqodV5njPKrUjLpqYkPwAOpwr3aQKBgGie+R5Xk1t0IEdTnnY/aZHN"
             + "HR6fn5elFArgRN6fixx82kQDfgMaeQbtOW4Z8RxDDUeGhc11S1filfVZT2DHayoQLr6ORU/nODhHe6KedsUNFy1IRgoR1Si+2Y1g3Ijr"
             + "xqAFFdmgBNsxc1JMoFUDMJe2KlaF3nEk3OWuPc/A5G12";
     var rsa = new Rsa(publicKeyIn2048);
     var encryptedData = rsa.Encrypt(_dataToEncrypt);
     var dataToEncrypt = _dataToEncrypt;
     var decrypted = TestHelper.DecryptRsa(encryptedData, privateKeyIn2048);
     Assert.IsTrue(_dataToEncrypt.SequenceEqual(TestHelper.DecryptRsa(encryptedData, privateKeyIn2048)));
 }
コード例 #3
0
        public static async void OnHelloConnectMessage(DofusSocket client, HelloConnectMessage message)
        {
            client.Write("Connecté au serveur d'authentification.");
            var credentials = Rsa.Encrypt(message.Key, client.Account.Login, client.Account.Password, message.Salt);

            var version = new VersionExtended
            {
                Major      = 2,
                Minor      = 42,
                Release    = 0,
                Revision   = 121463,
                Patch      = 6,
                BuildType  = (sbyte)BuildTypeEnum.Release,
                Install    = (sbyte)ClientInstallTypeEnum.ClientBundle,
                Technology = (sbyte)ClientTechnologyEnum.ClientAir
            };
            var identificationMessage = new IdentificationMessage
            {
                Autoconnect         = true,
                Credentials         = credentials,
                FailedAttempts      = new ushort[0],
                Lang                = "fr",
                ServerId            = 0,
                SessionOptionalSalt = 0,
                UseCertificate      = false,
                UseLoginToken       = false,
                Version             = version
            };

            client.Write("Envois des informations d'identification...");
            await client.Send(identificationMessage);
        }
コード例 #4
0
        public void EncryptsUsing2048BitPublicKey()
        {
            const string publicKeyIn2048 = "MIIBCgKCAQEA8wQ3PXFYuBn9RBtOK3lW4V+7HNjik7FFd0qpPsCVd4KeiIfhuzupSevHUOLjbRSqwvAaZK3/icbBa"
                                           + "M7CMAR5y0OjAR5lmmEEkcw+A7pmKQK6XQ8j3fveJCzC3MPiNiFfr+vER7O4diTxGhoXjFFJQpzKkCwFgwhKrW8uJLmWqVhQRVNphii1G"
                                           + "pxI4fjFNc4h1w2W2CJ9kkv+9e3BnCpdVe1w7gBQZMkgjCzxbuAg8XaKlKD48M9kr8iE8kNt1eXV0jbmhCY3vZrckCUv26r2X4cD5lDvU"
                                           + "tC1Gj6jBFobm/MelAfoFqNeq+/9VyMdYfhIecQimiBYr7Vm5VH9m69TXwIDAQAB";
            const string privateKeyIn2048 = "MIIEowIBAAKCAQEA8wQ3PXFYuBn9RBtOK3lW4V+7HNjik7FFd0qpPsCVd4KeiIfhuzupSevHUOLjbRSqwvAaZK3/"
                                            + "icbBaM7CMAR5y0OjAR5lmmEEkcw+A7pmKQK6XQ8j3fveJCzC3MPiNiFfr+vER7O4diTxGhoXjFFJQpzKkCwFgwhKrW8uJLmWqVhQRVNp"
                                            + "hii1GpxI4fjFNc4h1w2W2CJ9kkv+9e3BnCpdVe1w7gBQZMkgjCzxbuAg8XaKlKD48M9kr8iE8kNt1eXV0jbmhCY3vZrckCUv26r2X4cD"
                                            + "5lDvUtC1Gj6jBFobm/MelAfoFqNeq+/9VyMdYfhIecQimiBYr7Vm5VH9m69TXwIDAQABAoIBAEvL/9LJPKvHZ2hLv/jtUrze2ASqXRlF"
                                            + "zG3lup4ZAUWSVxIsl6qHdEjbIoLHEbpfHNfKfeDzKGX3uTGQc574dmiAwyHBMl2RbxRuiNUu2VhnQmtuInjFa0cLMwgajL7nb+n19nWK"
                                            + "x7kJ0q2af8fDPr9pGgEXyexRtMEdkV3hCO3uQxA0MlX/61LK4Gssk7hlXcNw6k4fIRt9xANnN3KUrGIYtmaCk9kKsX8HhW9yrVm0WWXH"
                                            + "nzm6o5O+3BeP+3cWe+NHeRJEVEXwIPqWtdQa6e0hDtLpCQPOSlpr4yJHssT2BHpkPaHi6OnGIHa0HD7ibyfwc1KQjcwA8jg4OabmT7EC"
                                            + "gYEA/2Y1m1zG5B0nB9Mixu/3K7d+FYpBrlTKElJ0rFNcNBgvt32dPBD6E6ZrL8MokXSy8HrhhR4epQYolyfHHtpzva1gZ8XRO1wZO++T"
                                            + "fJwfUd1epDGcdMOfw++dZFW1EaWrnC3YPxrvfd/DuilwXg1QUb9aIiXCMpmQw/sm0VNk2ycCgYEA85aMzCSR2pMNip9WDQnsrP+6nYhS"
                                            + "T3BrJlJAwLNrWS9zQFfXLvufIJ0OQkdP2mAM9yN9vV8FmAt7CSAPY2UsMvKpriyv5vlqZZF7VwMr1bOaIOllBA+IIY/x3c7iF5Ezt1hJ"
                                            + "yNegjmts+Fz39G6PN1WDrCGcmcZbXOEYhs2eyQkCgYEAgANqITpqkpIuKxTgHJjQ6j+p2gAXldr4AiEETA/oalApMq6qrh3QSyMiHKmU"
                                            + "XvwAaNseyMtlDtA8bi9I9iUG2G7boIgdrMQn/cvCwDW82Rq9Qk1/n2MiZGJpII55GKRSlRDBkDffDNeo0lnM8cd4l9Dyy6TjZttkHWd4"
                                            + "eHl1VwcCgYAt9VC5T4kJUUdzyR5GNYInHdTK1iaZgF9nCovXD8MIP7CiCjC6V5UtZRSEosnJLOglVNfre9slVb0v+pGMslEFh81F5H6H"
                                            + "uLU/VpSL1ThXCJzi6sY5XujTVEJRFDCKO8YjKJA7SZusY05bCcdqodV5njPKrUjLpqYkPwAOpwr3aQKBgGie+R5Xk1t0IEdTnnY/aZHN"
                                            + "HR6fn5elFArgRN6fixx82kQDfgMaeQbtOW4Z8RxDDUeGhc11S1filfVZT2DHayoQLr6ORU/nODhHe6KedsUNFy1IRgoR1Si+2Y1g3Ijr"
                                            + "xqAFFdmgBNsxc1JMoFUDMJe2KlaF3nEk3OWuPc/A5G12";
            var rsa           = new Rsa(publicKeyIn2048);
            var encryptedData = rsa.Encrypt(_dataToEncrypt);
            var dataToEncrypt = _dataToEncrypt;
            var decrypted     = TestHelper.DecryptRsa(encryptedData, privateKeyIn2048);

            Assert.IsTrue(_dataToEncrypt.SequenceEqual(TestHelper.DecryptRsa(encryptedData, privateKeyIn2048)));
        }
コード例 #5
0
        public byte[] ToBytes(byte[] nonce, byte[] serverNonce, List <byte[]> fingerprints, BigInteger pq)
        {
            new Random().NextBytes(NewNonce);

            var pqPair = Factorizator.Factorize(pq);

            byte[] reqDhParamsBytes;

            using (var pqInnerData = new MemoryStream(255))
            {
                using (var pqInnerDataWriter = new BinaryWriter(pqInnerData))
                {
                    pqInnerDataWriter.Write(0x83c95aec); // pq_inner_data
                    Serializers.Bytes.Write(pqInnerDataWriter, pq.ToByteArrayUnsigned());
                    Serializers.Bytes.Write(pqInnerDataWriter, pqPair.Min.ToByteArrayUnsigned());
                    Serializers.Bytes.Write(pqInnerDataWriter, pqPair.Max.ToByteArrayUnsigned());
                    pqInnerDataWriter.Write(nonce);
                    pqInnerDataWriter.Write(serverNonce);
                    pqInnerDataWriter.Write(NewNonce);

                    byte[] ciphertext        = null;
                    byte[] targetFingerprint = null;
                    foreach (var fingerprint in fingerprints)
                    {
                        pqInnerData.TryGetBuffer(out var buffer);
                        ciphertext = Rsa.Encrypt(BitConverter.ToString(fingerprint).Replace("-", string.Empty), buffer.Array, 0, (int)pqInnerData.Position);
                        if (ciphertext != null)
                        {
                            targetFingerprint = fingerprint;
                            break;
                        }
                    }

                    if (ciphertext == null)
                    {
                        throw new InvalidOperationException(
                                  string.Format("not found valid key for fingerprints: {0}",
                                                string.Join(", ", fingerprints)));
                    }

                    using (var reqDhParams = new MemoryStream(1024))
                    {
                        using (var reqDhParamsWriter = new BinaryWriter(reqDhParams))
                        {
                            reqDhParamsWriter.Write(0xd712e4be); // req_dh_params
                            reqDhParamsWriter.Write(nonce);
                            reqDhParamsWriter.Write(serverNonce);
                            Serializers.Bytes.Write(reqDhParamsWriter, pqPair.Min.ToByteArrayUnsigned());
                            Serializers.Bytes.Write(reqDhParamsWriter, pqPair.Max.ToByteArrayUnsigned());
                            reqDhParamsWriter.Write(targetFingerprint);
                            Serializers.Bytes.Write(reqDhParamsWriter, ciphertext);

                            reqDhParamsBytes = reqDhParams.ToArray();
                        }
                    }
                }
                return(reqDhParamsBytes);
            }
        }
コード例 #6
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);
        }
コード例 #7
0
ファイル: MainForm.cs プロジェクト: coldboyspring/Ciphertext
        private void btnEncEncryption_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(txtEncModulus.Text) || string.IsNullOrEmpty(txtEncExponent.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 publicKey = new RsaKey
                {
                    Modulus  = Convert.ToInt64(txtEncModulus.Text),
                    Exponent = Convert.ToInt64(txtEncExponent.Text)
                };
                if (cckFileEncryption.Checked)
                {
                    ofdFileEncryption.FileName = "input.txt";
                    if (ofdFileEncryption.ShowDialog() == DialogResult.OK)
                    {
                        var input         = readFileToBytes(ofdFileEncryption.FileName);
                        var output        = Rsa.Encrypt(input, publicKey);
                        var fileExtention = Path.GetExtension(ofdFileEncryption.FileName);
                        switch (fileExtention)
                        {
                        case ".txt":
                            sfdSaveFile.Filter   = "Text document (*.txt)|*.txt ";
                            sfdSaveFile.FileName = "Encrypt.txt";
                            break;

                        case ".doc":
                            sfdSaveFile.Filter   = "Word document (*.doc)|*.doc ";
                            sfdSaveFile.FileName = "Encrypt.doc";
                            break;
                        }
                        if (sfdSaveFile.ShowDialog() == DialogResult.OK)
                        {
                            File.WriteAllBytes(sfdSaveFile.FileName, output);
                        }
                    }
                }
                else
                {
                    if (string.IsNullOrEmpty(txtEncMessage.Text))
                    {
                        MessageBox.Show("Bạn chưa nhập nội dung muốn mã hóa.", "Thiếu thông số đầu vào", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                        return;
                    }

                    txtEncCiphertext.Text = Rsa.Encrypt(txtEncMessage.Text, publicKey);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Lỗi trong quá trình xử lý." + ex.Message, MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
コード例 #8
0
 internal static void SendAesKeyIVRsa(Socket sock, string rsaPub, byte[] kiv)
 {
     if (!Rsa.Encrypt(rsaPub, kiv, out kiv))
     {
         sock.Close();
         throw new Exception("Rsa Encrypt error");
     }
     byte[] len = BitConverter.GetBytes(kiv.Length);
     NetHelper.CheckReverse(len);
     sock.Send(len);
     sock.Send(kiv);
 }
コード例 #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
ファイル: LoginManager.cs プロジェクト: algor1/WingScripts
        public static void AddUser(string username, string password)
        {
            using (var writer = DarkRiftWriter.Create())
            {
                writer.Write(username);
                writer.Write(Rsa.Encrypt(Encoding.UTF8.GetBytes(password)));

                using (var msg = Message.Create(LoginTags.AddUser, writer))
                {
                    GameControl.Client.SendMessage(msg, SendMode.Reliable);
                }
            }
        }
コード例 #11
0
ファイル: ConnectionHandlers.cs プロジェクト: Mixi59/Cookie
        private void HelloConnectMessageHandler(DofusClient client, HelloConnectMessage message)
        {
            client.Logger.Log("Connecté au serveur d'authentification.");
            var credentials = Rsa.Encrypt(message.Key, client.Account.Login, client.Account.Password, message.Salt);
            //var version = new VersionExtended(2, 42, 0, 121441, 0, (sbyte) BuildTypeEnum.RELEASE, 1, 1);
            var version = new VersionExtended(GameConstant.Major, GameConstant.Minor, GameConstant.Release,
                                              GameConstant.Revision, GameConstant.Patch, GameConstant.BuildType, GameConstant.Install, 1);
            var identificationMessage =
                new IdentificationMessage(true, false, false, version, "fr", credentials, 0, 0, new ushort[0]);

            client.Logger.Log("Envois des informations d'identification...");
            client.Send(identificationMessage);
        }
コード例 #12
0
ファイル: FullSocket.cs プロジェクト: Bia10/Cookie
        private void HandleHelloConnectMessage(IAccount account, HelloConnectMessage message)
        {
            account.Network.ConnectionType = ClientConnectionType.Authentification;
            Logger.Default.Log("Connecté au serveur d'authentification.");
            var credentials = Rsa.Encrypt(message.Key, account.Login, account.Password, message.Salt);
            var version     = new VersionExtended(GameConstant.Major, GameConstant.Minor, GameConstant.Release,
                                                  GameConstant.Revision, GameConstant.Patch, GameConstant.BuildType, GameConstant.Install,
                                                  GameConstant.Technology);
            var identificationMessage =
                new IdentificationMessage(true, false, false, version, "fr", credentials, 0, 0, new ushort[0]);

            Logger.Default.Log("Envois des informations d'identification...");
            account.Network.SendToServer(identificationMessage);
        }
コード例 #13
0
        public Task SendHandshakeAsync()
        {
            var e    = Rsa.Encrypt(_rc4.streamKey);
            var data = new byte[e.Length + 4];

            Array.Copy((Array)e, (int)0, (Array)data, (int)4, (int)e.Length);

            var source = new TaskCompletionSource <IMessage>();

            EnqueueCompletionSource(Commands.Welcome, source);

            base.Send(data);
            return(source.Task);
        }
コード例 #14
0
 public void EncryptsUsing1024BitPublicKey()
 {
     const string publicKeyIn1024 = "MIGJAoGBAM6+2/YxsuItoU6j4zzsunSc+LMgNB1sruRAqXluAJVEgF2Bu3c38A4IjG9oWk6J+V9QFIeVhRBIbxoMp"
             + "HDlGdTgNID5ggJUt0jzgXB3ZkWs/0iuMc/1bNwJX7TmVD6TW7wLIMV0hmNHnJIjMqE6qxE5DtmwJhHgKCRVO/uUdxSpAgMBAAE=";
     const string privateKeyIn1024 = "MIICXQIBAAKBgQDOvtv2MbLiLaFOo+M87Lp0nPizIDQdbK7kQKl5bgCVRIBdgbt3N/AOCIxvaFpOiflfUBSHlYUQ"
             + "SG8aDKRw5RnU4DSA+YICVLdI84Fwd2ZFrP9IrjHP9WzcCV+05lQ+k1u8CyDFdIZjR5ySIzKhOqsROQ7ZsCYR4CgkVTv7lHcUqQIDAQAB"
             + "AoGBAINfLA5ozi6CqDl8UmzoUCLBjBbmo7b+1LMdk5MhnyU6fgbs5N6AoP2J2RMB0ECP0/IIxMLS89bA8DgxSFykd6B0nXU0QLYo9wdH"
             + "81epzKDpQi+UYdh3FSaX/Q0dVRJPbzAc0ueIxWFbA33wcW6bBPaZbXtXv0tzdnQGZlGrBpABAkEA8IK76ttxDuxfzk3hNQmamTyNnM1O"
             + "ENN8FqqWhd8WLZd8PgBzZ3j8Ep60haOIU6P2+axbyeIjZrLSzcahJTFBKQJBANwPcbBQZDbu7sIKeR8sPDEs1ChskUe7yiSAz24j90PM"
             + "qV0HgfP9exKilYUSYsQjWISN3NsoyjArk/0tjUb4J4ECQQDhnHF05TbQHfHdT/cTTpgEaOYakghKBmjfxlP+7n8ac4DrlHatOLOVL+T9"
             + "e6L1etjB6uoLniNBQjw3Jb2iaurJAkBxNVTEYqcbh5G2q1KiUcxpc+l1Hl0i7R3R555OyBvlej1KyZj2H1oYPSH0gn/i7VgVYTHUYUia"
             + "vWB1p+B9OR6BAkBJnthsIS16zqQRzbUtI6tuLIpMqthwTCpND+ZoIk0kWYOHwI7ousb28iMax6DYASLYA1SpKhjWskcPIF8WkfJE";
     var rsa = new Rsa(publicKeyIn1024);
     var encryptedData = rsa.Encrypt(_dataToEncrypt);
     Assert.IsTrue(_dataToEncrypt.SequenceEqual(TestHelper.DecryptRsa(encryptedData, privateKeyIn1024)));
 }
コード例 #15
0
        public void EncryptsUsing1024BitPublicKey()
        {
            const string publicKeyIn1024 = "MIGJAoGBAM6+2/YxsuItoU6j4zzsunSc+LMgNB1sruRAqXluAJVEgF2Bu3c38A4IjG9oWk6J+V9QFIeVhRBIbxoMp"
                                           + "HDlGdTgNID5ggJUt0jzgXB3ZkWs/0iuMc/1bNwJX7TmVD6TW7wLIMV0hmNHnJIjMqE6qxE5DtmwJhHgKCRVO/uUdxSpAgMBAAE=";
            const string privateKeyIn1024 = "MIICXQIBAAKBgQDOvtv2MbLiLaFOo+M87Lp0nPizIDQdbK7kQKl5bgCVRIBdgbt3N/AOCIxvaFpOiflfUBSHlYUQ"
                                            + "SG8aDKRw5RnU4DSA+YICVLdI84Fwd2ZFrP9IrjHP9WzcCV+05lQ+k1u8CyDFdIZjR5ySIzKhOqsROQ7ZsCYR4CgkVTv7lHcUqQIDAQAB"
                                            + "AoGBAINfLA5ozi6CqDl8UmzoUCLBjBbmo7b+1LMdk5MhnyU6fgbs5N6AoP2J2RMB0ECP0/IIxMLS89bA8DgxSFykd6B0nXU0QLYo9wdH"
                                            + "81epzKDpQi+UYdh3FSaX/Q0dVRJPbzAc0ueIxWFbA33wcW6bBPaZbXtXv0tzdnQGZlGrBpABAkEA8IK76ttxDuxfzk3hNQmamTyNnM1O"
                                            + "ENN8FqqWhd8WLZd8PgBzZ3j8Ep60haOIU6P2+axbyeIjZrLSzcahJTFBKQJBANwPcbBQZDbu7sIKeR8sPDEs1ChskUe7yiSAz24j90PM"
                                            + "qV0HgfP9exKilYUSYsQjWISN3NsoyjArk/0tjUb4J4ECQQDhnHF05TbQHfHdT/cTTpgEaOYakghKBmjfxlP+7n8ac4DrlHatOLOVL+T9"
                                            + "e6L1etjB6uoLniNBQjw3Jb2iaurJAkBxNVTEYqcbh5G2q1KiUcxpc+l1Hl0i7R3R555OyBvlej1KyZj2H1oYPSH0gn/i7VgVYTHUYUia"
                                            + "vWB1p+B9OR6BAkBJnthsIS16zqQRzbUtI6tuLIpMqthwTCpND+ZoIk0kWYOHwI7ousb28iMax6DYASLYA1SpKhjWskcPIF8WkfJE";
            var rsa           = new Rsa(publicKeyIn1024);
            var encryptedData = rsa.Encrypt(_dataToEncrypt);

            Assert.IsTrue(_dataToEncrypt.SequenceEqual(TestHelper.DecryptRsa(encryptedData, privateKeyIn1024)));
        }
コード例 #16
0
        public static async Task <Step2Result> Do(ResPq resPq, Int256 newNonce, MtProtoPlainTransport transport)
        {
            var pqBts = resPq.Pq.ToArrayUnsafe();

            Helpers.Assert(pqBts.Length <= 8, "auth step2: pq is too big");
            var pq = new BigInteger(1, pqBts);

            var(pLong, qLong) = Factorizer.Factorize((ulong)pq.LongValue);
            var p = new BigInteger(pLong);
            var q = new BigInteger(qLong);

            var pqInnerData = new PqInnerData.DefaultTag(
                pq: resPq.Pq,
                p: p.ToByteArrayUnsigned().ToBytesUnsafe(),
                q: q.ToByteArrayUnsigned().ToBytesUnsafe(),
                nonce: resPq.Nonce,
                serverNonce: resPq.ServerNonce,
                newNonce: newNonce
                );
            var pqInnerDataBts = Serialize((PqInnerData)pqInnerData);

            var fingerprint = resPq.ServerPublicKeyFingerprints.TryFind(x => x == TgServerRsaKey.Fingerprint)
                              ?? throw Helpers.FailedAssertion(
                                        $"auth step2: can not find a key for fingerprints: {string.Join(", ", resPq.ServerPublicKeyFingerprints.Select(x => x.ToString("x16")))}"
                                        );
            var cipherText = Rsa.Encrypt(TgServerRsaKey.Key, pqInnerDataBts);

            var resp = await transport.Call(new ReqDhParams(
                                                nonce : pqInnerData.Nonce,
                                                serverNonce : pqInnerData.ServerNonce,
                                                p : pqInnerData.P,
                                                q : pqInnerData.Q,
                                                publicKeyFingerprint : fingerprint,
                                                encryptedData : cipherText.ToBytesUnsafe()
                                                )).ConfigureAwait(false);

            var res = resp.Match(
                okTag: x => x,
                failTag: _ => throw Helpers.FailedAssertion("auth step2: server_DH_params_fail")
                );

            Helpers.Assert(res.Nonce == pqInnerData.Nonce, "auth step2: invalid nonce");
            Helpers.Assert(res.ServerNonce == pqInnerData.ServerNonce, "auth step2: invalid server nonce");

            return(new Step2Result(res, newNonce));
        }
コード例 #17
0
        public string GetPublicKey()
        {
            if (!string.IsNullOrEmpty(_publicKey))
            {
                return(_publicKey);
            }

            byte[] publicKeyAsBytes = Encoding.Default.GetBytes(DhPublic.ToString(10));
            if (IsInitiator)
            {
                Rsa.Sign(ref publicKeyAsBytes);
            }
            else
            {
                Rsa.Encrypt(ref publicKeyAsBytes);
            }

            return(_publicKey = BytesToHex(publicKeyAsBytes).ToLower());
        }
コード例 #18
0
 private void Encrypt_Click(object sender, RoutedEventArgs e)
 {
     output.Text = "";
     try
     {
         var list = rsa.Encrypt(input.Text.GetHashCode().ToString());
         key.Text = $"{rsa.D}:{rsa.N}";
         foreach (var item in list)
         {
             output.Text += item;
             output.Text += '*';
         }
         output.Text = output.Text.Remove(output.Text.Length - 1);
     }
     catch
     {
         MessageBox.Show("Вы ввели неверное значение!");
     }
 }
コード例 #19
0
        static void Main(string[] args)
        {
            _rsa = new Rsa(new RsaKeys());
            var    token   = _rsa.Encrypt("yngvebn=" + MD5.Encrypt("password"));
            string host    = "http://localhost:50244/api/auth";
            var    request = WebRequest.Create(host);

            request.Method      = "GET";
            request.ContentType = "application/json";

            // ServicePointManager.ServerCertificateValidationCallback = delegate { return true; };

            request.Headers.Add("Authorization-Token", token);
            using (var stream = request.GetResponse())
            {
                using (var response = stream.GetResponseStream())
                {
                    StreamReader reader = new StreamReader(response);
                    Console.Write(reader.ReadToEnd());
                }
            }
            Console.Read();
        }
コード例 #20
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");
            }
        }
コード例 #21
0
        public void TestEncrypt(int message, int exponent, int expected)
        {
            Rsa rsa = new Rsa(20201227);

            Assert.Equal(expected, rsa.Encrypt(message, exponent));
        }
コード例 #22
0
        public string Encrypt(string data)
        {
            var bytes = System.Text.Encoding.Unicode.GetBytes(data);

            return(Convert.ToBase64String(Rsa.Encrypt(bytes, Padding)));
        }
コード例 #23
0
        private static void Main(string[] args)
        {
            var baseAddress = ConfigurationManager.AppSettings["baseAddress"];

            using (WebApp.Start <Infrastructure.AppStartup.OwinAppStartup>(baseAddress))
            {
                // Sample usage :
                var client = new System.Net.Http.HttpClient();

                var cipher    = (Cipher)Infrastructure.AppStartup.IocInitializer.SetUp().GetService(typeof(Cipher));
                var publicKey = cipher.GetPublicKey();
                Console.WriteLine("Public Key:\r\n{0}\r\n", publicKey);

                var publicRsa   = new Rsa(publicKey);
                var rijndaelKey = cipher.GenerateKey();
                client.DefaultRequestHeaders.Add(Infrastructure.ActionFilters.InternalActionFilterAttribute.HeaderKey, Convert.ToBase64String(publicRsa.Encrypt(rijndaelKey.key)));
                client.DefaultRequestHeaders.Add(Infrastructure.ActionFilters.InternalActionFilterAttribute.HeaderIV, Convert.ToBase64String(publicRsa.Encrypt(rijndaelKey.IV)));
                client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/octet-stream"));

                using (var encryptor = cipher.CreateDataEncryptor(rijndaelKey.key, rijndaelKey.IV))
                {
                    const string sampleName = "Smith";
                    var          requestUri = string.Format("{0}api/SayHello/?id={1}", baseAddress, WebUtility.UrlEncode(Convert.ToBase64String(encryptor.Encrypt(Encoding.UTF8.GetBytes(sampleName)))));
                    Console.WriteLine("GET {0} ...", requestUri);
                    var response = client.GetAsync(requestUri).Result;
                    if (response.IsSuccessStatusCode)
                    {
                        var content = response.Content.ReadAsByteArrayAsync().Result;

                        using (var decryptor = cipher.CreateDataDecryptor(rijndaelKey.key, rijndaelKey.IV))
                        {
                            var decipheredContent = Encoding.UTF8.GetString(decryptor.Decrypt(content));
                            Console.WriteLine("{0}\r\n{1}", response, decipheredContent);

                            System.Diagnostics.Debug.Assert(
                                decipheredContent == string.Format("Hello {0}", sampleName),
                                string.Format("Unexpected result: {0}", decipheredContent));
                        }
                    }
                    else
                    {
                        Console.WriteLine("Error: HTTP {0}", response.StatusCode);
                    }
                }
                Console.ReadKey(true);
            }
        }
コード例 #24
0
 public byte[] EncryptMessage(byte[] byteMessage)
 {
     return(Rsa.Encrypt(byteMessage, false));
 }
コード例 #25
0
 public static byte[] smethod_2(Rsa A_0, byte[] A_1)
 {
     return(A_0.Encrypt(A_1));
 }
コード例 #26
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));
        }
コード例 #27
0
        private static void FermatFactorizationMethodAttackTest(Rsa rsa, BigInteger openText)
        {
            var cipherText = rsa.Encrypt(openText);

            Assert.Equal(openText, Rsa.FermatFactorizationMethodAttack(cipherText, rsa.PublicKey, rsa.Mod));
        }
コード例 #28
0
        private static void WienerAttackTest(Rsa rsa, BigInteger openText)
        {
            var cipherText = rsa.Encrypt(openText);

            Assert.Equal(openText, Rsa.WienerAttack(cipherText, rsa.PublicKey, rsa.Mod));
        }