Example #1
0
        public override bool Commit(GameEventArgs arg)
        {
            Owner[MingCeUsed] = 1;
            Game.CurrentGame.HandleCardTransferToHand(Owner, arg.Targets[0], arg.Cards);
            if (arg.Targets.Count == 1)
            {
                Game.CurrentGame.DrawCards(arg.Targets[0], 1);
                return(true);
            }
            int answer = 0;

            arg.Targets[0].AskForMultipleChoice(new MultipleChoicePrompt("MingCe"), new List <OptionPrompt>()
            {
                new OptionPrompt("MingCeSha", arg.Targets[1]), new OptionPrompt("MingCeMoPai")
            }, out answer);
            if (answer == 0)
            {
                Sha.UseDummyShaTo(arg.Targets[0], arg.Targets[1], new RegularSha(), new CardUsagePrompt("MingCe", arg.Targets[1]));
            }
            else
            {
                Game.CurrentGame.DrawCards(arg.Targets[0], 1);
            }
            return(true);
        }
        public Session GenerateSession(string username, string password)
        {
            var user = _repository.GetByUsername(username);

            if (user == null)
            {
                return(null);
            }

            if (Valid(user.Id, user.Password))
            {
                return(_context.Session.FirstOrDefault(u => u.UserId == user.Id));
            }

            var hash    = Sha.Encrypt(RandomString.CreateString(256));
            var session = new Session
            {
                UserId = user.Id,
                Key    = hash
            };

            _context.Session.Add(session);
            _context.SaveChanges();
            return(session);
        }
Example #3
0
        protected override bool?AdditionalVerify(Player source, List <Card> cards, List <Player> players)
        {
            if (source[XueJiUsed] != 0 || source.LostHealth == 0)
            {
                return(false);
            }
            if (players != null && players.Count > 0 && (cards == null || cards.Count == 0))
            {
                return(false);
            }
            if (players != null && source.LostHealth < players.Count)
            {
                return(false);
            }
            var temp = new Sha();

            temp.HoldInTemp(cards);
            if (players.Any(p => Game.CurrentGame.DistanceTo(source, p) > source[Player.AttackRange] + 1))
            {
                temp.ReleaseHoldInTemp();
                return(false);
            }
            temp.ReleaseHoldInTemp();
            return(true);
        }
        private string GetHash(string secret, Sha algorithm)
        {
            HashAlgorithm hashAlgorithm;

            switch (algorithm)
            {
            case Sha.Sha1:
                hashAlgorithm = SHA1.Create();
                break;

            case Sha.Sha256:
                hashAlgorithm = SHA256.Create();
                break;

            case Sha.Sha512:
                hashAlgorithm = SHA512.Create();
                break;

            default:
                hashAlgorithm = SHA256.Create();
                break;
            }

            byte[] bytes = hashAlgorithm.ComputeHash(Encoding.ASCII.GetBytes(secret));

            return(string.Concat(bytes.Select(x => x.ToString("X2")).ToArray()));
        }
Example #5
0
        public AddUserResponse AddUser(AddUserRequest request)
        {
            var response = new AddUserResponse {
                Errors = new List <string>()
            };

            //TODO: validari

            if (request.Age < 10)
            {
                response.Success = false;
                response.Errors.Add("Age is lower than 10");
                return(response);
            }

            _userRepository.Add(new User
            {
                Name      = request.Name,
                Age       = request.Age,
                Username  = request.Username,
                Password  = Sha.Encrypt(request.Password),
                UserImage = request.UserImage
            });

            response.Success = true;
            return(response);
        }
 public override int GetHashCode()
 {
     unchecked
     {
         return((Type != null ? Type.GetHashCode() : 0) ^ (Sha != null ? Sha.GetHashCode() : 0) ^ (Path != null ? Path.GetHashCode() : 0) ^ (GitUrl != null ? GitUrl.GetHashCode() : 0) ^ (HtmlUrl != null ? HtmlUrl.GetHashCode() : 0) ^ (DownloadUrl != null ? DownloadUrl.GetHashCode() : 0) ^ (Encoding != null ? Encoding.GetHashCode() : 0) ^ (Url != null ? Url.GetHashCode() : 0) ^ (Size != null ? Size.GetHashCode() : 0) ^ (Name != null ? Name.GetHashCode() : 0) ^ (Content != null ? Content.GetHashCode() : 0));
     }
 }
