Esempio n. 1
0
        public void HashMinLength_Decodes()
        {
            var hashids = new Hashids(salt, 8);

            hashids.Decode("gB0NV05e").Should().Equal(new[] { 1 });
            hashids.Decode("mxi8XH87").Should().Equal(new[] { 25, 100, 950 });
            hashids.Decode("KQcmkIW8hX").Should().Equal(new[] { 5, 200, 195, 1 });
        }
Esempio n. 2
0
        void it_can_decode_from_a_hash_with_a_minimum_length()
        {
            var h = new Hashids(salt, 8);

            h.Decode("gB0NV05e").Should().Equal(new [] { 1 });
            h.Decode("mxi8XH87").Should().Equal(new[] { 25, 100, 950 });
            h.Decode("KQcmkIW8hX").Should().Equal(new[] { 5, 200, 195, 1 });
        }
Esempio n. 3
0
        private void It_can_decode_from_a_hash_with_a_minimum_length()
        {
            var h = new Hashids(SALT, 8);

            h.Decode("gB0NV05e").ShouldBe(new[] { 1 });
            h.Decode("mxi8XH87").ShouldBe(new[] { 25, 100, 950 });
            h.Decode("KQcmkIW8hX").ShouldBe(new[] { 5, 200, 195, 1 });
        }
Esempio n. 4
0
        void it_does_not_decode_with_a_different_salt()
        {
            var peppers = new Hashids("this is my pepper");

            hashids.Decode("NkK9").Should().Equal(new [] { 12345 });
            peppers.Decode("NkK9").Should().Equal(new int [0]);
        }
Esempio n. 5
0
        /// <summary>
        /// 对ID进行解码
        /// </summary>
        /// <param name="hash">哈希值</param>
        /// <returns>解密后的ID</returns>
        public static int Decode(string hash)
        {
            var arr = _hashids.Decode(hash);

            // 如果解析出的ID不存在,则得到一个空数组,这时候返回0
            return(arr.Length > 0 ? arr[0] : 0);
        }
        public ValidationResult Validate(DeleteCommentModel instance)
        {
            var result = new ValidationResult {
                IsValid = false
            };

            var hashIds = new Hashids(minHashLength: 5);

            var commentId = hashIds.Decode(instance.HashId).FirstOrDefault();

            if (commentId == 0)
            {
                result.Messages.Add("Invalid comment id.");
                return(result);
            }

            var comment = DbContext.Comments.FirstOrDefault(c => c.Id == commentId);

            if (comment == null)
            {
                result.Messages.Add("Invalid comment id.");
                return(result);
            }

            if (comment.UserId != instance.UserId)
            {
                result.Messages.Add("You are not the owner of this comment.");
                return(result);
            }

            result.IsValid = true;
            return(result);
        }
        public IActionResult Index(string id)
        {
            var linkId = 1;
            var url    = UrlPrefix;

            try
            {
                var linkIds = _hashId.Decode(id);
                if (linkIds.Length > 0)
                {
                    linkId = linkIds[0];
                }

                using var db = new LiteDatabase("persistence/linkshortener.db");
                var col       = db.GetCollection <LinkModel>("links");
                var foundLink = col.FindOne(c => c.Id == linkId);
                if (foundLink != null)
                {
                    url = foundLink.RedirectTargetUrl;
                }
            } catch (Exception ex)
            {
                _logger.LogWarning("Could not resolve hashid to integer", ex);
            }

            return(RedirectPermanent(url));
        }
Esempio n. 8
0
        public long Decrypt(string encryptedId)
        {
            if (string.IsNullOrEmpty(encryptedId))
            {
                throw new BusinessException <CommonErrorType>(CommonErrorType.NullArguments);
            }

            encryptedId = encryptedId?.Trim();

            int[] result;
            try
            {
                result = hashids.Decode(encryptedId);
            }
            catch (Exception)
            {
                throw new BusinessException <EncryptionErrorType>(EncryptionErrorType.ErrorInDecryption);
            }


            if (result == null || result.Length != 1)
            {
                throw new BusinessException <EncryptionErrorType>(EncryptionErrorType.ErrorInDecryption);
            }

            return(result[0]);
        }
