示例#1
0
        public void Serialize(Guid connectionId, IConnectionEvent eventObject, Stream output)
        {
            var serializer = new JsonSerializer {
                ContractResolver = new CamelCasePropertyNamesContractResolver()
            };
            UserConnection user;

            ConnectionManager._connections.TryGetValue(connectionId, out user);
            if (user != null)
            {
                var json = JObject.FromObject(eventObject, serializer);
                json.Add("type", new JValue(eventObject.GetType().Name));
                json.Remove("connectionId");
                var jsonString = json.ToString();
                var utfJson    = Encoding.Default.GetBytes(jsonString);
                jsonString = Encoding.UTF8.GetString(utfJson);
                if (user.AesShook)
                {
                    var keybytes      = Encoding.UTF8.GetBytes(Rsa.SecureStringToString(user.AesKey));
                    var iv            = Encoding.UTF8.GetBytes(Rsa.SecureStringToString(user.AesIv));
                    var encrpytedJson = UlteriusAes.Encrypt(jsonString, keybytes, iv);
                    using (var writer = new BinaryWriter(output, Encoding.UTF8, true))
                    {
                        writer.Write(encrpytedJson);
                    }
                }
                else
                {
                    using (var writer = new StreamWriter(output, Encoding.UTF8, 4096, true))
                    {
                        writer.Write(jsonString);
                    }
                }
            }
        }
        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)));
        }
        public IConnectionRequest Deserialize(Guid connectionId, Stream source, out Type type)
        {
            UserConnection user;
            var            typeName = string.Empty;

            ConnectionManager._connections.TryGetValue(connectionId, out user);
            if (user != null)
            {
                var data = ReadFully(source);
                if (data != null && data.Length > 0)
                {
                    if (user.AesShook)
                    {
                        try
                        {
                            var keybytes   = Encoding.UTF8.GetBytes(Rsa.SecureStringToString(user.AesKey));
                            var iv         = Encoding.UTF8.GetBytes(Rsa.SecureStringToString(user.AesIv));
                            var packetJson = JObject.Parse(UlteriusAes.Decrypt(data, keybytes, iv));
                            typeName = packetJson.Property("type").Value.ToString();
                            return(Build(typeName, packetJson, out type, user));
                        }
                        catch (Exception exception)
                        {
                            Console.WriteLine(exception.Message);
                            return(Build("error", null, out type));
                        }
                    }
                    var json = JObject.Parse(Encoding.UTF8.GetString(data));
                    typeName = json.Property("type").Value.ToString();
                    return(Build(typeName, json, out type, user));
                }
            }
            return(Build("error", null, out type));
        }
示例#4
0
        /// <summary>
        ///     Sends a new user their unique RSA keypair
        /// </summary>
        /// <param name="client"></param>
        /// <param name="clientSocket"></param>
        private static async Task SendWelcomeMessage(AuthClient client, WebSocket clientSocket)
        {
            var welcomeMessage = JsonConvert.SerializeObject(new
            {
                endpoint = "connectedToUlterius",
                results  = new
                {
                    message   = "Ulterius server online!",
                    publicKey = Rsa.SecureStringToString(client.PublicKey)
                }
            });

            if (clientSocket != null)
            {
                try
                {
                    await clientSocket.WriteStringAsync(welcomeMessage, CancellationToken.None);

                    var userCount = AllClients.Count;
                    var extra     = userCount > 1 ? "s" : string.Empty;
                    UlteriusTray.ShowMessage($"There are now {userCount} user{extra} connected.", "A new user connected!");
                }
                catch (Exception ex)
                {
                    Console.WriteLine("Failed to write welcome message " + ex.Message);
                }
            }
        }
示例#5
0
        static void Main(string[] args)
        {
            Console.WriteLine("Standalone Login Server is not yet supported!");
            Console.ReadKey();
            return;

            Tools.Initialize();

            ConfigManager.Load("config_login.lua");
            Rsa.SetKey(RsaP, RsaQ);

            Database.Initialize();

            LoginServer.Start();

            while (true)
            {
                string input = Console.ReadLine();

                if (input == null)
                {
                    continue;
                }

                string[]      firstPass  = input.Split('"');
                List <string> secondPass = firstPass[0].Trim().Split(' ').ToList();

                if (firstPass.Length > 1)
                {
                    for (int i = 1; i < firstPass.Length; i++)
                    {
                        if (i % 2 == 1)
                        {
                            secondPass.Add(firstPass[i]);
                        }
                        else
                        {
                            secondPass.AddRange(firstPass[i].Trim().Split(' '));
                        }
                    }
                }
                string[] command = secondPass.ToArray();

                if (ScriptManager.CommandLineOperations.ContainsKey(command[0]))
                {
                    try
                    {
                        ScriptManager.CommandLineOperations[command[0]].Invoke(command);
                    }
                    catch (Exception)
                    {
                        Logger.Log(LogLevels.Warning, "Command '" + command[0] + "' could not be executed in this environment!");
                    }
                }
                else
                {
                    Logger.Log(LogLevels.Warning, "Command is unknown!");
                }
            }
        }