Example #7
0
        /// <summary>
        ///     Generates a Request Token from Post Data and a Static Token
        /// </summary>
        /// <param name="postData">The Html Encoded Post Data</param>
        /// <param name="staticToken">The Snapchat Static Token.</param>
        /// <returns>The Request Token, all nice.</returns>
        public static string GenerateRequestToken(string postData, string staticToken)
        {
            string s1 = KeyVault.Secret + postData;
            string s2 = staticToken + KeyVault.Secret;

            string s3 = Sha.Sha256(s1);
            string s4 = Sha.Sha256(s2);

            string output = "";

            for (int i = 0; i < KeyVault.HashingPattern.Length; i++)
            {
                char c = KeyVault.HashingPattern[i];

                if (c == '0')
                {
                    output += s3[i];
                }
                else
                {
                    output += s4[i];
                }
            }
            return(output);
        }
        public override PaddingResult Pad(int nlen, BitString message)
        {
            // 1. Message Hashing
            var hashedMessage = Sha.HashMessage(message).Digest;

            // 2. Hash Encapsulation
            var trailer = new BitString("66CC");    // ERROR: The first byte of the trailer is unexpected

            // Header is always 4, trailer is always 16
            var paddingLen = nlen - Header.BitLength - Sha.HashFunction.OutputLen - trailer.BitLength;
            var padding    = GetPadding(paddingLen);

            var IR = Header.GetDeepCopy();

            IR = BitString.ConcatenateBits(IR, padding);
            IR = BitString.ConcatenateBits(IR, hashedMessage);
            IR = BitString.ConcatenateBits(IR, trailer);      // ERROR: Change the trailer to something else

            if (IR.BitLength != nlen)
            {
                return(new PaddingResult("Improper length for IR"));
            }

            return(new PaddingResult(IR));
        }
Example #9
0
 public override int GetHashCode()
 {
     unchecked
     {
         return((Url != null ? Url.GetHashCode() : 0) ^ (Sha != null ? Sha.GetHashCode() : 0) ^ (Author != null ? Author.GetHashCode() : 0) ^ (Committer != null ? Committer.GetHashCode() : 0) ^ (Message != null ? Message.GetHashCode() : 0) ^ (Tree != null ? Tree.GetHashCode() : 0));
     }
 }
Example #10
0
        public override void Load(GitPackReader reader)
        {
            byte[] shaContents = reader.ReadBytes(20);

            BaseSHA = Sha.Decode(shaContents);
            Delta   = reader.UncompressToLength(Size).ToArray();
        }
Example #11
0
        private void LoginButtonClicked(object sender, RoutedEventArgs e)
        {
            string address = AddressComboBox.Text;;
            string hashPw  = Sha.GenerateSha256String(PasswordBox1.Password);

            //check Private key and public Key
            var walletBank = new WalletBank();
            var wallet     = walletBank.FindWallet(address, hashPw);

            if (wallet == null)
            {
                Errormessage.Text = "First import your wallet";
                return;
            }

            if (!wallet.IsValid())
            {
                Errormessage.Text = "Wallet isn't valid";
                return;
            }

            //check inside DB
            var context = new UserContext();
            var user    = context.Users.FirstOrDefault(n => n.Address == address && n.Password == hashPw);

            if (user != null)
            {
                NavigationService?.Navigate(new WalletPage(user));
            }
            else
            {
                Errormessage.Text = "Passwords doesn't match or connection is lost";
            }
        }
Example #12
0
        /// <inheritdoc/>
        protected override async Task <object> CallGitHubApi(DialogContext dc, Octokit.GitHubClient gitHubClient, CancellationToken cancellationToken = default(CancellationToken))
        {
            if (Owner != null && Name != null && Sha != null && Options != null)
            {
                var ownerValue   = Owner.GetValue(dc.State);
                var nameValue    = Name.GetValue(dc.State);
                var shaValue     = Sha.GetValue(dc.State);
                var optionsValue = Options.GetValue(dc.State);
                return(await gitHubClient.Repository.Comment.GetAllForCommit(ownerValue, nameValue, shaValue, optionsValue).ConfigureAwait(false));
            }
            if (Owner != null && Name != null && Sha != null)
            {
                var ownerValue = Owner.GetValue(dc.State);
                var nameValue  = Name.GetValue(dc.State);
                var shaValue   = Sha.GetValue(dc.State);
                return(await gitHubClient.Repository.Comment.GetAllForCommit(ownerValue, nameValue, shaValue).ConfigureAwait(false));
            }
            if (RepositoryId != null && Sha != null && Options != null)
            {
                var repositoryIdValue = RepositoryId.GetValue(dc.State);
                var shaValue          = Sha.GetValue(dc.State);
                var optionsValue      = Options.GetValue(dc.State);
                return(await gitHubClient.Repository.Comment.GetAllForCommit((Int64)repositoryIdValue, shaValue, optionsValue).ConfigureAwait(false));
            }
            if (RepositoryId != null && Sha != null)
            {
                var repositoryIdValue = RepositoryId.GetValue(dc.State);
                var shaValue          = Sha.GetValue(dc.State);
                return(await gitHubClient.Repository.Comment.GetAllForCommit((Int64)repositoryIdValue, shaValue).ConfigureAwait(false));
            }

            throw new ArgumentNullException("Required [sha] arguments missing for GitHubClient.Repository.Comment.GetAllForCommit");
        }
