ToHexString() public method

public ToHexString ( ) : string
return string
Ejemplo n.º 1
0
        public string InternalsToString()
        {
            string type = IsServer ? "server" : "client";
            string str  = string.Format("SRP {0} Internals:\n", type);

            str += string.Format("G      = {0}\n", Generator.ToHexString());
            str += string.Format("K      = {0}\n", Multiplier.ToHexString());
            str += string.Format("N      = {0}\n", Modulus.ToHexString());

            str += string.Format("I      = '{0}'\n", Credentials);
            str += string.Format("Hash(I)= {0}\n", Hash(Credentials).ToHexString());
            str += string.Format("X      = {0}\n", CredentialsHash.ToHexString());
            str += string.Format("V      = {0}\n", Verifier.ToHexString());
            if (m_salt != null)
            {
                str += string.Format("Salt   = {0}\n", Salt.ToHexString());
            }
            if (null != m_publicEphemeralValueA && null != m_publicEphemeralValueB)
            {
                str += string.Format("u      = {0}\n", ScramblingParameter.ToHexString());
                str += string.Format("h(A)   = {0}\n", Hash(PublicEphemeralValueA).ToHexString());
                str += string.Format("h(B)   = {0}\n", Hash(PublicEphemeralValueB.GetBytes()).ToHexString());
            }

            if (IsServer == false || PublicEphemeralValueA != null)
            {
                str += string.Format("A      = {0}\n", PublicEphemeralValueA.ToHexString());
            }
            if (IsServer || PublicEphemeralValueB != null)
            {
                str += string.Format("B      = {0}\n", PublicEphemeralValueB.ToHexString());
                BigInteger tmp = Multiplier * Generator.ModPow(CredentialsHash, Modulus);
                str += string.Format("kg^x   = {0}\n", tmp.ToHexString());
                tmp  = PublicEphemeralValueB - tmp % Modulus;
                if (tmp < 0)
                {
                    tmp += Modulus;
                }
                str += string.Format("B-kg^x = {0}\n", tmp.ToHexString());
            }

            try
            {
                str += string.Format("S.key  = {0}\n", SessionKey.ToHexString());
            }
            catch
            {
                str += "S.key  = empty\n";
            }

            return(str);
        }
Ejemplo n.º 2
0
            public static void AuthStep2(
                string vHex,
                string uHex,
                string AHex,
                string bHex,
                string BHex,
                out string m1serverHex,
                out string m2Hex)
            {
                BigInteger v = new BigInteger(vHex, 16);
                BigInteger u = new BigInteger(uHex, 16);
                BigInteger A = new BigInteger(AHex, 16);
                BigInteger b = new BigInteger(bHex, 16);
                BigInteger B = new BigInteger(BHex, 16);

                // S - common exponential value
                // S = (A * v^u) ^ b (mod N)
                BigInteger S = ((v.modPow(u, N) * A) % N).modPow(b, N);

                // K - the strong cryptographically session key
                // K = H(S)
                string KHex = HHex(S.ToHexString()).TrimStart('0');

                // m2 - expected client's proof as computed by the server
                m1serverHex = HHex(
                    AHex +
                    BHex +
                    KHex).TrimStart('0');

                // m2 - server's proof that it has the correct key
                m2Hex = HHex(
                    AHex +
                    m1serverHex +
                    KHex).TrimStart('0');
            }
        //подписываем сообщение
        public string SignGen(byte[] h, BigInteger d)
        {
            BigInteger alpha = new BigInteger(h);
            BigInteger e     = alpha % n;

            if (e == 0)
            {
                e = 1;
            }
            BigInteger k = new BigInteger();
            ECPoint    C = new ECPoint();
            BigInteger r = new BigInteger();
            BigInteger s = new BigInteger();

            do
            {
                do
                {
                    k.genRandomBits(n.bitCount(), new Random());
                } while ((k < 0) || (k > n));
                C = ECPoint.multiply(k, G);
                r = C.x % n;
                s = ((r * d) + (k * e)) % n;
            } while ((r == 0) || (s == 0));
            string Rvector = padding(r.ToHexString(), n.bitCount() / 4);
            string Svector = padding(s.ToHexString(), n.bitCount() / 4);

            return(Rvector + Svector);
        }
