Ejemplo n.º 1
0
        private static byte[] Decode58Check(string input)
        {
            var decodeCheck = Base58.Decode(input);

            if (decodeCheck.Length <= 4)
            {
                return(null);
            }

            var decodeData = new byte[decodeCheck.Length - 4];

            Array.Copy(decodeCheck, 0, decodeData, 0, decodeData.Length);

            var hash0 = Sha256.Hash(decodeData);
            var hash1 = Sha256.Hash(hash0);

            if (hash1[0] == decodeCheck[decodeData.Length] &&
                hash1[1] == decodeCheck[decodeData.Length + 1] &&
                hash1[2] == decodeCheck[decodeData.Length + 2] &&
                hash1[3] == decodeCheck[decodeData.Length + 3])
            {
                return(decodeData);
            }

            return(null);
        }
Ejemplo n.º 2
0
        public void Main4Test()
        {
            Wallet.WalletClient wallet = GetMainNetWalletClient;

            var keyTriple = new KeyTriple("B7E85CA5910922C49DCCB92EE48DFEC13A60674845CB7152C86B88F31DA6DC67");

            byte[]       hashTransaction1 = StringHelper.HexStringToByteArray("a7e974c6e69fb7741bf5e08de8a2d8f6617826c59422b440de22e0612b03c393");
            BytesMessage bytesMessage1    = new BytesMessage();

            bytesMessage1.Value = ByteString.CopyFrom(hashTransaction1);
            Transaction transactionLoad1 = wallet.GetTransactionByIdAsync(bytesMessage1).GetAwaiter().GetResult();

            Transaction.Types.Contract contract         = transactionLoad1.RawData.Contract[0];
            TransferContract           transferContract = TransferContract.Parser.ParseFrom(contract.Parameter.Value.ToByteArray());

            byte[] publicKeyOwner = transferContract.OwnerAddress.ToByteArray();
            string encode         = Base58.Encode(publicKeyOwner);

            byte[] transactionRaw = transactionLoad1.RawData.ToByteArray();
            byte[] hash           = Sha256.Hash(transactionRaw);
            string signBase64     = transactionLoad1.Signature[0].ToBase64();

            byte[] byteArray = transactionLoad1.Signature[0].ToByteArray();
            bool   isSignatureValidFromBytes = new ECSigner().IsSignatureValidFromBytes(hash, byteArray, publicKeyOwner);
        }
Ejemplo n.º 3
0
        private string getTransactionHash(Transaction transaction)
        {
            byte[] transactionHash = Sha256.Hash(transaction.RawData.ToByteArray());
            string txid            = transactionHash.ToHexString2();

            return(txid);
        }
Ejemplo n.º 4
0
        public ActionResult Login(UsersModel user)
        {
            using (augblogsEntities db = new augblogsEntities())
            {
                if (user != null &&
                    !String.IsNullOrEmpty(user.Username) &&
                    !String.IsNullOrEmpty(user.Password))
                {
                    var username  = user.Username;
                    var password  = Sha256.Hash(user.Password);
                    var userLogin = (from u in db.Users
                                     where u.Username == username && u.Password == password
                                     select u).FirstOrDefault();

                    if (userLogin != null)
                    {
                        Session["UserLogin"] = userLogin;

                        return(RedirectToAction("Index", "Home"));
                    }
                }

                ModelState.AddModelError("", "Tên đăng nhập hoặc mật khẩu không đúng!");
            }

            return(View());
        }