示例#6
0
        public void Connect(string addr, int port, string pub, bool async = true)
        {
            var ip = NetHelper.ParseIpAddressV6(addr);

            if (ip == null)
            {
                throw new Exception("Unknown addr = " + addr);
            }
            Close(string.Empty);

            m_SocketArgs          = new SocketArgs();
            m_SocketArgs.m_RsaPub = pub;
            if (!Rsa.CheckIsPub(pub))
            {
                throw new Exception(string.Format("RsaPub error {0}", pub));
            }
            m_SocketArgs.m_Socket = new Socket(ip.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
            m_SocketArgs.m_Socket.SetSocketOption(SocketOptionLevel.Tcp, SocketOptionName.NoDelay, true);
            m_SocketArgs.m_Socket.NoDelay = true;
            LogHelper.Debug("NetClient Connect {0}:{1}", ip, port);
            if (async)
            {
                m_SocketArgs.m_Socket.BeginConnect(new IPEndPoint(ip, port), new AsyncCallback(ConnectCallback), m_SocketArgs);
            }
            else
            {
                m_SocketArgs.m_Socket.Connect(new IPEndPoint(ip, port));
                LogHelper.Debug("NetClient Connect {0}", "OK");
                OnConnected(m_SocketArgs);
            }
        }
        private string Obtener_Certificado(byte[] pCertificado)
        {
            Cert loCert = new Cert();
            Rsa  loRsa  = new Rsa();

            bool success = true;

            // Desbloquea componente
            success = loRsa.UnlockComponent("RSAT34MB34N_7F1CD986683M");
            if (success != true)
            {
                throw new ArgumentException("No se pudo debloquear componente Chilkat RSA");
            }

            success = loCert.LoadFromBinary(pCertificado);

            if (success != true)
            {
                throw new ArgumentException("No se pudo cargar el archivo certificado");
            }

            string strCertificado = loCert.GetEncoded();
            int    LongitudCer    = strCertificado.Length;

            strCertificado = strCertificado.Substring(1 - 1, LongitudCer - 2);

            return(strCertificado);
        }
示例#8
0
        public static void GenKeyPair()
        {
            const int byteSize = 2048 / 8;

            Rsa.GenerateKey(byteSize, out var pk, out var sk);
            var pks = "public readonly static byte[] PkData = new byte[]{\n    ";

            for (var i = 0; i < pk.Length; ++i)
            {
                pks += $"{pk[i]},";
                if (i % 20 == 19)
                {
                    pks += "\n    ";
                }
            }
            pks += "\n};";
            var sks = "public readonly static byte[] SkData = new byte[]{\n    ";

            for (var i = 0; i < sk.Length; ++i)
            {
                sks += $"{sk[i]},";
                if (i % 20 == 19)
                {
                    sks += "\n    ";
                }
            }
            sks += "\n};";
            Console.WriteLine(pks);
            Console.WriteLine(sks);
        }
示例#9
0
        public bool VerificarSelloComprobante(string cadenaOriginal, string sello, HashAlgorithm algoritmo)
        {
            byte[]        digest       = Hash.BytesFromBytes(Encoding.UTF8.GetBytes(cadenaOriginal), algoritmo);
            StringBuilder llavePublica = Rsa.GetPublicKeyFromCert(Convert.ToBase64String(Convert.FromBase64String(_Base64)));

            if (llavePublica.Length == 0)
            {
                return(false);
            }
            byte[] sellado = System.Convert.FromBase64String(sello);
            if (sellado.Length != Rsa.KeyBytes(llavePublica.ToString()))
            {
                return(false);
            }
            sellado = Rsa.RawPublic(sellado, llavePublica.ToString());
            if (sellado.Length == 0)
            {
                return(false);
            }
            sellado = Rsa.DecodeDigestForSignature(sellado);
            if (sellado.Length == 0)
            {
                return(false);
            }
            return(String.Compare(Cnv.ToHex(sellado), Cnv.ToHex(digest), true) == 0);
        }
        public RSACryptoServiceProvider(KeySpec keySpec, bool genKey)
        {
            IntPtr prov   = IntPtr.Zero;
            IntPtr rsaKey = IntPtr.Zero;

            try
            {
                this.keySpec = keySpec;
                if (genKey == false)                //faster
                {
                    prov   = Context.AcquireContext("rSaContainer");
                    rsaKey = Key.GetUserKey(prov, keySpec);
                }
                else                 //new key
                {
                    prov = Context.AcquireContext("rSaContainerImp");
                    Calg calg = Calg.RSA_KEYX;
                    if (keySpec == KeySpec.SIGNATURE)
                    {
                        calg = Calg.RSA_SIGN;
                    }
                    rsaKey = Key.GenKey(prov, calg, GenKeyParam.EXPORTABLE);
                }
                byte [] baPrivKey = Key.ExportKey(rsaKey, IntPtr.Zero, KeyBlob.PRIVATEKEYBLOB);
                _rsa = new Rsa(baPrivKey);
            }
            finally
            {
                Key.DestroyKey(rsaKey);
                Context.ReleaseContext(prov);
            }
        }
示例#11
0
        private void btnCalcD_Click(object sender, EventArgs e)
        {
            var publicExponent = Convert.ToInt64(txtE.Text);
            var euler          = Convert.ToInt64(txtEuler.Text);
            var result         = Rsa.CalculatePrivateExponent(publicExponent, euler);
            var i = 0;

            while ((result <= 0 || result == publicExponent) && i < 5000)
            {
                publicExponent = Rsa.GeneralPublicExponent(Convert.ToInt64(txtEuler.Text), int.Parse(txtMin.Text));
                if (publicExponent > 1)
                {
                    result = Rsa.CalculatePrivateExponent(publicExponent, euler);
                }
                i++;
            }
            if (result > 0)
            {
                txtE.Text = publicExponent.ToString();
                txtD.Text = result.ToString();
                if (i > 0)
                {
                    MessageBox.Show("Giá trị publicExponent ( số mũ công khai ) ban đầu không phù hợp nên đã được tính lại.", "Sự cố trong quá trình tính toán", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                }
            }
            else
            {
                MessageBox.Show("Không tính được giá trị publicExponent ( số mũ công khai ). Hãy chọn lại 2 số nguyên tố ban đầu", "Lỗi trong quá trình tính toán", MessageBoxButtons.OK, MessageBoxIcon.Error);
                txtQ.Text        = txtP.Text = "";
                btnCalcD.Enabled = btnCalcE.Enabled = false;
            }
        }
示例#12
0
        private void SendClientKeyExchange()
        {
            var preMasterSecret = TLS12.GetPreMasterSecret();

            _session.MasterSecret = TLS12.GetMasterSecret(preMasterSecret, _session.ClientRandom, _session.ServerRandom);
            var clientKeyExchange = new ClientKeyExchange
            {
                SessionId       = _session.Id,
                PreMasterSecret = preMasterSecret
            };
            var serverRsa = Rsa.CreateFromPublicPEM(_session.RSAPublicPem);
            var request   = new SecurityLayerMessage
            {
                Type = SecurityMessageType.ClientKeyExchange,
                Data = serverRsa.Encrypt(_serializer.Serialize <ClientKeyExchange>(clientKeyExchange))
            };
            var requestBytes = _serializer.Serialize <SecurityLayerMessage>(request);

            Send(requestBytes);

            var responseBytes  = Receive();
            var message        = _serializer.Deserialize <SecurityLayerMessage>(responseBytes);
            var serverFinished = _serializer.Deserialize <ServerFinished>(message.Data);

            _session.Id = serverFinished.SessionId;
            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;
        }
示例#13
0
        public void DoHandshake(string signedPrime, string signedGenerator)
        {
            if (IsInitiator)
            {
                return;
            }

            byte[] signedPrimeAsBytes = HexToBytes(signedPrime);
            Rsa.Verify(ref signedPrimeAsBytes);

            byte[] signedGeneratorAsBytes = HexToBytes(signedGenerator);
            Rsa.Verify(ref signedGeneratorAsBytes);

            DhPrime     = new BigInteger(Encoding.Default.GetString(signedPrimeAsBytes), 10);
            DhGenerator = new BigInteger(Encoding.Default.GetString(signedGeneratorAsBytes), 10);

            if (DhPrime <= 2)
            {
                throw new Exception("Prime cannot be <= 2!\nPrime: " + DhPrime);
            }
            if (DhGenerator >= DhPrime)
            {
                throw new Exception(string.Format("Generator cannot be >= Prime!\nPrime: {0}\nGenerator: {1}", DhPrime, DhGenerator));
            }

            DhPrivate = new BigInteger(RandomHex(30), _bitSize);
            DhPublic  = DhGenerator.ModPow(DhPrivate, DhPrime);
        }
示例#14
0
        /// <summary>
        ///     When a client connects, assign them a unique RSA keypair for handshake.
        /// </summary>
        /// <param name="clientSocket"></param>
        private static void HandleConnect(WebSocket clientSocket)
        {
            var        connectionId = CookieManager.GetConnectionId(clientSocket);
            AuthClient authClient;

            AllClients.TryGetValue(connectionId, out authClient);
            if (authClient != null)
            {
                MessageQueueManager manager;
                //check if a manager for that port exist, if not, create one
                if (!authClient.MessageQueueManagers.TryGetValue(clientSocket.LocalEndpoint.Port, out manager))
                {
                    if (authClient.MessageQueueManagers.TryAdd(clientSocket.LocalEndpoint.Port,
                                                               new MessageQueueManager()))
                    {
                        Console.WriteLine("Manager started for " + clientSocket.LocalEndpoint.Port);
                    }
                }
                return;
            }
            Console.WriteLine("Connection from " + clientSocket.RemoteEndpoint);
            var rsa = new Rsa();

            rsa.GenerateKeyPairs();
            var client = new AuthClient
            {
                PublicKey            = rsa.PublicKey,
                PrivateKey           = rsa.PrivateKey,
                MessageQueueManagers = new ConcurrentDictionary <int, MessageQueueManager>()
            };

            client.MessageQueueManagers.TryAdd(clientSocket.LocalEndpoint.Port, new MessageQueueManager());
            AllClients.AddOrUpdate(connectionId, client, (key, value) => value);
            SendWelcomeMessage(client, clientSocket);
        }
示例#15
0
        public void CheckSanity()
        {
            // Get some bignum parameters
            BigNumber p1, q1, gcd, lambda;

            p1     = Rsa.SecretPrimeFactorP - 1; // p-1
            q1     = Rsa.SecretPrimeFactorQ - 1; // q-1
            gcd    = BigNumber.gcd(p1, q1);      // gcd of (p-1)(q-1)
            lambda = BigNumber.lcm(p1, q1, gcd); // lcm of (p-1)(q-1)

            // Check for sanity
            if (BigNumber.gcd(lambda, Rsa.PublicExponent) != 1) // check if e is coprime to lambda(n)
            {
                throw new Exception("Key not sane - e and lcm not coprime");
            }
            if (!(Rsa.PublicExponent < Rsa.PublicModulus - 1))
            {
                throw new Exception("Key not sane - not (e < n-1)");
            }

            // Ask OpenSSL if it's sane
            if (!Rsa.Check())
            {
                throw new Exception("Key not sane - openssl says so");
            }
        }
 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)));
 }