Ejemplo n.º 4
0
        /// <summary>
        /// Verifies that the server's proof value matches the value
        /// calculated by the client.
        /// </summary>
        /// <param name="serverProof">The 20-byte server proof.</param>
        /// <exception cref="ArgumentOutOfRangeException">Thrown if
        /// the server proof value is not exactly 20 bytes.</exception>
        /// <exception cref="InvalidOperationException">Thrown if the object has not
        /// yet been initialized.</exception>
        /// <remarks>
        /// This method should be called after the <see cref="LoginProof(byte[], int, int, byte[], byte[])">LoginProof</see> method.
        /// </remarks>
        /// <returns><b>True</b> if the server proof is valid;
        /// otherwise <b>false</b>.</returns>
        public bool VerifyServerProof(byte[] serverProof)
        {
            if (serverProof.Length != 20)
            {
                throw new ArgumentOutOfRangeException(Resources.nlsServerProof20);
            }

            MemoryStream ms_m2 = new MemoryStream(92);
            BinaryWriter bw    = new BinaryWriter(ms_m2);

            bw.Write(EnsureArrayLength(A.GetBytes(), 32));
            bw.Write(m1.GetBytes());
            bw.Write(k);
            byte[] client_m2_data = ms_m2.GetBuffer();
            ms_m2.Close();

            byte[]     client_hash_m2 = s_sha.ComputeHash(client_m2_data);
            BigInteger client_m2      = new BigInteger(client_hash_m2);
            BigInteger server_m2      = new BigInteger(serverProof);

#if DEBUG
            Trace.WriteLine(client_m2.ToHexString(), "Client");
            Trace.WriteLine(server_m2.ToHexString(), "Server");
#endif

            return(client_m2.Equals(server_m2));
        }
Ejemplo n.º 5
0
        /// <summary>
        /// Generates the server request and return the A key.
        /// </summary>
        public String GenerateRequest()
        {
            a = BigInteger.genPseudoPrime(256, 30, new Random());
            A = g.modPow(a, p);

            return(A.ToHexString());
        }
Ejemplo n.º 6
0
 /// <summary>
 /// 用指定的密匙加密 
 /// </summary>
 /// <param name="source">明文</param>
 /// <param name="d">可以是RSACryptoServiceProvider生成的D</param>
 /// <param name="n">可以是RSACryptoServiceProvider生成的Modulus</param>
 /// <returns>返回密文</returns>
 private static string EncryptString(string source, BigInteger d, BigInteger n)
 {
     int len = source.Length;
     int len1 = 0;
     int blockLen = 0;
     if ((len % 128) == 0)
         len1 = len / 128;
     else
         len1 = len / 128 + 1;
     string block = "";
     StringBuilder result = new StringBuilder();
     for (int i = 0; i < len1; i++)
     {
         if (len >= 128)
             blockLen = 128;
         else
             blockLen = len;
         block = source.Substring(i * 128, blockLen);
         byte[] oText = System.Text.Encoding.Default.GetBytes(block);
         BigInteger biText = new BigInteger(oText);
         BigInteger biEnText = biText.modPow(d, n);
         string temp = biEnText.ToHexString();
         result.Append(temp).Append("@");
         len -= blockLen;
     }
     return result.ToString().TrimEnd('@');
 }
Ejemplo n.º 7
0
        private void LoginButton_Click(object sender, EventArgs e)
        {
            if (isRigistred)
            {
                srpServer         = new Srp6(identityHash, modulus, Generator, salt.ToHexString(), ScramblerBitLength);
                saltTextBox.Text  = srpServer.Salt.ToHexString();
                saltTextBox2.Text = srpServer.Salt.ToHexString();
                byte[] identityHashLogin = Encoding.Unicode.GetBytes((LoginUsernameTextBox.Text + ":" + LoginPasswordTextBox.Text)).Sha1Hash();
                srpClient = new Srp6(identityHashLogin, modulus, Generator, srpServer.Salt.ToHexString());
                srpClient.SetSessionKey(srpServer.PublicKey.ToHexString(), srpServer.Scrambler.ToHexString());
                srpServer.SetSessionKey(srpClient.PublicKey.ToHexString());

                secretATextBox.Text            = srpClient.PrivateKey.ToHexString();
                openATextBox.Text              = srpClient.PublicKey.ToHexString();
                saltTextBox2.Text              = srpServer.Salt.ToHexString();
                clientScramberTextBox.Text     = srpClient.Scrambler.ToHexString();
                KeyOfSessionClientTextBox.Text = srpClient.SessionKey.ToHexString();

                secretBTextBox.Text = srpServer.PrivateKey.ToHexString();
                openBTextBox.Text   = srpServer.PublicKey.ToHexString();

                serverScramberTextBox.Text     = srpServer.Scrambler.ToHexString();
                KeyOfSessionServerTextBox.Text = srpServer.SessionKey.ToHexString();
            }
        }