Esempio n. 9
0
        public async Task <StoryViewModel> Get(string hashId, Guid?userId)
        {
            var ids     = new Hashids(minHashLength: 5);
            var storyId = ids.Decode(hashId).First();

            var story = await StoriesDbContext.Stories.Include(s => s.User)
                        .Include(s => s.Comments)
                        .SingleOrDefaultAsync(s => s.Id == storyId);

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

            var userUpvoted = userId != null && await StoriesDbContext.Votes.AnyAsync(v => story.Id == v.StoryId && v.UserId == userId);

            var model = new StoryViewModel
            {
                Summary = MapToStorySummaryViewModel(story, hashId, userId, userUpvoted)
            };

            var upvotedComments = await StoriesDbContext.Votes.Where(v => v.CommentId != null && v.UserId == userId)
                                  .Select(v => (int)v.CommentId)
                                  .ToListAsync();

            foreach (var comment in story.Comments.OrderByDescending(c => c.Score?.Value).Where(c => c.ParentCommentId == null))
            {
                model.Comments.Add(MapCommentToCommentViewModel(comment, upvotedComments));
            }

            return(model);
        }
Esempio n. 10
0
        public async Task <bool> Delete(string hashId)
        {
            var ids     = new Hashids(minHashLength: 5);
            var storyId = ids.Decode(hashId).First();

            if (storyId == 0)
            {
                return(false);
            }

            var story = await StoriesDbContext.Stories.Include(s => s.Comments)
                        .Where(s => s.Id == storyId)
                        .FirstOrDefaultAsync();

            if (story == null)
            {
                return(false);
            }

            foreach (var comment in story.Comments)
            {
                StoriesDbContext.Votes.RemoveRange(comment.Votes);
            }

            StoriesDbContext.Comments.RemoveRange(story.Comments);
            StoriesDbContext.Stories.Remove(story);

            return(await StoriesDbContext.SaveChangesAsync() > 0);
        }
Esempio n. 11
0
        public static int Decode(string encoded)
        {
            var hashids = new Hashids(salt);
            var link    = hashids.Decode(encoded);

            return(link[0]);
        }
Esempio n. 12
0
        public static string Decode(string encodedText)
        {
            var hashIds = new Hashids("LotusInn");
            var intArr  = hashIds.Decode(encodedText);

            return(Encoding.UTF8.GetString(intArr.Select(i => (byte)i).ToArray()));
        }
Esempio n. 13
0
        private void It_does_not_decode_with_a_different_salt()
        {
            var peppers = new Hashids("this is my pepper");

            _hashids.Decode("NkK9").ShouldBe(new[] { 12345 });
            peppers.Decode("NkK9").ShouldBe(new int[0]);
        }
Esempio n. 14
0
        private void button2_Click_1(object sender, EventArgs e)
        {
            using (MySqlConnection cn = new MySqlConnection(_myconnectionstring))
            {
                string idClear = textBox1.Text;
                int    intId;
                string sql = null;
                int    idHashKonvertert;

                if (textBox1.Text == string.Empty)
                {
                    MessageBox.Show(@"Du må taste inn noe!");
                    return;
                }


                if (int.TryParse(idClear, out intId))
                {
                    sql = "DELETE FROM booking WHERE bookingId=" + intId;
                }

                else
                {
                    var   hashids = new Hashids("Tralalalalala, dette er min SALT");
                    int[] idHash  = hashids.Decode(idClear);
                    try
                    {
                        idHashKonvertert = idHash[0];
                    }
                    catch (Exception exception)
                    {
                        idHashKonvertert = 9999999;
                    }
                    sql = "DELETE FROM booking WHERE bookingId=" + idHashKonvertert;
                }


                MySqlCommand cmd = new MySqlCommand();
                cmd.Connection  = cn;
                cmd.CommandText = sql;
                cn.Open();
                int numRowsUpdated = cmd.ExecuteNonQuery();
                cmd.Dispose();

                if (numRowsUpdated == 1)
                {
                    MessageBox.Show("Booking med id/ref: " + idClear +
                                    " ble slettet. Applikasjonen vil nå laste på nytt");
                    Hide();
                    HotelBookForm hotelBookForm = new HotelBookForm();
                    hotelBookForm.Closed += (s, args) => Close();
                    hotelBookForm.Show();
                }
                else
                {
                    MessageBox.Show("Fant ingen booking med inntastet id eller ref nummer");
                }
            }
        }