示例#17
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);
 }
示例#18
0
        public void Setup()
        {
            var shaFactory     = new NativeShaFactory();
            var hmacFactory    = new HmacFactory(shaFactory);
            var entropyFactory = new EntropyProviderFactory();
            var rsa            = new Rsa(new RsaVisitor());

            var kdfVisitor = new KdfVisitor(
                new KdfOneStepFactory(shaFactory, new HmacFactory(shaFactory), new KmacFactory(new CSHAKEWrapper())),
                new Crypto.KDF.KdfFactory(new CmacFactory(new BlockCipherEngineFactory(), new ModeBlockCipherFactory()),
                                          hmacFactory), hmacFactory,
                new CmacFactory(new BlockCipherEngineFactory(), new ModeBlockCipherFactory()),
                new IkeV1Factory(hmacFactory, shaFactory),
                new IkeV2Factory(hmacFactory),
                new TlsKdfFactory(hmacFactory),
                new HkdfFactory(hmacFactory));

            _rsaSve = new RsaSve(rsa, _entropyProvider);

            _kasBuilderPartyU    = new KasIfcBuilder();
            _schemeBuilderPartyU = new SchemeIfcBuilder(kdfVisitor);

            _kasBuilderPartyV    = new KasIfcBuilder();
            _schemeBuilderPartyV = new SchemeIfcBuilder(kdfVisitor);

            _secretKeyingMaterialBuilderPartyU = new IfcSecretKeyingMaterialBuilder();
            _secretKeyingMaterialBuilderPartyV = new IfcSecretKeyingMaterialBuilder();

            _kdfFactory             = new KdfFactory(kdfVisitor);
            _kdfParameterVisitor    = new KdfParameterVisitor(entropyFactory.GetEntropyProvider(EntropyProviderTypes.Random));
            _ktsFactory             = new KtsFactory(shaFactory, rsa, entropyFactory);
            _keyConfirmationFactory = new KeyConfirmationFactory(new KeyConfirmationMacDataCreator());
            _fixedInfoFactory       = new FixedInfoFactory(new FixedInfoStrategyFactory());
        }