Ejemplo n.º 5
0
        public ActionResult ChangePassword(UsersModel um)
        {
            if (Session["UserLogin"] == null)
            {
                return(RedirectToAction("Login", "Home"));
            }

            User user = (User)Session["UserLogin"];

            string username           = user.Username;
            string currentPassowrd    = user.Password;
            string password           = Sha256.Hash(um.Password);
            string newPassword        = Sha256.Hash(um.NewPassword);
            string confirmNewPassword = Sha256.Hash(um.ConfirmPassword);

            using (var db = new augblogsEntities())
            {
                if (string.IsNullOrEmpty(username) ||
                    string.IsNullOrEmpty(password) ||
                    string.IsNullOrEmpty(newPassword) ||
                    string.IsNullOrEmpty(confirmNewPassword))
                {
                    ModelState.AddModelError("", "Hãy điền đầy đủ các trường thông tin!");
                }
                else if (!confirmNewPassword.Equals(newPassword))
                {
                    ModelState.AddModelError("ConfirmPassword", "Xác nhận mật khẩu mới không khớp!");
                }
                else
                {
                    if (!password.Equals(currentPassowrd))
                    {
                        ModelState.AddModelError("Password", "Mật khẩu hiện tại không chính xác!");
                    }
                    else
                    {
                        var userEdit = (from u in db.Users
                                        where u.Username == username
                                        select u).FirstOrDefault();
                        if (userEdit != null)
                        {
                            userEdit.Password = newPassword;

                            int updated = db.SaveChanges();
                            if (updated > 0)
                            {
                                ViewBag.UpdateResult = "Cập nhật mật khẩu thành công.";
                            }
                            else
                            {
                                ViewBag.UpdateResult = "Cập nhật mật khẩu không thành công!";
                            }
                        }
                    }
                }
            }

            return(View(um));
        }
Ejemplo n.º 6
0
        public static byte[] sha3omit12(byte[] input)
        {
            byte[] hash    = Sha256.Hash(input);
            byte[] address = hash.SubArray(11, hash.Length - 11);
            address[0] = TypeNode.AddressPreFixByte;

            return(address);
        }
Ejemplo n.º 7
0
        public void Sha256_448Bits()
        {
            var(data, expected) = TestVectors["Sha256 448 Bits"];

            var hash = Sha256.Hash(data);

            CustomAssert.MatchArrays(hash, expected);
        }
Ejemplo n.º 8
0
        public void Sha256Stream_EmptyString()
        {
            var(data, expected) = TestVectorsStream["Sha256-Stream Empty String"];

            var hash = Sha256.Hash(data);

            CustomAssert.MatchArrays(hash, expected);
        }
Ejemplo n.º 9
0
        public void Hash_WithControlledInput_ResultMatchesExpected(string x, string y)
        {
            var input    = x.FromHexToByteArray();
            var hash     = Sha256.Hash(input);
            var expected = y.FromHexToByteArray();

            hash.Should().Equal(expected);
        }
Ejemplo n.º 10
0
        public void Sha256Stream_896Bits()
        {
            var(data, expected) = TestVectorsStream["Sha256-Stream 896 Bits"];

            var hash = Sha256.Hash(data);

            CustomAssert.MatchArrays(hash, expected);
        }
Ejemplo n.º 11
0
        public void Sha256Stream_OneMillionSmallAs()
        {
            var(data, expected) = TestVectorsStream["Sha256-Stream One Million As"];

            var hash = Sha256.Hash(data);

            CustomAssert.MatchArrays(hash, expected);
        }
Ejemplo n.º 12
0
        public static bool CheckTrees(byte[] first, uint firstTreeSize, byte[] second, uint secondTreeSize, List <byte[]> consistency)
        {
            if (IsPowerOf2(firstTreeSize))
            {
                consistency.Insert(0, first);
            }

            var fn = firstTreeSize - 1;
            var sn = secondTreeSize - 1;

            var tmp = fn >> BitOperations.TrailingZeroCount(fn);

            while (Lsb(fn) != 0)
            {
                fn >>= 1;
                sn >>= 1;
            }

            Debug.Assert(tmp == fn);

            if (consistency.Count == 0)
            {
                return(false);
            }

            var fr = consistency[0];
            var sr = consistency[0];

            for (int i = 1; i < consistency.Count; i++)
            {
                var c = consistency[i];
                if (sn == 0)
                {
                    return(false);
                }

                if (Lsb(fn) != 0 || fn == sn)
                {
                    Sha256.Hash(fr, c, fr);
                    Sha256.Hash(sr, c, sr);
                    while (!(fn == 0 || Lsb(fn) != 0))
                    {
                        fn >>= 1;
                        sn >>= 1;
                    }
                }
                else
                {
                    Sha256.Hash(c, sr, sr);
                }

                fn >>= 1;
                sn >>= 1;
            }

            return(fr.AsSpan().SequenceEqual(first) && sr.AsSpan().SequenceEqual(second));
        }