Esempio n. 15
0
        public CompanyDescriptionsMapper()
        {
            CreateMap <CompanyDescriptions, CompanyDescriptionsDto>()
            .ForMember(d => d.Id, m => m.MapFrom(e => _hash.Encode(e.Id)));

            CreateMap <CompanyDescriptionsDto, CompanyDescriptions>()
            .ForMember(e => e.Id, m => m.MapFrom(d => _hash.Decode(d.Id)));
        }
Esempio n. 16
0
        public IActionResult ViewGradeSet(string hashId)
        {
            var hashid     = new Hashids("gwa-calc-server");
            var gradeSetId = hashid.Decode(hashId)[0];
            var grades     = _ctx.Grades.Where(x => x.GradeSetId == gradeSetId).ToList();

            return(View(grades));
        }
Esempio n. 17
0
        public void GuardCharacterOnly_DecodesToEmptyArray()
        {
            // no salt creates guard characters: "abde"
            var hashids      = new Hashids("");
            var decodedValue = hashids.Decode("a");

            decodedValue.Should().Equal(Array.Empty <int>());
        }
Esempio n. 18
0
        public void CustomAlphabet2_Roundtrip()
        {
            var hashids = new Hashids(salt, 0, "ABCDEFGHIJKMNOPQRSTUVWXYZ23456789");
            var input   = new[] { 1, 2, 3, 4, 5 };

            hashids.Encode(input).Should().Be("44HYIRU3TO");
            hashids.Decode(hashids.Encode(input)).Should().BeEquivalentTo(input);
        }
        void issue_15_it_should_return_emtpy_array_when_decoding_characters_missing_in_alphabet()
        {
            var hashids = new Hashids(salt: "Salty stuff", alphabet: "qwerty1234!¤%&/()=", seps: "1234");
            var numbers = hashids.Decode("abcd");

            numbers.Length.Should().Be(0);

            var hashids2 = new Hashids();

            hashids.Decode("13-37").Length.Should().Be(0);
            hashids.DecodeLong("32323kldffd!").Length.Should().Be(0);

            var hashids3 = new Hashids(alphabet: "1234567890;:_!#¤%&/()=", seps: "!#¤%&/()=");

            hashids.Decode("asdfb").Length.Should().Be(0);
            hashids.DecodeLong("asdfgfdgdfgkj").Length.Should().Be(0);
        }
Esempio n. 20
0
        public void CustomAlphabet_Roundtrip()
        {
            var hashids = new Hashids(salt, 0, "ABCDEFGhijklmn34567890-:");
            var input   = new[] { 1, 2, 3, 4, 5 };

            hashids.Encode(input).Should().Be("6nhmFDikA0");
            hashids.Decode(hashids.Encode(input)).Should().BeEquivalentTo(input);
        }
Esempio n. 21
0
        public UsersMapper()
        {
            CreateMap <User, UserDto>()
            .ForMember(d => d.Id, m => m.MapFrom(e => _hash.Encode(e.Id)));

            CreateMap <UserDto, User>()
            .ForMember(e => e.Id, m => m.MapFrom(d => _hash.Decode(d.Id)));
        }
Esempio n. 22
0
        public void SaltIsLongerThanAlphabet_Roundtrip()
        {
            var longSalt     = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890";
            var hashids      = new Hashids(salt: longSalt);
            var input        = new[] { 1, 2, 0 };
            var decodedValue = hashids.Decode(hashids.Encode(input));

            decodedValue.Should().Equal(input);
        }