示例#19
0
        public static void CreateKey()
        {
            Global glob = new Global();

            glob.UnlockBundle("Anything for 30-day trial");

            SshKey key    = new SshKey();
            Rsa    rsaKey = new Rsa();

            rsaKey.GenerateKey(1024);
            _privateKey = rsaKey.ExportPrivateKeyObj();
            Console.WriteLine("Private Key: " + rsaKey.ExportPrivateKey());
            _publicKey = rsaKey.ExportPublicKey();
            Console.WriteLine("Public Key: " + _publicKey);
            using (ConsulClient consulClient = new ConsulClient())
            {
                String url = Constants.BASE_URL + ":" + Constants.CONSUL_PORT;
                Console.WriteLine("Consul URL: " + url);
                consulClient.Config.Address = new Uri(url);
                var putPair = new KVPair("publickey")
                {
                    Value = Encoding.UTF8.GetBytes(_publicKey)
                };
                var putAttempt = consulClient.KV.Put(putPair).Result;
                Console.WriteLine("Put Result: " + JsonConvert.SerializeObject(putAttempt));
            }
            _isCreated = true;
        }
示例#20
0
        public Server(ISerializer serializer, string serverUri)
        {
            _serializer   = serializer;
            _rsa          = Rsa.Create();
            _sessionCache = new SessionCache();
            _socket       = new ResponseSocket();
            _socket.Bind(serverUri);

            while (true)
            {
                var messageBytes = _socket.ReceiveFrameBytes();
                var message      = _serializer.Deserialize <SecurityLayerMessage>(messageBytes);
                switch (message.Type)
                {
                case SecurityMessageType.ClientHello:
                    HandleClientHello(message.Data);
                    break;

                case SecurityMessageType.ClientKeyExchange:
                    HandleClientKeyExchange(message.Data);
                    break;

                case SecurityMessageType.ApplicationData:
                    HandleApplicationData(message.Data);
                    break;
                }
            }
        }