Ejemplo n.º 13
0
        public static void HashEmptyWithSpan()
        {
            var a = new Sha256();

            var expected = s_hashOfEmpty.DecodeHex();
            var actual   = new byte[expected.Length];

            a.Hash(ReadOnlySpan <byte> .Empty, actual);
            Assert.Equal(expected, actual);
        }
Ejemplo n.º 14
0
        private const string AddPreFixByteTestnet = "a0";   //a0 + address

        private static string Encode58Check(byte[] input)
        {
            var hash0      = Sha256.Hash(input);
            var hash1      = Sha256.Hash(hash0);
            var inputCheck = new byte[input.Length + 4];

            Array.Copy(input, 0, inputCheck, 0, input.Length);
            Array.Copy(hash1, 0, inputCheck, input.Length, 4);
            return(Base58.Encode(inputCheck));
        }
Ejemplo n.º 15
0
        public static void HashEmptyWithSize()
        {
            var a = new Sha256();

            var expected = s_hashOfEmpty.DecodeHex();
            var actual   = a.Hash(ReadOnlySpan <byte> .Empty, a.MaxHashSize);

            Assert.Equal(a.MaxHashSize, actual.Length);
            Assert.Equal(expected, actual);
        }
Ejemplo n.º 16
0
        private static byte[] Hash(IEnumerable <byte[]> encoded)
        {
            Sha256 hash = New <Sha256>();

            foreach (byte[] part in encoded)
            {
                hash.TransformBlock(part, 0, part.Length, null, 0);
            }
            hash.TransformFinalBlock(new byte[0], 0, 0);
            return(hash.Hash());
        }
Ejemplo n.º 17
0
        public static void Test(string msg, string digest)
        {
            var a = new Sha256();

            var m = msg.DecodeHex();

            var expected = digest.DecodeHex();
            var actual   = a.Hash(m, expected.Length);

            Assert.Equal(expected, actual);
        }
Ejemplo n.º 18
0
        private Transaction signTransaction2Object(byte[] transaction, KeyTriple privateKey)
        {
            Transaction transaction1 = Transaction.Parser.ParseFrom(transaction);

            byte[] rawdata = transaction1.RawData.ToByteArray();
            byte[] hash    = Sha256.Hash(rawdata);
            byte[] sign    = privateKey.GetSignature(hash);

            transaction1.Signature.Add(ByteString.CopyFrom(sign));

            return(transaction1);
        }
        private async Task <string> CreateAccessToken(ISessionIdentity identity)
        {
            var tokenBytes = Encoding.UTF8.GetBytes(Newtonsoft.Json.JsonConvert.SerializeObject(identity));

            var encryptedToken = Aes.Encrypt(tokenBytes, encryptionKey);
            var hash           = Sha256.Hash(tokenBytes);

            var tokenSignature = (await keyVaultClient.SignAsync(signKeyIdentifier, JsonWebKeySignatureAlgorithm.RS256, hash)).Result;

            return(identity.IdentityType.ToString()
                   + "." + Convert.ToBase64String(encryptedToken)
                   + "." + Convert.ToBase64String(tokenSignature));
        }
Ejemplo n.º 20
0
        private byte[] signTransaction2Byte(byte[] transactionBytes, KeyTriple privateKey)
        {
            Transaction transaction1 = Transaction.Parser.ParseFrom(transactionBytes);

            byte[] rawdata = transaction1.RawData.ToByteArray();
            byte[] hash    = Sha256.Hash(rawdata);

            byte[]      sign        = privateKey.GetSignature(hash);
            ByteString  byteString  = ByteString.CopyFrom(sign);
            Transaction transaction = transaction1.Clone();

            transaction.Signature.Add(byteString);
            return(transaction.ToByteArray());
        }