Example #13
0
    public void UpdateInsertCache(string filePath, string sha)
    {
        Sha newSHA = new Sha();

        newSHA.path     = filePath;
        newSHA.unixTime = DateTime.Now;
        newSHA.SHA      = sha;
        string write = "";
        bool   found = false;

        for (int i = 0; i < shas.Count; i++)
        {
            if (shas[i].path == newSHA.path)
            {
                shas[i] = newSHA; found = true;
            }
            write += shas[i].ToString() + "\n";
        }
        if (!found)
        {
            shas.Add(newSHA);
            write += newSHA.ToString() + "\n";
        }
        File.WriteAllText("Assets/essential/Update/SHACACHE.conf", write);
    }
Example #14
0
        /// <summary>
        /// Gets called be the Children getter for lazy loading
        /// </summary>
        private void LoadChildren()
        {
            _children = new TreeNodeCollection();

            try
            {
                using (GitObjectReader stream = new GitObjectReader(_childrenRaw))
                {
                    while (!stream.IsEndOfStream)
                    {
                        string mode, path, sha;

                        mode = stream.ReadWord().GetString();
                        path = stream.ReadToNull().GetString();
                        sha  = Sha.Decode(stream.ReadBytes(20));

                        TreeNode child = Repo.Storage.GetObject <TreeNode>(sha);
                        child.Path   = path;
                        child.Mode   = FileMode.FromBits(int.Parse(mode));
                        child.Parent = this;

                        _children.Add(child);
                    }
                }
            }
            catch (Exception)
            {
                // Reset _children field, otherwise the object would be in an invalid state
                _children = null;

                throw;
            }
        }
        public override PaddingResult Pad(int nlen, BitString message)
        {
            // 1. Message Hashing
            var hashedMessage = Sha.HashMessage(message).Digest;

            // 2. Hash Encapsulation
            var trailer = GetTrailer();

            // Header is always 4, trailer is always 16
            var paddingLen = nlen - Header.BitLength - Sha.HashFunction.OutputLen - trailer.BitLength;
            var padding    = GetPadding(paddingLen);

            // ERROR: Split the padding into two chunks and put the hashed message in the middle
            var firstChunkPadding  = padding.GetMostSignificantBits(paddingLen - 8);
            var secondChunkPadding = padding.GetLeastSignificantBits(8);

            var IR = Header.GetDeepCopy();

            IR = BitString.ConcatenateBits(IR, firstChunkPadding);
            IR = BitString.ConcatenateBits(IR, hashedMessage);
            IR = BitString.ConcatenateBits(IR, secondChunkPadding);
            IR = BitString.ConcatenateBits(IR, trailer);

            if (IR.BitLength != nlen)
            {
                return(new PaddingResult("Improper length for IR"));
            }

            return(new PaddingResult(IR));
        }
 public string GetShortHash()
 {
     if (!string.IsNullOrEmpty(Sha) && Sha.Length >= 7)
     {
         return(Sha.Substring(0, 7));
     }
     return("NOTHASH");
 }
Example #17
0
        public static byte[] PublicKeyHashed(byte[] pubK)
        {
            var pubHash       = Sha.GenerateSha256String(ByteHelper.GetStringFromBytes(pubK));
            var ripemd160     = new RIPEMD160Managed();
            var ripemd160Hash = ripemd160.ComputeHash(Encoding.UTF8.GetBytes(pubHash));

            return(ripemd160Hash);
        }