示例#21
0
        public static void Main(string[] args)
        {
            int p = 5, q = 7;
            int n  = p * q;
            int fi = (p - 1) * (q - 1);
            int e  = Rsa.CalculateE(fi);

            var openKey = Rsa.GenerateOpenKey(n, fi);

            Console.WriteLine(openKey.e + " " + openKey.n);

            int d         = Rsa.CalculateD(e, fi);
            var secretKey = Rsa.GenerateSecretKey(n, d);

            Console.WriteLine(secretKey.e + " " + secretKey.n);

            var encodedMessage = Rsa.Encode(5, openKey.e, openKey.n);

            Console.WriteLine(encodedMessage);

            var decodedMessage = Rsa.Decode(encodedMessage, secretKey.e, secretKey.n);

            Console.WriteLine(decodedMessage);

            var secretKey2 = Rsa.GenerateSecretKeyByOpen(openKey);

            Console.WriteLine(secretKey2.e + " " + secretKey2.n);
            Console.ReadKey();
        }
示例#22
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);
        }
示例#23
0
        public static void V_Test_CMS_MakeSigData()
        {
            Console.WriteLine("Testing CMS_MakeSigData ...");
            string        strPriKeyFile = null;
            StringBuilder sbPrivateKey  = null;
            //'Dim nIntKeyLen As Integer
            int    nRet          = 0;
            string strInputFile  = null;
            string strOutputFile = null;
            string strCertFile   = null;

            strPriKeyFile = "myuser.epk";
            strCertFile   = "myuser.cer";
            strInputFile  = "excontent.txt";
            strOutputFile = "BasicSignBy_myuser.bin";

            // First we need to read in the private key string
            // NB: This version is not encrypted
            sbPrivateKey = Rsa.ReadEncPrivateKey(strPriKeyFile, "password");
            Console.WriteLine("nIntKeyLen = " + sbPrivateKey.Length);
            if (sbPrivateKey.Length == 0)
            {
                Console.WriteLine(General.LastError());
                Console.WriteLine("Unable to retrieve private key");
                return;
            }
            Console.WriteLine("Key size=" + Rsa.KeyBits(sbPrivateKey.ToString()) + " bits");

            // Now we can sign our message
            nRet = Cms.MakeSigData(strOutputFile, strInputFile, strCertFile, sbPrivateKey.ToString(), 0);
            Console.WriteLine("CMS_MakeSigData returns " + nRet);
        }