Ejemplo n.º 21
0
        public void ValidateTransactionTest()
        {
            Wallet.WalletClient wallet = GetMainNetWalletClient;

            byte[] hashTransaction1 =
                StringHelper.HexStringToByteArray("a7e974c6e69fb7741bf5e08de8a2d8f6617826c59422b440de22e0612b03c393");
            BytesMessage bytesMessage1 = new BytesMessage();

            bytesMessage1.Value = ByteString.CopyFrom(hashTransaction1);
            Transaction signedTransaction = wallet.GetTransactionByIdAsync(bytesMessage1).GetAwaiter().GetResult();

            Assert.IsTrue(signedTransaction.Signature.Count == signedTransaction.RawData.Contract.Count);

            RepeatedField <Transaction.Types.Contract> listContract = signedTransaction.RawData.Contract;

            byte[] hash  = Sha256.Hash(signedTransaction.RawData.ToByteArray());
            int    count = signedTransaction.Signature.Count;

            if (count == 0)
            {
                Assert.Fail();
            }

            for (int i = 0; i < count; ++i)
            {
                try
                {
                    Transaction.Types.Contract contract         = listContract[i];
                    TransferContract           transferContract = TransferContract.Parser.ParseFrom(signedTransaction.RawData.Contract[i].Parameter.Value.ToByteArray());


                    byte[] owner = transferContract.OwnerAddress.ToByteArray();
                    signedTransaction.Signature[i].ToByteArray();

                    string signatureBase64 = Base64.ToBase64String(signedTransaction.Signature[i].ToByteArray());
                    byte[] address         = signatureToAddress(hash, signatureBase64);
                    if (!Arrays.AreEqual(owner, address))
                    {
                        Assert.Fail();
                    }
                }
                catch (Exception e)
                {
                    e.ToString();
                    Assert.Fail();
                }
            }

            Assert.IsTrue(true);
        }
Ejemplo n.º 22
0
        public Transaction Sign(Transaction transaction, KeyTriple keyTriple)
        {
            Transaction transactionBuilderSigned = transaction.Clone();

            byte[] hash = Sha256.Hash(transaction.RawData.ToByteArray());
            RepeatedField <Transaction.Types.Contract> listContract = transaction.RawData.Contract;

            for (int i = 0; i < listContract.Count; i++)
            {
                // внимание тут подпись нужно  смотреть внимательное что переделалось
                byte[]     signatureBytes = keyTriple.GetSignature(hash);
                ByteString bsSign         = ByteString.CopyFrom(signatureBytes);
                transactionBuilderSigned.Signature
                .Add(bsSign);                         //Each contract may be signed with a different private key in the future.
            }

            transaction = transactionBuilderSigned.Clone();

            return(transaction);
        }