Ejemplo n.º 8
0
        /// <summary>
        /// Verifies that the server's proof value matches the value
        /// calculated by the client.
        /// </summary>
        /// <param name="serverProof">The 20-byte server proof.</param>
        /// <exception cref="ArgumentOutOfRangeException">Thrown if
        /// the server proof value is not exactly 20 bytes.</exception>
        /// <exception cref="InvalidOperationException">Thrown if the object has not
        /// yet been initialized.</exception>
        /// <remarks>
        /// This method should be called after the <see cref="LoginProof(byte[], int, int, byte[], byte[])">LoginProof</see> method.
        /// </remarks>
        /// <returns><b>True</b> if the server proof is valid;
        /// otherwise <b>false</b>.</returns>
        public bool VerifyServerProof(byte[] serverProof)
        {
            if (serverProof.Length != 20)
            {
                throw new ArgumentOutOfRangeException("Server proof must be exactly 20 bytes.");
            }

            using (MemoryStream ms_m2 = new MemoryStream(92))
            {
                BinaryWriter bw = new BinaryWriter(ms_m2);
                bw.Write(EnsureArrayLength(A.ToByteArray(), 32));
                bw.Write(m1.ToByteArray());
                bw.Write(k);
                byte[] client_m2_data = ms_m2.GetBuffer();
                ms_m2.Close();

                byte[]     client_hash_m2 = s_sha.ComputeHash(client_m2_data);
                BigInteger client_m2      = new BigInteger(client_hash_m2);
                BigInteger server_m2      = new BigInteger(serverProof);

                Debug.WriteLine(client_m2.ToHexString(), "Client");
                Debug.WriteLine(server_m2.ToHexString(), "Server");

                return(client_m2.Equals(server_m2));
            }
        }
Ejemplo n.º 9
0
        // This assumes MAX_LENGTH of BigInteger is 70
        public void TestToHexString()
        {
            BigInteger bi;

            byte[] buffer = new byte[8];
            long   val;
            string valHexString;

            Random rand = new Random();

            for (int i = 0; i < 100; i++)
            {
                rand.NextBytes(buffer);
                val = BitConverter.ToInt64(buffer, 0);

                bi = new BigInteger(val);


                valHexString = val.ToString("X");
                if (val < 0)
                {
                    while (valHexString.Length < 8 * 70)
                    {
                        valHexString = "F" + valHexString;
                    }
                }

                Assert.AreEqual(valHexString, bi.ToHexString());
            }

            // Test on big number
            bi = new BigInteger("9329857983749832748932749873298479328748923759347985734985739749327498327492387498237498237493794872394723947923749823759347598475983475943759843759834759834759374975984375984375934759437593", 10);
            Assert.AreEqual("86042e915cdcf19902845ddf57c6b604685c53a01da858573f52219e1c743fc193e5b56aaba29ef308a82cd26da8066d1ae2af170b1443f3b539938966107f8f77263e4f13fb815049d5f746438519".ToUpper(),
                            bi.ToHexString());
        }
Ejemplo n.º 10
0
    public string RSADecryptStr(string str)
    {
        string     temp   = Encoding.Default.GetString(Convert.FromBase64String(str));
        BigInteger b_data = new BigInteger(temp, 16);

        b_data = b_data.modPow(m_d, m_n);
        return(HexToStr(b_data.ToHexString()));
    }