Example #18
0
        public static uint[] Digest(byte[] src)
        {
            var sha = new Sha();
            sha.Input(src);
            sha.Result();

            return sha.MessageDigest;
        }
Example #19
0
        public static bool ValidateInviteKeyAndCredentials
        (
            SessionType sessionType,
            Guid inviteGuid,
            string domain,
            string email,
            string currentPassword,
            double InviteTimeOutHrs,
            out Tenant tenantDatabase,
            out Exception exception
        )
        {
            var  result = false;
            User user   = null;
            var  now    = DateTime.UtcNow;

            tenantDatabase = null;
            exception      = null;
            try
            {
                if (!MasterTenantManagement.GetTenantByDomain(domain, out tenantDatabase, out exception))
                {
                    throw (exception);
                }
                if (tenantDatabase == null)
                {
                    throw (new DomainNotFoundException());
                }
                using (var context = new ContextTenant(tenantDatabase.DatabaseConnectionString))
                {
                    user = context.Users.Where(x => x.InviteGuid == inviteGuid && x.Email == email).SingleOrDefault();
                    if (user == null)
                    {
                        throw new Exception(@"Unable to find the invitation. This might happen for the follwoing reason:" + Environment.NewLine + "1) If the user is already a member." + Environment.NewLine + "2)Invalid key or domain." + Environment.NewLine + "3)Invalid credentials.");
                    }
                    var expiryDate = user.DateTimeCreated.AddHours(InviteTimeOutHrs);
                    if (DateTime.UtcNow >= expiryDate)
                    {
                        throw new Exception("The invitation was expired, please contact the sender for a new invitation.");
                    }
                    string passwordHash = "";
                    if (!Sha.GenerateHash((currentPassword ?? ""), GlobalConstants.EncodingCryptography, GlobalConstants.AlgorithmHashShaKind, out passwordHash, out exception))
                    {
                        throw (exception);
                    }
                    if (!PasswordHash.ValidatePassword(passwordHash, user.PasswordHash))
                    {
                        throw (new AuthenticationException(isValidDomain: true, isValidUsername: true, isValidPassword: false));
                    }
                    result = true;
                }
            }
            catch (Exception e)
            {
                exception = e;
            }
            return(result);
        }
Example #20
0
        protected void SetUp()
        {
            const string Sha = "2DEA9A198FDCF0FE70473C079F1036B6E16FBFCE";

            _checksum = Enumerable.Range(0, Sha.Length)
                        .Where(x => x % 2 == 0)
                        .Select(x => Convert.ToByte(Sha.Substring(x, 2), 16))
                        .ToArray();
        }
Example #21
0
        public static uint[] Digest(byte[] src)
        {
            var sha = new Sha();

            sha.Input(src);
            sha.Result();

            return(sha.MessageDigest);
        }
Example #22
0
        public IActionResult Post([FromBody] Sha data)
        {
            if (data?.HashKey == null || data.SecureParameters == null)
            {
                return(BadRequest("Missing Paramaters"));
            }

            return(Ok(new BoldchatEncryptionUtil.Sha512Util(data.HashKey).GetEncryptedString(data.SecureParameters)));
        }
Example #23
0
        public override bool Commit(GameEventArgs arg)
        {
            Owner[MiZhaoUsed] = 1;
            Game.CurrentGame.HandleCardTransferToHand(Owner, arg.Targets[0], Owner.HandCards());
            List <Player> alivePlayers = Game.CurrentGame.AlivePlayers;

            if (!alivePlayers.Any(p => p.HandCards().Count > 0 && p != arg.Targets[0]))
            {
                return(true);
            }
            ISkill        skill;
            List <Card>   cards;
            List <Player> players;

            if (!Owner.AskForCardUsage(new CardUsagePrompt("MiZhao", arg.Targets[0]), new MiZhaoVerifier(arg.Targets[0]), out skill, out cards, out players))
            {
                players = new List <Player>();
                foreach (Player p in alivePlayers)
                {
                    if (p.HandCards().Count > 0 && p != arg.Targets[0])
                    {
                        players.Add(p);
                        break;
                    }
                }
            }
            Player pindianTarget = players[0];
            var    result = Game.CurrentGame.PinDian(arg.Targets[0], pindianTarget, this);
            Player winner, loser;

            if (result == null)
            {
                return(true);
            }
            if (result == true)
            {
                winner = arg.Targets[0]; loser = pindianTarget;
            }
            else
            {
                winner = pindianTarget; loser = arg.Targets[0];
            }
            if (!Game.CurrentGame.PlayerCanBeTargeted(winner, new List <Player>()
            {
                loser
            }, new CompositeCard()
            {
                Type = new Sha()
            }))
            {
                return(true);
            }
            winner[Sha.NumberOfShaUsed]--;
            Sha.UseDummyShaTo(winner, loser, new RegularSha(), new CardUsagePrompt("MingCe", loser), MiZhaoSha);
            return(true);
        }