示例#24
0
        public static void SendMessage(string endpoint, object data, AuthClient authClient)
        {
            var serializer = new JavaScriptSerializer {
                MaxJsonLength = int.MaxValue
            };
            var json = serializer.Serialize(new
            {
                endpoint,
                results = data
            });

            try
            {
                if (authClient != null)
                {
                    if (authClient.AesShook)
                    {
                        var keyBytes      = Encoding.UTF8.GetBytes(Rsa.SecureStringToString(authClient.AesKey));
                        var keyIv         = Encoding.UTF8.GetBytes(Rsa.SecureStringToString(authClient.AesIv));
                        var encryptedData = UAes.Encrypt(json, keyBytes, keyIv);
                        json = Convert.ToBase64String(encryptedData);
                        Console.WriteLine("Message Encrypted");
                    }
                }
            }
            catch (Exception)
            {
                //TODO Handle
            }
            Push(authClient.Client, json);
        }
示例#25
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);
 }
示例#26
0
        /// <summary>
        ///     Decodes the <seealso cref="ChecksumTable" /> in the specified
        ///     <seealso cref="ByteBuffer" /> and decrypts the final whirlpool hash.
        /// </summary>
        /// <param name="buffer"> The <seealso cref="ByteBuffer" /> containing the table. </param>
        /// <param name="whirlpool"> If whirlpool digests should be read. </param>
        /// <param name="modulus"> The modulus. </param>
        /// <param name="publicKey"> The public key. </param>
        /// <returns> The decoded <seealso cref="ChecksumTable" />. </returns>
        /// <exception cref="IOException"> if an I/O error occurs. </exception>
        public static ChecksumTable Decode(ByteBuffer buffer, bool whirlpool, BigInteger modulus, BigInteger publicKey)
        {
            /* find out how many entries there are and allocate a new table */
            var size  = whirlpool ? (buffer.limit() / 8) : (buffer.get() & 0xFF);
            var table = new ChecksumTable(size);

            /* calculate the whirlpool digest we expect to have at the end */
            byte[] masterDigest = null;
            if (whirlpool)
            {
                var temp = new byte[size * 72 + 1];
                buffer.position(0);
                buffer.get(temp);
                masterDigest = Whirlpool.Crypt(temp, 0, temp.Length);
            }

            /* read the entries */
            buffer.position(1);
            for (var i = 0; i < size; i++)
            {
                var crc     = buffer.getInt();
                var version = buffer.getInt();
                var digest  = new byte[64];
                if (whirlpool)
                {
                    buffer.get(digest);
                }
                table.entries[i] = new Entry(crc, version, digest);
            }

            /* read the trailing digest and check if it matches up */
            if (whirlpool)
            {
                var bytes = new byte[buffer.remaining()];
                buffer.get(bytes);
                var temp = ByteBuffer.wrap(bytes);

                if (modulus != null && publicKey != null)
                {
                    temp = Rsa.Crypt(buffer, modulus, publicKey);
                }

                if (temp.limit() != 66)
                {
                    throw new IOException("Decrypted data is not 66 bytes long");
                }

                for (var i = 0; i < 64; i++)
                {
                    if (temp.get(i + 1) != masterDigest[i])
                    {
                        throw new IOException("Whirlpool digest mismatch");
                    }
                }
            }

            /* if it looks good return the table */
            return(table);
        }
示例#27
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);
            }
        }