Esempio n. 23
0
        protected void Button1_Click(object sender, EventArgs e)
        {
            _myconnectionstring = "Database=Test; Data Source = localhost; User = test; Password = test";

            if (TextBox1.Text == string.Empty || TextBox2.Text == string.Empty)
            {
                Label3.Text = @"Du må taste inn både fornavn og etternavn!";
                return;
            }

            if (Calendar1.SelectedDate < DateTime.Now.Date)
            {
                Label3.Text = @"Fra dato kan ikke være før dagens dato!";
                return;
            }

            if (Calendar2.SelectedDate < Calendar1.SelectedDate)
            {
                Label3.Text = @"Du kan ikke velge en til dato som er tidligere enn fra dato!";
                return;
            }

            try
            {
                using (MySqlConnection cn = new MySqlConnection(_myconnectionstring))
                {
                    var sql = "INSERT INTO booking (fornavn, etternavn, datoFra, datoTil) VALUES(" + '"' + TextBox1.Text +
                              '"' + "," + '"' + TextBox2.Text + '"' + "," + '"' +
                              Calendar1.SelectedDate.ToString("yyyy-MM-dd") + '"' + "," + '"' +
                              Calendar2.SelectedDate.ToString("yyyy-MM-dd") + '"' + ")";
                    MySqlCommand cmd = new MySqlCommand();
                    cmd.Connection  = cn;
                    cmd.CommandText = sql;
                    cn.Open();
                    int numRowsUpdated = cmd.ExecuteNonQuery();
                    int bid            = (int)cmd.LastInsertedId;
                    cmd.Dispose();


                    TextBox1.Text = string.Empty;
                    TextBox2.Text = string.Empty;
                    Calendar1.SelectedDates.Clear();
                    Calendar2.SelectedDates.Clear();

                    var hashids = new Hashids("Tralalalalala, dette er min SALT");
                    var id      = hashids.Encode(bid);
                    var numbers = hashids.Decode(id);

                    Label3.Text = "Takk! Bookingen ble registrert. </br> Din bookingreferanse er \"" + id + "\". </br>Benytt denne for å kansellere bestillingen";
                }
            }

            catch
            {
                Console.WriteLine(@"Error: DB not updated!");
            }//TextBox1.Text = Calendar1.SelectedDate.ToString("yyyy-M-dd");
        }
 public static int DecodeSeedValue(string hash)
 {
     if (String.IsNullOrEmpty(hash) || String.IsNullOrWhiteSpace(hash))
     {
         throw new ArgumentException("Hash cannot be null, empty or white spaces");
     }
     int[] decodedValueDigits = hashIds.Decode(hash);
     return(JoinDigitArray(decodedValueDigits));
 }
Esempio n. 25
0
        public CompaniesMapper()
        {
            CreateMap <Company, CompanyDto>()
            .ForMember(d => d.Id, m => m.MapFrom(e => _hash.Encode(e.Id)));
            //.ForMember(d => d.Test, m => m.MapFrom(e => RoleHelper.Role != "Admin" ? e.Test : null));

            CreateMap <CompanyDto, Company>()
            .ForMember(e => e.Id, m => m.MapFrom(d => _hash.Decode(d.Id)));
        }
Esempio n. 26
0
        public void AddLink(Link link)
        {
            var hashids = new Hashids(link.FullLink);
            var id      = hashids.Encode(1, 2, 3);
            var numbers = hashids.Decode(id);

            link.ShortLink = id;
            link.Id        = _context.Links.Count();
            _context.Add(link);
            _context.SaveChanges();
        }
Esempio n. 27
0
 public int?HashDecodeId(string hashValue)
 {
     try
     {
         return(hashids.Decode(hashValue).First());
     }
     catch (Exception)
     {
         return(null);
     }
 }