Ejemplo n.º 23
0
        public void TestInformalMillionA()
        {
            byte[] bytes = new byte[] { 97, 97, 97, 97, 97, 97, 97 };

            Sha256 hash = New <Sha256>();

            for (int i = 0; i < 1000000; i += bytes.Length)
            {
                if (1000000 - i > bytes.Length)
                {
                    hash.TransformBlock(bytes, 0, bytes.Length, null, 0);
                }
                else
                {
                    hash.TransformBlock(bytes, 0, 1000000 - i, null, 0);
                }
            }
            hash.TransformFinalBlock(new byte[0], 0, 0);

            byte[] actual;
            actual = hash.Hash();
            Assert.That(actual, Is.EquivalentTo("CDC76E5C 9914FB92 81A1C7E2 84D73E67 F1809A48 A497200E 046D39CC C7112CD0".FromHex()));
        }
        private ISessionIdentity ValidateTokenBearer(ISession session, string token)
        {
            var parts = token.Split('.');

            if (parts.Length != 3)
            {
                throw new HttpStatusException($"Invalid:Token(Token={token})")
                      {
                          Status = StatusCode.Unauthorized
                      }
            }
            ;

            var identityType = IdentityType.Unknown;

            switch (parts[0])
            {
            case "App":
                identityType = IdentityType.App;
                break;

            case "Usr":
                identityType = IdentityType.User;
                break;

            case "Bot":
                identityType = IdentityType.Bot;
                break;

            default:
                throw new HttpStatusException($"Invalid:Token.IdentityType(Token={token})")
                      {
                          Status = StatusCode.Unauthorized
                      };
            }

            var encryptedToken = Convert.FromBase64String(parts[1]);
            var decryptedToken = default(byte[]);

            try
            {
                decryptedToken = Aes.Decrypt(encryptedToken, encryptionKey);
            }
            catch (Exception e)
            {
                throw new HttpStatusException($"UnableDecrypt:Token(Token={token})", e)
                      {
                          Status = StatusCode.Unauthorized
                      };
            }

            var hash = Sha256.Hash(decryptedToken);
            var sign = Convert.FromBase64String(parts[2]);

            if (!Rsa.VerifySha256Hash(hash, sign, jwk.N, jwk.E))
            {
                throw new HttpStatusException($"ValidateFail:Signature(Token={token})")
                      {
                          Status = StatusCode.Unauthorized
                      }
            }
            ;

            var tokenString = Encoding.UTF8.GetString(decryptedToken);

            ISessionIdentity identity = default(AnonymousIdentity);

            switch (identityType)
            {
            case IdentityType.App:
                identity = Newtonsoft.Json.JsonConvert.DeserializeObject <AppIdentity>(tokenString);
                break;

            case IdentityType.User:
                identity = Newtonsoft.Json.JsonConvert.DeserializeObject <UserIdentity>(tokenString);
                break;

            case IdentityType.Bot:
                //identity = Newtonsoft.Json.JsonConvert.DeserializeObject<BotI>
                break;

            default:
                throw new HttpStatusException($"Invalid:Token.IdentityType(Token={token})")
                      {
                          Status = StatusCode.Unauthorized
                      };
            }

            //if (identity == null) throw new HttpStatusException("Null:Identity") { Status = StatusCode.Unauthorized };

            if (identity.ClientDeviceId != session.ClientDeviceId || identity.ClientSessionId != session.ClientSessionId)
            {
                throw new HttpStatusException(
                          $"NotMatch:Session(IdentityDeviceId={identity.ClientDeviceId}, CurrentDeviceId={session.ClientDeviceId}, IdentitySessionId={identity.ClientSessionId}, CurrentSessionId={session.ClientSessionId})")
                      {
                          Status = StatusCode.Unauthorized
                      }
            }
            ;

            if (identity.ExpireIn < DateTime.UtcNow.Ticks)
            {
                throw new HttpStatusException("Expired:Identity")
                      {
                          Status = StatusCode.Unauthorized
                      }
            }
            ;

            return(identity);
        }