Ejemplo n.º 11
0
    public string RSAEncryptStr(string str)
    {
        string     temp   = StrToHex(str);
        BigInteger b_data = new BigInteger(temp, 16);

        b_data = b_data.modPow(m_e, m_n);
        return(Convert.ToBase64String(Encoding.Default.GetBytes(b_data.ToHexString())));
    }
        private byte[] EncryptString(string strData, string strkeyNum, string strnNum)
        {
            BigInteger exp = new BigInteger(strkeyNum, 16);
            BigInteger n   = new BigInteger(strnNum, 16);

            byte[] bytes = Encoding.UTF8.GetBytes(strData);
            int    num   = bytes.Length;
            int    num2;

            if (num % 120 == 0)
            {
                num2 = num / 120;
            }
            else
            {
                num2 = num / 120 + 1;
            }
            ArrayList arrayList = new ArrayList();

            for (int i = 0; i < num2; i++)
            {
                int num3;
                if (num >= 120)
                {
                    num3 = 120;
                }
                else
                {
                    num3 = num;
                }
                byte[] array = new byte[num3];
                Array.Copy(bytes, i * 120, array, 0, num3);
                Encoding.UTF8.GetString(array);
                BigInteger bigInteger  = new BigInteger(array);
                BigInteger bigInteger2 = bigInteger.modPow(exp, n);
                string     text        = bigInteger2.ToHexString();
                if (text.Length < 256)
                {
                    while (text.Length != 256)
                    {
                        text = "0" + text;
                    }
                }
                byte[] array2 = new byte[128];
                for (int j = 0; j < array2.Length; j++)
                {
                    array2[j] = Convert.ToByte(text.Substring(j * 2, 2), 16);
                }
                arrayList.AddRange(array2);
                num -= num3;
            }
            byte[] array3 = new byte[arrayList.Count];
            for (int k = 0; k < arrayList.Count; k++)
            {
                array3[k] = (byte)arrayList[k];
            }
            return(array3);
        }
Ejemplo n.º 13
0
        public string RSAEncrypt(string a)
        {
            BigInteger tmp = pkcs1pad2(a, (n.bitCount() + 7) >> 3);

            tmp = RSADoPublic(tmp);
            string result = tmp.ToHexString();

            return(0 == (result.Length & 1) ? result : "0" + result);
        }
Ejemplo n.º 14
0
        public string Encrypt(string a)
        {
            BigInteger tmp = AE(a, (Modulus.bitCount() + 7) >> 3);

            tmp = RSADoPublic(tmp);
            string result = tmp.ToHexString();

            return((result.Length & 1) == 0 ? result : "0" + result);
        }
Ejemplo n.º 15
0
        /// <inheritdoc />
        public async Task <Block> GetBlockAsync(
            BigInteger blockNumber,
            bool includeTransactions)
        {
            var requestParams = new object[] { $"{blockNumber.ToHexString()}", includeTransactions };
            var request       = new RpcRequest("eth_getBlockByNumber", requestParams);
            var response      = await SendRpcRequestAsync(request);

            return(GetBlock(response, includeTransactions));
        }
Ejemplo n.º 16
0
        /// <summary>
        /// Generates the client response and the S key with the A key.
        /// The B key will be returned.
        /// </summary>
        public String GenerateResponse(String PubKey)
        {
            b = BigInteger.genPseudoPrime(256, 30, new Random());
            B = g.modPow(b, p);

            A = new BigInteger(PubKey, 16);
            s = A.modPow(b, p);

            return(B.ToHexString());
        }
Ejemplo n.º 17
0
        public string InternalsToString()
        {
            string str1 = string.Format("SRP {0} Internals:\n", this.IsServer ? (object)"server" : (object)"client") +
                          string.Format("G      = {0}\n", (object)this.Generator.ToHexString()) +
                          string.Format("K      = {0}\n", (object)this.Multiplier.ToHexString()) +
                          string.Format("N      = {0}\n", (object)this.Modulus.ToHexString()) +
                          string.Format("I      = '{0}'\n", (object)this.Credentials) +
                          string.Format("Hash(I)= {0}\n",
                                        (object)this.Hash((HashUtilities.HashDataBroker) this.Credentials).ToHexString()) +
                          string.Format("X      = {0}\n", (object)this.CredentialsHash.ToHexString()) +
                          string.Format("V      = {0}\n", (object)this.Verifier.ToHexString());

            if (this.m_salt != (BigInteger)null)
            {
                str1 += string.Format("Salt   = {0}\n", (object)this.Salt.ToHexString());
            }
            if ((BigInteger)null != this.m_publicEphemeralValueA && (BigInteger)null != this.m_publicEphemeralValueB)
            {
                str1 = str1 + string.Format("u      = {0}\n", (object)this.ScramblingParameter.ToHexString()) +
                       string.Format("h(A)   = {0}\n",
                                     (object)this.Hash((HashUtilities.HashDataBroker) this.PublicEphemeralValueA)
                                     .ToHexString()) + string.Format("h(B)   = {0}\n",
                                                                     (object)this.Hash((HashUtilities.HashDataBroker) this.PublicEphemeralValueB.GetBytes())
                                                                     .ToHexString());
            }
            if (!this.IsServer || this.PublicEphemeralValueA != (BigInteger)null)
            {
                str1 += string.Format("A      = {0}\n", (object)this.PublicEphemeralValueA.ToHexString());
            }
            if (this.IsServer || this.PublicEphemeralValueB != (BigInteger)null)
            {
                string     str2        = str1 + string.Format("B      = {0}\n", (object)this.PublicEphemeralValueB.ToHexString());
                BigInteger bigInteger1 = this.Multiplier * this.Generator.ModPow(this.CredentialsHash, this.Modulus);
                string     str3        = str2 + string.Format("kg^x   = {0}\n", (object)bigInteger1.ToHexString());
                BigInteger bigInteger2 = this.PublicEphemeralValueB - bigInteger1 % this.Modulus;
                if (bigInteger2 < 0)
                {
                    bigInteger2 += this.Modulus;
                }
                str1 = str3 + string.Format("B-kg^x = {0}\n", (object)bigInteger2.ToHexString());
            }

            string str4;

            try
            {
                str4 = str1 + string.Format("S.key  = {0}\n", (object)this.SessionKey.ToHexString());
            }
            catch
            {
                str4 = str1 + "S.key  = empty\n";
            }

            return(str4);
        }