示例#28
0
        /// <summary>
        ///     Writes a message, either encrypted or plain text to the message queue
        /// </summary>
        /// <param name="data"></param>
        public void WriteMessage(object data)
        {
            if (_client != null && data != null)
            {
                var host = new Uri($"ws://{_client.HttpRequest.Headers[RequestHeader.Host]}", UriKind.Absolute);
                JsonSerializerSettings settings = new JsonSerializerSettings {
                    ContractResolver = new MessageResolver()
                };

                var json = JsonConvert.SerializeObject(new
                {
                    endpoint = Endpoint,
                    synckey,
                    results = data
                }, settings);


                try
                {
                    if (_authClient != null)
                    {
                        if (_authClient.AesShook)
                        {
                            var keyBytes = Encoding.UTF8.GetBytes(Rsa.SecureStringToString(_authClient.AesKey));
                            var keyIv    = Encoding.UTF8.GetBytes(Rsa.SecureStringToString(_authClient.AesIv));

                            var encryptedData = Encrypt(Encoding.UTF8.GetBytes(json), keyBytes, keyIv);
                            using (var memoryStream = new MemoryStream())
                            {
                                using (var binaryWriter = new BinaryWriter(memoryStream))
                                {
                                    binaryWriter.Write(Endpoint.Length);
                                    binaryWriter.Write(Encoding.UTF8.GetBytes(Endpoint));
                                    binaryWriter.Write(Encoding.UTF8.GetBytes(EncryptionType.CBC.ToString()));
                                    binaryWriter.Write(encryptedData);
                                }
                                var message    = new Message(_client, memoryStream.ToArray(), Message.MessageType.Binary);
                                var targetPort = host.Port;
                                _authClient?.MessageQueueManagers[targetPort]?.SendQueue.Add(message);
                            }
                            return;
                        }
                    }
                }
                catch (Exception e)
                {
                    Console.WriteLine($"Could not send encrypted message: {e.Message}");
                    Console.WriteLine(e.StackTrace);
                    return;
                }
                var jsonMessage = new Message(_client, json, Message.MessageType.Text);
                if (_authClient != null)
                {
                    var targetPort = host.Port;
                    _authClient?.MessageQueueManagers[targetPort]?.SendQueue.Add(jsonMessage);
                }
            }
        }
示例#29
0
        private static KeySet CreateKeySet()
        {
            var keySet = new KeySet();

            // Populate the key set with all the keys in IncludedKeys.txt
            using (Stream keyFile = GetResource(InputMainKeyFileName))
            {
                List <KeyInfo> list = KeySet.CreateKeyInfoList();
                ExternalKeyReader.ReadMainKeys(keySet, keyFile, list);
            }

            // Recover all the RSA key parameters and write the key to the key set
            RSAParameters betaNca0Params =
                Rsa.RecoverParameters(BetaNca0Modulus, StandardPublicExponent, BetaNca0Exponent);

            betaNca0Params.D.AsSpan().CopyTo(keySet.BetaNca0KeyAreaKey.PrivateExponent.Data);
            betaNca0Params.DP.AsSpan().CopyTo(keySet.BetaNca0KeyAreaKey.Dp.Data);
            betaNca0Params.DQ.AsSpan().CopyTo(keySet.BetaNca0KeyAreaKey.Dq.Data);
            betaNca0Params.Exponent.AsSpan().CopyTo(keySet.BetaNca0KeyAreaKey.PublicExponent.Data);
            betaNca0Params.InverseQ.AsSpan().CopyTo(keySet.BetaNca0KeyAreaKey.InverseQ.Data);
            betaNca0Params.Modulus.AsSpan().CopyTo(keySet.BetaNca0KeyAreaKey.Modulus.Data);
            betaNca0Params.P.AsSpan().CopyTo(keySet.BetaNca0KeyAreaKey.P.Data);
            betaNca0Params.Q.AsSpan().CopyTo(keySet.BetaNca0KeyAreaKey.Q.Data);

            // First populate the prod RSA keys
            keySet.SetMode(KeySet.Mode.Prod);

            StandardPublicExponent.CopyTo(keySet.NcaHeaderSigningKeys[0].PublicExponent.Data);
            StandardPublicExponent.CopyTo(keySet.NcaHeaderSigningKeys[1].PublicExponent.Data);
            NcaHdrFixedKeyModulus0Prod.CopyTo(keySet.NcaHeaderSigningKeys[0].Modulus.Data);
            NcaHdrFixedKeyModulus1Prod.CopyTo(keySet.NcaHeaderSigningKeys[1].Modulus.Data);

            StandardPublicExponent.CopyTo(keySet.AcidSigningKeys[0].PublicExponent.Data);
            StandardPublicExponent.CopyTo(keySet.AcidSigningKeys[1].PublicExponent.Data);
            AcidFixedKeyModulus0Prod.CopyTo(keySet.AcidSigningKeys[0].Modulus.Data);
            AcidFixedKeyModulus1Prod.CopyTo(keySet.AcidSigningKeys[1].Modulus.Data);

            StandardPublicExponent.CopyTo(keySet.Package2SigningKey.PublicExponent.Data);
            Package2FixedKeyModulusProd.CopyTo(keySet.Package2SigningKey.Modulus.Data);

            // Populate the dev RSA keys
            keySet.SetMode(KeySet.Mode.Dev);

            StandardPublicExponent.CopyTo(keySet.NcaHeaderSigningKeys[0].PublicExponent.Data);
            StandardPublicExponent.CopyTo(keySet.NcaHeaderSigningKeys[1].PublicExponent.Data);
            NcaHdrFixedKeyModulus0Dev.CopyTo(keySet.NcaHeaderSigningKeys[0].Modulus.Data);
            NcaHdrFixedKeyModulus1Dev.CopyTo(keySet.NcaHeaderSigningKeys[1].Modulus.Data);

            StandardPublicExponent.CopyTo(keySet.AcidSigningKeys[0].PublicExponent.Data);
            StandardPublicExponent.CopyTo(keySet.AcidSigningKeys[1].PublicExponent.Data);
            AcidFixedKeyModulus0Dev.CopyTo(keySet.AcidSigningKeys[0].Modulus.Data);
            AcidFixedKeyModulus1Dev.CopyTo(keySet.AcidSigningKeys[1].Modulus.Data);

            StandardPublicExponent.CopyTo(keySet.Package2SigningKey.PublicExponent.Data);
            Package2FixedKeyModulusDev.CopyTo(keySet.Package2SigningKey.Modulus.Data);

            return(keySet);
        }