Ejemplo n.º 25
0
        public byte[] GetTransactionHash(Transaction transaction)
        {
            byte[] hashTransaction = Sha256.Hash(transaction.RawData.ToByteArray());

            return(hashTransaction);
        }
        public void Sign(DateTime t, string[] includeHeaders = null, int debugLevel = 1)
        {
            if (includeHeaders == null)
            {
                includeHeaders = new string[] { "host", "content-type", "x-rai-date" };
            }
            if (this.Creds == null)
            {
                return;
            }

            // ISO8601 date/time strings for time of request
            string signatureDate = String.Format("{0:yyyyMMddTHHmmssZ}", t);
            string scopeDate     = String.Format("{0:yyyyMMdd}", t);

            // Authentication scope
            string scope = string.Join("/", new string[] {
                scopeDate, EnumString.GetDescription(this.Region), this.Service, "rai01_request"
            });

            // SHA256 hash of content
            Sha256 shaw256HashAlgo = new Sha256();

            byte[] reqContent  = InnerReq.Content.ReadAsByteArrayAsync().Result;
            byte[] sha256Hash  = shaw256HashAlgo.Hash(reqContent);
            string contentHash = sha256Hash.ToHex();

            // HTTP headers
            InnerReq.Headers.Authorization = null;
            // Include "x-rai-date" in signed headers
            if (!InnerReq.Headers.Contains("x-rai-date"))
            {
                InnerReq.Headers.TryAddWithoutValidation("x-rai-date", signatureDate);
            }

            var allHeaders = InnerReq.Headers.Union(InnerReq.Content.Headers);

            // Sort and lowercase() Headers to produce canonical form
            string canonicalHeaders = string.Join(
                "\n",
                from header in allHeaders
                orderby header.Key.ToLower()
                where includeHeaders.Contains(header.Key.ToLower())
                select string.Format(
                    "{0}:{1}",
                    header.Key.ToLower(),
                    string.Join(",", header.Value).Trim()
                    )
                );
            string signedHeaders = string.Join(
                ";",
                from header in allHeaders
                orderby header.Key.ToLower()
                where includeHeaders.Contains(header.Key.ToLower())
                select header.Key.ToLower()
                );

            // Sort Query String
            var parsedQuery     = HttpUtility.ParseQueryString(InnerReq.RequestUri.Query);
            var parsedQueryDict = parsedQuery.AllKeys.SelectMany(
                parsedQuery.GetValues, (k, v) => new { key = k, value = v }
                );
            string query = string.Join(
                "&",
                from qparam in parsedQueryDict
                orderby qparam.key, qparam.value
                select string.Format(
                    "{0}={1}",
                    HttpUtility.UrlEncode(qparam.key),
                    HttpUtility.UrlEncode(qparam.value))
                );

            // Create hash of canonical request
            string canonicalForm = string.Format(
                "{0}\n{1}\n{2}\n{3}\n\n{4}\n{5}",
                InnerReq.Method,
                HttpUtility.UrlPathEncode(InnerReq.RequestUri.AbsolutePath),
                query,
                canonicalHeaders,
                signedHeaders,
                contentHash
                );

            if (debugLevel > 2)
            {
                Console.WriteLine("reqContent:");
                Console.WriteLine(System.Text.Encoding.Default.GetString(reqContent));
                Console.WriteLine("canonical_form:");
                Console.WriteLine(canonicalForm);
                Console.WriteLine();
            }

            sha256Hash = shaw256HashAlgo.Hash(Encoding.UTF8.GetBytes(canonicalForm));
            string canonicalHash = sha256Hash.ToHex();

            // Create and sign "String to Sign"
            string stringToSign = string.Format(
                "RAI01-ED25519-SHA256\n{0}\n{1}\n{2}", signatureDate, scope, canonicalHash
                );

            byte[] seed = Convert.FromBase64String(Creds.PrivateKey);

            // select the Ed25519 signature algorithm
            var algorithm = SignatureAlgorithm.Ed25519;

            // create a new key pair
            using var key = Key.Import(algorithm, seed, KeyBlobFormat.RawPrivateKey);

            // sign the data using the private key
            byte[] signature = algorithm.Sign(key, Encoding.UTF8.GetBytes(stringToSign));

            string sig = signature.ToHex();

            if (debugLevel > 2)
            {
                Console.WriteLine("string_to_sign:");
                Console.WriteLine(stringToSign);
                Console.WriteLine();
                Console.WriteLine("signature:");
                Console.WriteLine(sig);
                Console.WriteLine();
            }

            var authHeader = string.Format(
                "RAI01-ED25519-SHA256 Credential={0}/{1}, SignedHeaders={2}, Signature={3}",
                Creds.AccessKey,
                scope,
                signedHeaders,
                sig
                );

            InnerReq.Headers.TryAddWithoutValidation("Authorization", authHeader);
        }
Ejemplo n.º 27
0
 private byte[] getBlockHash(Block block)
 {
     return(Sha256.Hash(block.BlockHeader.RawData.ToByteArray()));
 }