Ejemplo n.º 18
0
        public string InternalsToString()
        {
            string str1 = string.Format("SRP {0} Internals:\n", IsServer ? "server" : "client") +
                          string.Format("G      = {0}\n", Generator.ToHexString()) +
                          string.Format("K      = {0}\n", Multiplier.ToHexString()) +
                          string.Format("N      = {0}\n", Modulus.ToHexString()) +
                          string.Format("I      = '{0}'\n", Credentials) +
                          string.Format("Hash(I)= {0}\n",
                                        Hash((HashUtilities.HashDataBroker)Credentials).ToHexString()) +
                          string.Format("X      = {0}\n", CredentialsHash.ToHexString()) +
                          string.Format("V      = {0}\n", Verifier.ToHexString());

            if (m_salt != null)
            {
                str1 += string.Format("Salt   = {0}\n", Salt.ToHexString());
            }
            if (null != m_publicEphemeralValueA && null != m_publicEphemeralValueB)
            {
                str1 = str1 + string.Format("u      = {0}\n", ScramblingParameter.ToHexString()) +
                       string.Format("h(A)   = {0}\n",
                                     Hash((HashUtilities.HashDataBroker)PublicEphemeralValueA)
                                     .ToHexString()) + string.Format("h(B)   = {0}\n",
                                                                     Hash((HashUtilities.HashDataBroker)PublicEphemeralValueB.GetBytes())
                                                                     .ToHexString());
            }
            if (!IsServer || PublicEphemeralValueA != null)
            {
                str1 += string.Format("A      = {0}\n", PublicEphemeralValueA.ToHexString());
            }
            if (IsServer || PublicEphemeralValueB != null)
            {
                string     str2        = str1 + string.Format("B      = {0}\n", PublicEphemeralValueB.ToHexString());
                BigInteger bigInteger1 = Multiplier * Generator.ModPow(CredentialsHash, Modulus);
                string     str3        = str2 + string.Format("kg^x   = {0}\n", bigInteger1.ToHexString());
                BigInteger bigInteger2 = PublicEphemeralValueB - bigInteger1 % Modulus;
                if (bigInteger2 < 0)
                {
                    bigInteger2 += Modulus;
                }
                str1 = str3 + string.Format("B-kg^x = {0}\n", bigInteger2.ToHexString());
            }

            string str4;

            try
            {
                str4 = str1 + string.Format("S.key  = {0}\n", SessionKey.ToHexString());
            }
            catch
            {
                str4 = str1 + "S.key  = empty\n";
            }

            return(str4);
        }
Ejemplo n.º 19
0
        /// <inheritdoc />
        public async Task <BigInteger> EstimateGasAmountAsync(
            string from,
            string to,
            BigInteger transferAmount)
        {
            var requestParams = new object[] { new { from, to, value = transferAmount.ToHexString() } };
            var request       = new RpcRequest("eth_estimateGas", requestParams);
            var response      = await SendRpcRequestAsync(request);

            return(response.ResultValue <BigInteger>());
        }