Esempio n. 28
0
        /// <summary>
        /// 从将Id藏起来到给定的Guid中;返回解密后的Id;
        /// 如果传入为空字符串,则返回 0;注意,不是空,而是 0;
        /// </summary>
        /// <param name="cryptIntString"></param>
        /// <param name="typeName">类型,如果传入null,则解密时不进行类型校验;</param>
        /// <param name="debug"></param>
        /// <returns></returns>
        public static int DecryptIdInGuid(string cryptIntString, string typeName, bool debug = false)
        {
            if (string.IsNullOrEmpty(cryptIntString))
            {
                return(0);
            }
            if (cryptIntString.Length < 32)
            {
                Hashids hashids = GetHashids(typeName);
                var     ids     = hashids.Decode(cryptIntString);
                if (ids == null || ids.Length == 0)
                {
                    return(0);
                }
                return(ids[0]);
            }

            int typeHash = 0;

            if (!string.IsNullOrEmpty(typeName))
            {
                typeHash = Math.Abs(typeName.GetHashCode());
            }
            if (string.IsNullOrEmpty(cryptIntString))
            {
                return(0);
            }
            if (cryptIntString.Length < 32)
            {
                return(0);
            }

            var  bytes    = cryptIntString.ToCharArray();
            var  beginPos = System.Convert.ToInt32(new string(new char[] { bytes[bytes.Length - 1] }), 16);
            var  len      = System.Convert.ToInt32(new string(new char[] { bytes[beginPos + 11] }), 16);
            var  sub      = cryptIntString.Substring(beginPos, len);
            long subLong  = System.Convert.ToInt64(sub, 16);
            var  id       = (int)(subLong / 135721L);

            if (!string.IsNullOrEmpty(typeName) && CryptIdInGuid(id, typeName) != cryptIntString || debug)
            //不能验证,因为在 Ehay 和 EhayDataHandle 会产生不同的 GuidList;
            //悲催的是, 反序列化时, Newtonsoft.Json.JsonConvert.DeserializeObject<EH_DeviceInfo>(keyContent)
            //在 IdEntity 中无法获取到正确的 EH_DeviceInfo 类型,
            {
                var crcString = cryptIntString.Substring(28, 3);
                CryptIdInGuid(id, typeName, true);
//                LogUtil.xLogUtil.Warn(
//"加解密异常:解密过程:{1}{2}type:{3}{2}typeHash:{4}{2}beginPos:{5}{2}len:{6}{2}sub:{7}{2}subLong:{8}{2}crcString:{9}{2}id:{0}",
//                    null,
//                    id, cryptIntString, Environment.NewLine, typeName, typeHash, beginPos, len, sub, subLong, crcString);
                // throw new Exception("错误的解密字符串");
            }
            return(id);
        }
Esempio n. 29
0
 public static int FromEncodedId(this string id)
 {
     try
     {
         return(Hashids.Decode(id).FirstOrDefault());
     }
     catch
     {
         return(-1);
     }
 }
Esempio n. 30
0
        public async Task <CommentViewModel> Get(string hashId)
        {
            var hashIds = new Hashids(minHashLength: 5);

            var comment = await StoriesDbContext.Comments.FindAsync(hashIds.Decode(hashId).FirstOrDefault());

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

            return(await MapCommentToCommentViewModel(comment));
        }
Esempio n. 31
0
 void it_does_not_decode_with_a_different_salt()
 {
     var peppers = new Hashids("this is my pepper");
     hashids.Decode("NkK9").Should().Equal(new []{ 12345 });
     peppers.Decode("NkK9").Should().Equal(new int [0]);
 }
Esempio n. 32
0
 void it_can_decode_from_a_hash_with_a_minimum_length()
 {
     var h = new Hashids(salt, 8);
     h.Decode("gB0NV05e").Should().Equal(new [] {1});
     h.Decode("mxi8XH87").Should().Equal(new[] { 25, 100, 950 });
     h.Decode("KQcmkIW8hX").Should().Equal(new[] { 5, 200, 195, 1 });
 }
Esempio n. 33
0
 void issue_8_should_not_throw_out_of_range_exception()
 {
     var hashids = new Hashids("janottaa", 6);
     var numbers = hashids.Decode("NgAzADEANAA=");
 }