示例#30
0
    internal static DigitalSignature smethod_0(BinaryReader A_0, byte[] A_1)
    {
        bool             flag;
        int              num       = 8;
        DigitalSignature signature = new DigitalSignature(DigitalSignatureType.CryptoApi);

        try
        {
            int num2 = A_0.ReadInt32();
            int num3 = A_0.ReadInt32();
            smethod_1(A_0);
            uint num4     = A_0.ReadUInt32();
            uint num5     = A_0.ReadUInt32();
            long fileTime = num4;
            fileTime  = fileTime << 0x20;
            fileTime |= num5;
            signature.method_0(DateTime.FromFileTimeUtc(fileTime));
            A_0.ReadInt32();
            int count = A_0.ReadInt32();
            int num8  = A_0.ReadInt32();
            A_0.ReadInt32();
            int num9  = A_0.ReadInt32();
            int num10 = A_0.ReadInt32();
            A_0.ReadInt32();
            Class1029.smethod_5(A_0, (num2 + 1) * 2);
            Class1029.smethod_5(A_0, (num3 + 1) * 2);
            byte[] array   = A_0.ReadBytes(count);
            byte[] rawData = A_0.ReadBytes(num8);
            A_0.ReadBytes(num9);
            A_0.ReadBytes(num10);
            if (num8 == 0)
            {
                throw new InvalidOperationException(BookmarkStart.b("稭堯圱䘳匵ᠷ匹伻ḽ⸿ⵁ摃╅ⵇ㡉㡋❍㙏㭑㝓㝕ⱗ㽙籛㭝ൟaţɥ౧ཀྵ࡫乭ᙯᵱٳ噵᥷婹᡻᝽ꪉヒﲑ鍊낝", num));
            }
            X509Certificate2 certificate = new X509Certificate2(rawData);
            signature.method_3(certificate);
            RSAParameters parameters = ((RSACryptoServiceProvider)certificate.PublicKey.Key).ExportParameters(false);
            Array.Reverse(array);
            byte[] buffer3          = Class1078.smethod_0(array);
            Rsa    rsa              = new Rsa(parameters.Modulus, parameters.Exponent);
            byte[] sourceArray      = Class1078.smethod_1(Class1078.smethod_2(rsa, buffer3), rsa.Modulus.method_0() >> 3);
            byte[] destinationArray = new byte[0x10];
            Array.Copy(sourceArray, sourceArray.Length - 0x10, destinationArray, 0, 0x10);
            MD5 md = new MD5();
            md.Update(A_1, A_1.Length);
            md.Update(BitConverter.GetBytes(num5), 4);
            md.Update(BitConverter.GetBytes(num4), 4);
            md.FinalUpdate();
            flag = Class85.smethod_1(destinationArray, md.Digest);
        }
        catch (Exception)
        {
            flag = false;
        }
        signature.method_2(flag);
        return(signature);
    }
示例#31
0
        public Result VerifySignature(ReadOnlySpan <byte> modulus, ReadOnlySpan <byte> data)
        {
            if (!Rsa.VerifyRsa2048PssSha256(Signature, modulus, RsaPublicKeyExponent, data))
            {
                return(ResultLibHac.InvalidPackage2HeaderSignature.Log());
            }

            return(Result.Success);
        }
示例#32
0
        public override Day Run()
        {
            dayOfMonth = 25;
            stopwatch.Start();
            Rsa rsa = new Rsa(20201227);

            answer_part1 = rsa.FindEncryptionKeyFromFile("input/day25.txt").ToString();
            return(this);
        }
        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);
        }
 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)));
 }