Ejemplo n.º 20
0
            public static void AuthStep1(
                string vHex,
                string AHex,
                out string bHex,
                out string BHex,
                out string uHex)
            {
                BigInteger v = new BigInteger(vHex, 16);
                BigInteger A = new BigInteger(AHex, 16);

                BigInteger b;

                // b - ephemeral private key
                // b = random between 2 and N-1
                {
                    b = new BigInteger();
                    //[TODO] perhaps here use a better random generator
                    b.genRandomBits(_nbits, new Random((int)DateTime.Now.Ticks));

                    if (b >= N)
                    {
                        b = b % Nminus1;
                    }
                    if (b < 2)
                    {
                        b = 2;
                    }
                }
                bHex = b.ToHexString();

                // B = public key
                // B = kv + g^b (mod N)
                BigInteger B = (v * k + g.modPow(b, N)) % N;

                BHex = B.ToHexString();

                BigInteger u;

                // u - scrambling parameter
                // u = H (A || B)
                {
                    int nlen = 2 * ((_nbits + 7) >> 3);

                    BigInteger utmp = new BigInteger(HHex(
                                                         new string('0', nlen - AHex.Length) + AHex +
                                                         new string('0', nlen - BHex.Length) + BHex
                                                         ), 16);

                    u = (utmp < N) ? utmp : (utmp % Nminus1);
                }

                uHex = u.ToHexString();
            }
Ejemplo n.º 21
0
 /// <summary>
 /// Converts B36 encoded string into Hexadecimal EPC
 /// </summary>
 /// <param name="b36"></param>
 /// <returns>Hex string</returns>
 public static String ConvertBase36ToHex(String b36)
 {
     if (b36.Length > 0)
     {
         StringBuilder sb        = new StringBuilder(b36.ToUpper());
         char[]        charArray = sb.ToString().ToCharArray();
         Array.Reverse(charArray);
         BigInteger big = new BigInteger(new string(charArray), 36);
         if (b36.Length != big.ToHexString().Length)
         {
             return(big.ToHexString().TrimStart('0'));
         }
         else
         {
             return(big.ToHexString());
         }
     }
     else
     {
         return(string.Empty);
     }
 }
Ejemplo n.º 22
0
        /// <inheritdoc />
        public async Task UpdateSessionKey(int accountId, BigInteger sessionKey)
        {
            Account account = await AuthenticationDatabaseContext
                              .Account
                              .FindAsync((uint)accountId);   //EF now requires uint for this TC table mapping

            account.Sessionkey = sessionKey.ToHexString();

            AuthenticationDatabaseContext.Update(account);

            //TODO: If this fails for some reason then auth shouldn't continue. We need a better way to handle that case
            await AuthenticationDatabaseContext.SaveChangesAsync();
        }
Ejemplo n.º 23
0
 /// <summary>
 /// Encrypt the content.
 /// </summary>
 /// <param name="content"></param>
 /// <returns></returns>
 public string Encrypt(string content)
 {
     if (Rsa == null)
     {
         BigInteger tmp = AE(content, (Modulus.bitCount() + 7) >> 3);
         tmp = RSADoPublic(tmp);
         string result = tmp.ToHexString();
         return((result.Length & 1) == 0 ? result : "0" + result);
     }
     else
     {
         return(Convert.ToBase64String(Rsa.Encrypt(Encoding.UTF8.GetBytes(content), false)));
     }
 }
Ejemplo n.º 24
0
        public static string Encrypt(string source, string n, string d)
        {
            source = ConvertTool.RemoveSpace(source);
            n      = ConvertTool.RemoveSpace(n);
            d      = ConvertTool.RemoveSpace(d);

            BigInteger D    = new BigInteger(ConvertTool.String2Bytes(d));
            BigInteger N    = new BigInteger(ConvertTool.String2Bytes(n));
            BigInteger Data = new BigInteger(ConvertTool.String2Bytes(source));

            BigInteger biText   = new BigInteger(Data);
            BigInteger biEnText = biText.modPow(D, N);

            return(biEnText.ToHexString());
        }
Ejemplo n.º 25
0
        private void button1_Click(object sender, EventArgs e)
        {
            if (UsernameTextBox.Text != null && PasswordTextBox.Text != null)
            {
                identityHash              = Encoding.Unicode.GetBytes((UsernameTextBox.Text + ":" + PasswordTextBox.Text)).Sha1Hash();
                identificator             = byteToString(identityHash);
                verificatorTextBox.Text   = identificator;
                verificator               = UsernameTextBox.Text;
                identificatorTextBox.Text = UsernameTextBox.Text;

                salt             = Srp6.generateSalt(512);
                saltTextBox.Text = salt.ToHexString();
                isRigistred      = true;
            }
        }