Example #24
0
        public static string GenerateAuthenticatedMessage(string message, long timestamp, string password)
        {
            if (message.Contains(":[:BR:]:"))
            {
                throw new MessageUnallowedCharsException("Message can't contain :[:BR:]:");
            }
            var prepare = message + ":[:BR:]:" + Convert.ToString(timestamp);

            return(prepare + ":[:BR:]:" + Sha.HashToString(Sha.Sha512Hmac(Sha.Sha512(password), new UTF8Encoding().GetBytes(prepare))));
        }
Example #25
0
 public override int GetHashCode()
 {
     unchecked
     {
         int result = Sha?.GetHashCode() ?? 0;
         result = (result * 397) ^ (Message?.GetHashCode() ?? 0);
         result = (result * 397) ^ (Description?.GetHashCode() ?? 0);
         return(result);
     }
 }
Example #26
0
 public override int GetHashCode()
 {
     unchecked
     {
         int result = (Sha != null ? Sha.GetHashCode() : 0);
         result = (result * 397) ^ (Message != null ? Message.GetHashCode() : 0);
         result = (result * 397) ^ (Description != null ? Description.GetHashCode() : 0);
         return(result);
     }
 }
Example #27
0
        public static string ToSHAString(this byte[] input)
        {
            string sha = Sha.Decode(input);

            if (!Utility.IsValidSHA(sha))
            {
                throw new ParseException("Invalid sha: {0}".FormatWith(sha));
            }

            return(sha);
        }
Example #28
0
        public int GetPackFileOffset(Sha sha)
        {
            int levelTwo = SearchLevelTwo(sha, sha.FirstByte);


            if (levelTwo == -1)
            {
                throw new ObjectNotFoundException(sha.SHAString);
            }

            return(System.Net.IPAddress.HostToNetworkOrder(BitConverter.ToInt32(offsets[sha.FirstByte], levelTwo << 2)));
        }
Example #29
0
        protected override void Seed(DatabaseContext context)
        {
            User _user = new User()
            {
                Email        = "*****@*****.**".ToLower(),
                Password     = Sha.Encoder("admin123"),
                SecurityGuid = Guid.NewGuid()
            };

            context.Users.Add(_user);
            context.SaveChanges();
        }
Example #30
0
        /// <summary>
        /// Returns true if GithubContent instances are equal
        /// </summary>
        /// <param name="other">Instance of GithubContent to be compared</param>
        /// <returns>Boolean</returns>
        public bool Equals(GithubContent other)
        {
            if (other is null)
            {
                return(false);
            }
            if (ReferenceEquals(this, other))
            {
                return(true);
            }

            return
                ((
                     Name == other.Name ||
                     Name != null &&
                     Name.Equals(other.Name)
                     ) &&
                 (
                     Sha == other.Sha ||
                     Sha != null &&
                     Sha.Equals(other.Sha)
                 ) &&
                 (
                     Class == other.Class ||
                     Class != null &&
                     Class.Equals(other.Class)
                 ) &&
                 (
                     Repo == other.Repo ||
                     Repo != null &&
                     Repo.Equals(other.Repo)
                 ) &&
                 (
                     Size == other.Size ||
                     Size != null &&
                     Size.Equals(other.Size)
                 ) &&
                 (
                     Owner == other.Owner ||
                     Owner != null &&
                     Owner.Equals(other.Owner)
                 ) &&
                 (
                     Path == other.Path ||
                     Path != null &&
                     Path.Equals(other.Path)
                 ) &&
                 (
                     Base64Data == other.Base64Data ||
                     Base64Data != null &&
                     Base64Data.Equals(other.Base64Data)
                 ));
        }
Example #31
0
        public bool ChangeNewPassword(string password)
        {
            User _user = _manager.Find(u => u.UserID == 1);

            if (_user != null)
            {
                _user.Password = Sha.Encoder(password);
                _manager.Update(_user);
                return(true);
            }

            return(false);
        }