Ejemplo n.º 26
0
        /// <summary>
        /// 用指定的密匙加密
        /// </summary>
        /// <param name="source">明文</param>
        /// <param name="d">可以是RSACryptoServiceProvider生成的D</param>
        /// <param name="n">可以是RSACryptoServiceProvider生成的Modulus</param>
        /// <returns>返回密文</returns>
        private static string EncryptString(string source, BigInteger d, BigInteger n)
        {
            StringBuilder result = new StringBuilder();

            try
            {
                int len      = source.Length;
                int len1     = 0;
                int blockLen = 0;
                if ((len % 128) == 0)
                {
                    len1 = len / 128;
                }
                else
                {
                    len1 = len / 128 + 1;
                }

                string block = "";
                for (int i = 0; i < len1; i++)
                {
                    if (len >= 128)
                    {
                        blockLen = 128;
                    }
                    else
                    {
                        blockLen = len;
                    }

                    block = source.Substring(i * 128, blockLen);
                    byte[]     oText    = System.Text.Encoding.Default.GetBytes(block);
                    BigInteger biText   = new BigInteger(oText);
                    BigInteger biEnText = biText.ModPow(d, n);
                    string     temp     = biEnText.ToHexString();
                    result.Append(temp).Append("@");
                    len -= blockLen;
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
            }
            return(result.ToString().TrimEnd('@'));
        }
Ejemplo n.º 27
0
        //подписываем сообщение
        // msg - сообщение
        // d - ключ подписи
        public string SingMsg(byte[] msg, BigInteger d)
        {
            // Шаг 2: вычислить e
            BigInteger e = new BigInteger(msg) % q;

            if (e == 0)
            {
                e = 1;
            }

            BigInteger k = new BigInteger();
            // точка эллиптической кривой
            ECPoint C = new ECPoint();

            BigInteger r = new BigInteger();
            BigInteger s = new BigInteger();

            do
            {
                // Шаг 3: сгенерировать случайное k (0< k <q)
                do
                {
                    k.genRandomBits(q.bitCount(), new Random());
                } while ((k < 0) || (k > q));

                // найти точку элл. C = kP
                C = ECPoint.multiply(k, Q);
                // и определить r = Xc(mod q)
                r = C.x % q;
                // определим s = (rd + ke)(mod q), s == 0 -> Шаг 3
                s = ((r * d) + (k * e)) % q;
            } while ((r == 0) || (s == 0));

            // перевод значений в двоичный вид
            string Rvector = padding(r.ToHexString(), q.bitCount() / 4);

            string Svector = padding(s.ToHexString(), q.bitCount() / 4);

            // конкатенацию двух двоичных векторов  (цифровая подпись)
            return(Rvector + Svector);
        }
Ejemplo n.º 28
0
        public static string HashString(string s)
        {
            SHA1Managed sh = new SHA1Managed();

            byte[] bytes = Encoding.UTF8.GetBytes(s);
            var    hash  = sh.ComputeHash(bytes);

            BigInteger test  = new BigInteger(bytes);
            BigInteger test2 = BigInt.Hash(bytes);

            string test3 = test2.ToHexString();
            string test4 = test2.ToString();

            var sb = new StringBuilder();

            foreach (byte b in hash)
            {
                var hex = b.ToString("x2");
                sb.Append(hex);
            }

            return(sb.ToString());
        }
Ejemplo n.º 29
0
        /// <summary>
        /// 功能:用指定的私钥(n,d)加密指定字符串source
        /// </summary>
        /// <param name="source"></param>
        /// <param name="d"></param>
        /// <param name="n"></param>
        /// <returns></returns>
        private string EncryptString(string source, BigInteger d, BigInteger n)
        {
            int len      = source.Length;
            int len1     = 0;
            int blockLen = 0;

            if ((len % 128) == 0)
            {
                len1 = len / 128;
            }
            else
            {
                len1 = len / 128 + 1;
            }
            string block = "";
            string temp  = "";

            for (int i = 0; i < len1; i++)
            {
                if (len >= 128)
                {
                    blockLen = 128;
                }
                else
                {
                    blockLen = len;
                }
                block = source.Substring(i * 128, blockLen);
                byte[]     oText    = System.Text.Encoding.Default.GetBytes(block);
                BigInteger biText   = new BigInteger(oText);
                BigInteger biEnText = biText.modPow(d, n);
                string     temp1    = biEnText.ToHexString();
                temp += temp1;
                len  -= blockLen;
            }
            return(temp);
        }
Ejemplo n.º 30
0
        public static void GenPQKey(string sp, string sq, string exponent)
        {
            sp       = ConvertTool.RemoveSpace(sp);
            sq       = ConvertTool.RemoveSpace(sq);
            exponent = ConvertTool.RemoveSpace(exponent);

            BigInteger e, n, d, p, q, dp, dq, invq;

            p = new BigInteger(sp, 16);
            q = new BigInteger(sq, 16);
            e = new BigInteger(exponent, 16);
            n = p * q;

            BigInteger oula = (p - 1) * (q - 1);

            try
            {
                d    = e.modInverse(oula);
                dp   = d % (p - 1);
                dq   = d % (q - 1);
                invq = q.modInverse(p);

                RSA_D    = d.ToHexString();
                RSA_N    = n.ToHexString();
                RSA_E    = e.ToHexString();
                RSA_P    = p.ToHexString();
                RSA_Q    = q.ToHexString();
                RSA_DP   = dp.ToHexString();
                RSA_DQ   = dq.ToHexString();
                RSA_INVQ = invq.ToHexString();
            }
            catch (Exception)
            {
                throw new ArgumentException("e and φ(n) are not coprime, change e or p&q.");
            }
        }
Ejemplo n.º 31
0
        /// <summary>
        /// Verifies that the server's proof value matches the value
        /// calculated by the client.
        /// </summary>
        /// <param name="serverProof">The 20-byte server proof.</param>
        /// <exception cref="ArgumentOutOfRangeException">Thrown if 
        /// the server proof value is not exactly 20 bytes.</exception>
        /// <exception cref="InvalidOperationException">Thrown if the object has not 
        /// yet been initialized.</exception>
        /// <remarks>
        /// This method should be called after the <see cref="LoginProof(byte[], int, int, byte[], byte[])">LoginProof</see> method.
        /// </remarks>
        /// <returns><b>True</b> if the server proof is valid; 
        /// otherwise <b>false</b>.</returns>
        public bool VerifyServerProof(byte[] serverProof)
        {
            if (serverProof.Length != 20)
                throw new ArgumentOutOfRangeException(Resources.nlsServerProof20);

            MemoryStream ms_m2 = new MemoryStream(92);
            BinaryWriter bw = new BinaryWriter(ms_m2);
            bw.Write(EnsureArrayLength(A.GetBytes(), 32));
            bw.Write(m1.GetBytes());
            bw.Write(k);
            byte[] client_m2_data = ms_m2.GetBuffer();
            ms_m2.Close();

            byte[] client_hash_m2 = s_sha.ComputeHash(client_m2_data);
            BigInteger client_m2 = new BigInteger(client_hash_m2);
            BigInteger server_m2 = new BigInteger(serverProof);

            Debug.WriteLine(client_m2.ToHexString(), "Client");
            Debug.WriteLine(server_m2.ToHexString(), "Server");

            return client_m2.Equals(server_m2);
        }
Ejemplo n.º 32
0
        //формирование цифровой подписи.
        public string genDS(byte[] h, BigInteger d)
        {
            BigInteger a = new BigInteger(h);
            BigInteger e = a % n;
            if (e == 0)
                e = 1;
            BigInteger k = new BigInteger();
            CECPoint C=new CECPoint();
            BigInteger r=new BigInteger();
            BigInteger s = new BigInteger();
            do
            {
                do
                {
                    k.genRandomBits(n.bitCount(), new Random());
                } 
                while ((k < 0) || (k > n));

                C = CECPoint.multiply(G, k);
                r = C.x % n;
                s = ((r * d) + (k * e)) % n;
            } 
            while ((r == 0)||(s==0));

            string Rvector = padding(r.ToHexString(), n.bitCount() / 4);
            string Svector = padding(s.ToHexString(), n.bitCount() / 4);
            return Rvector + Svector;
        }
Ejemplo n.º 33
0
 //подписываем сообщение
 public string SignGen(byte[] h, BigInteger d)
 {
     alpha = new BigInteger(h);
     e = alpha % n;
     if (e == 0)
         e = 1;
     k = new BigInteger();
     C = new ECPoint();
     r = new BigInteger();
     s = new BigInteger();
     do
     {
         do
         {
             k.genRandomBits(n.bitCount(), new Random());
         } while ((k < 0) || (k > n));
         C = ECPoint.multiply(k, G);
         r = C.x % n;
         s = ((r * d) + (k * e)) % n;
     } while ((r == 0) || (s == 0));
     string Rvector = padding(r.ToHexString(), n.bitCount() / 4);
     string Svector = padding(s.ToHexString(), n.bitCount() / 4);
     return Rvector + Svector;
 }