Esempio n. 1
0
 public ActionResult StreamSource(string shortenedUrl, string password)
 {
     if (shortenedUrl.Length > 5)
     {
         var mapping = _context.CustomMapping.Find(Base62.Decode(shortenedUrl));
         if (password != mapping.Password)
         {
             return(BadRequest());
         }
         else
         {
             return(PhysicalFile(mapping.Original, "application/octet-stream", true));
         }
     }
     else
     {
         var mapping = _context.Mapping.Find(Base62.Decode(shortenedUrl));
         if (password != mapping.Password)
         {
             return(BadRequest());
         }
         else
         {
             return(PhysicalFile(mapping.Original, "application/octet-stream", true));
         }
     }
 }
Esempio n. 2
0
 public IActionResult OnPost(string shortenedUrl, string password)
 {
     if (shortenedUrl.Length > 5)
     {
         var mapping = _context.CustomMapping.Find(Base62.Decode(shortenedUrl));
         if (password != mapping.Password)
         {
             return(RedirectToPage("./VerifyPassword", new { shortenedUrl = shortenedUrl }));
         }
         else
         {
             VideoSource = "/StreamSource?shortenedUrl=" + shortenedUrl + "password="******"video/" + mapping.Original.Split(".").Last();
             return(Page());
         }
     }
     else
     {
         var mapping = _context.Mapping.Find(Base62.Decode(shortenedUrl));
         if (password != mapping.Password)
         {
             return(RedirectToPage("./VerifyPassword", new { shortenedUrl = shortenedUrl }));
         }
         else
         {
             VideoSource = "/StreamSource?shortenedUrl=" + shortenedUrl + "&password="******"video/" + mapping.Original.Split(".").Last();
             return(Page());
         }
     }
 }
        public async Task <ActionResult> Index(LoginViewModel model)
        {
            using (var hash = SHA256.Create())
            {
                if (!ModelState.IsValid)
                {
                    return(View(model));
                }

                var result = await _signinManager.Value.PasswordSignInAsync(
                    Base62.Encode(hash.ComputeHash(Encoding.UTF8.GetBytes(model.Email))),
                    model.Password, false, false);

                switch (result)
                {
                case SignInStatus.LockedOut:
                case SignInStatus.RequiresVerification:
                    throw new NotImplementedException();

                case SignInStatus.Success:
                    return(RedirectToRoute("Default"));

                case SignInStatus.Failure:
                    ModelState.AddModelError("", "Username or password was incorrect.");
                    model.Password = "";
                    return(View(model));

                default:
                    throw new NotImplementedException();
                }
            }
        }
Esempio n. 4
0
        public async Task <IActionResult> ShortUrlAsync(string base62,
                                                        CancellationToken token)
        {
            if (string.IsNullOrEmpty(base62))
            {
                return(NotFound());
            }

            //if (!long.TryParse(base62, out var id))
            //{
            if (!Base62.TryParse(base62, out var id))
            {
                return(NotFound());
            }

            _userManager.TryGetLongUserId(User, out var userId);
            var query = new DocumentById(id, userId);
            var model = await _queryBus.QueryAsync(query, token);

            if (model == null)
            {
                return(NotFound());
            }
            var t = RedirectToRoutePermanent(SeoTypeString.Document, new
            {
                courseName = FriendlyUrlHelper.GetFriendlyTitle(model.Document.Course),
                id         = id.Value,
                name       = FriendlyUrlHelper.GetFriendlyTitle(model.Document.Title)
            });

            return(t);
        }
Esempio n. 5
0
 public IActionResult OnPost(string shortenedUrl, string password)
 {
     if (shortenedUrl.Length > 5)
     {
         var mapping = _context.CustomMapping.Find(Base62.Decode(shortenedUrl));
         if (password != mapping.Password)
         {
             return(RedirectToPage("./VerifyPassword", new { shortenedUrl = shortenedUrl }));
         }
         else
         {
             ImageBase64String = "data:image/" + Path.GetExtension(mapping.Original).Substring(1) + ";base64," +
                                 Extension.ConvertToBase64(new FileStream(mapping.Original, FileMode.Open, FileAccess.Read));
             return(Page());
         }
     }
     else
     {
         var mapping = _context.Mapping.Find(Base62.Decode(shortenedUrl));
         if (password != mapping.Password)
         {
             return(RedirectToPage("./VerifyPassword", new { shortenedUrl = shortenedUrl }));
         }
         else
         {
             ImageBase64String = "data:image/" + Path.GetExtension(mapping.Original).Substring(1) + ";base64," +
                                 Extension.ConvertToBase64(new FileStream(mapping.Original, FileMode.Open, FileAccess.Read));
             return(Page());
         }
     }
 }
        public void FromBase62Chars11_WithOverlappingInputAndOutputSpans_ShouldReturnExpectedOutput(string text, string base62String)
        {
            Span <byte> bytes = stackalloc byte[11];

            System.Text.Encoding.UTF8.GetBytes(base62String, bytes);
            Base62.FromBase62Chars11(bytes, bytes);
            var originalString = System.Text.Encoding.UTF8.GetString(bytes[..8]);
Esempio n. 7
0
 public ActionResult OnGet(string shortenedUrl)
 {
     if (shortenedUrl.Length > 5)
     {
         var mapping = _context.CustomMapping.Find(Base62.Decode(shortenedUrl));
         if (!string.IsNullOrWhiteSpace(mapping.Password))
         {
             return(RedirectToPage("./VerifyPassword", new { shortenedUrl = shortenedUrl }));
         }
         else
         {
             VideoSource = "/StreamSource?shortenedUrl=" + shortenedUrl;
             VideoType   = "video/" + mapping.Original.Split(".").Last();
             return(Page());
         }
     }
     else
     {
         var mapping = _context.Mapping.Find(Base62.Decode(shortenedUrl));
         if (!string.IsNullOrWhiteSpace(mapping.Password))
         {
             return(RedirectToPage("./VerifyPassword", new { shortenedUrl = shortenedUrl }));
         }
         else
         {
             VideoSource = "/StreamSource?shortenedUrl=" + shortenedUrl;
             VideoType   = "video/" + mapping.Original.Split(".").Last();
             return(Page());
         }
     }
 }
        private void PostAuthenticateRequest(object sender, EventArgs e)
        {
            var url            = HttpContext.Current.Request.Path;
            var rootPathLength = Utils.ApplicationPath.Length;

            url = url.Length > rootPathLength?url.Substring(rootPathLength) : string.Empty;

            if (!url.StartsWith("!"))
            {
                return;
            }

            try {
                var pageInstanceId = Base62.Decode(url.Substring(1));
                var pageUrl        = PageFactory.GetUrlForPageInstanceId(pageInstanceId);
                if (string.IsNullOrEmpty(pageUrl))
                {
                    return;
                }

                var response = HttpContext.Current.Response;
                response.Status = "301 Moved Permanently";
                response.AddHeader("Location", pageUrl);
                response.End();
            }
            catch {
                // Let the rest of the URL handlers take care of this URL
            }
        }
Esempio n. 9
0
        public void Unicode()
        {
            var ascii      = "سلام من اسکی هستم";
            var base62     = Base62.Encode62(ascii);
            var ascii_back = Base62.Decode62(base62);

            Assert.Equal(ascii, ascii_back, StringComparer.Ordinal);
        }
Esempio n. 10
0
        public void Ascii()
        {
            var ascii      = "Hello I'm ASCII";
            var base62     = Base62.Encode62(ascii);
            var ascii_back = Base62.Decode62(base62);

            Assert.Equal(ascii, ascii_back, StringComparer.Ordinal);
        }
Esempio n. 11
0
        public IActionResult Decode([HttpTrigger(AuthorizationLevel.Anonymous, "get", Route = "encoder/decode")] HttpRequest req)
        {
            if (!req.QueryString.HasValue)
            {
                return(new BadRequestObjectResult(Properties.Resources.Encoder_MissingDecodeQuery));
            }

            return(new OkObjectResult(Base62.Decode(req.QueryString.Value.TrimStart('?'))));
        }
Esempio n. 12
0
        public void TryParse_InvalidValue_False()
        {
            const string invalidString = "המסלול-האקדמי-המכללה-למנהל";
            var          result        = Base62.TryParse(invalidString, out var p);

            result.Should().BeFalse();
            p.Value.Should().Be(0);
            p.ToString().Should().Be("0");
        }
Esempio n. 13
0
 public IActionResult OnGet(string shortenedUrl)
 {
     if (shortenedUrl == null)
     {
         return(Page());
     }
     else
     {
         if (shortenedUrl.Length > 5)
         {
             var mapping = _context.CustomMapping.Find(Base62.Decode(shortenedUrl));
             if (mapping == null)
             {
                 ErrorMessage = "Not Found";
                 return(Page());
             }
             if (!string.IsNullOrWhiteSpace(mapping.Password))
             {
                 return(RedirectToPage("./VerifyPassword", new { shortenedUrl = shortenedUrl }));
             }
             return(Redirect(mapping.Original));
         }
         else
         {
             var mapping = _context.Mapping.Find(Base62.Decode(shortenedUrl));
             if (mapping == null)
             {
                 ErrorMessage = "Not Found";
                 return(Page());
             }
             if (!string.IsNullOrWhiteSpace(mapping.Password))
             {
                 return(RedirectToPage("./VerifyPassword", new { shortenedUrl = shortenedUrl }));
             }
             if (mapping.MappingType == MappingType.URL)
             {
                 return(Redirect(mapping.Original));
             }
             else if (mapping.MappingType == MappingType.IMAGE)
             {
                 return(RedirectToPage("./ImageContent", new { shortenedUrl = shortenedUrl }));
             }
             else if (mapping.MappingType == MappingType.VIDEO)
             {
                 return(RedirectToPage("./VideoContent", new { shortenedUrl = shortenedUrl }));
             }
             else if (mapping.MappingType == MappingType.AUDIO)
             {
                 return(RedirectToPage("./AudioContent", new { shortenedUrl = shortenedUrl }));
             }
             else
             {
                 return(BadRequest());
             }
         }
     }
 }
Esempio n. 14
0
        /// <summary>
        /// Branca specification-level token generation
        /// </summary>
        /// <param name="payload">The payload to be encrypted into the Branca token</param>
        /// <param name="key">32-byte private key used to encrypt and decrypt the Branca token</param>
        /// <returns>Base62 encoded Branca Token</returns>
        public virtual string CreateToken(string payload, byte[] key)
        {
            if (string.IsNullOrWhiteSpace(payload))
            {
                throw new ArgumentNullException(nameof(payload));
            }
            if (!IsValidKey(key))
            {
                throw new InvalidOperationException("Invalid encryption key");
            }

            var nonce = new byte[24];

            RandomNumberGenerator.Create().GetBytes(nonce);

            var timestamp = Convert.ToUInt32(DateTimeOffset.UtcNow.ToUnixTimeSeconds());

            // header
            var header = new byte[29];

            using (var stream = new MemoryStream(header))
            {
                // version
                stream.WriteByte(0xBA);

                // timestamp
                stream.Write(BitConverter.GetBytes(timestamp), 0, 4);

                // nonce
                stream.Write(nonce, 0, nonce.Length);
            }

            var keyMaterial = new KeyParameter(key);
            var parameters  = new ParametersWithIV(keyMaterial, nonce);

            var engine = new XChaChaEngine();

            engine.Init(true, parameters);

            var plaintextBytes = Encoding.UTF8.GetBytes(payload);
            var ciphertext     = new byte[plaintextBytes.Length + 16];

            engine.ProcessBytes(plaintextBytes, 0, plaintextBytes.Length, ciphertext, 0);

            var poly = new Poly1305();

            poly.Init(keyMaterial);
            poly.BlockUpdate(header, 0, header.Length);
            poly.DoFinal(ciphertext, plaintextBytes.Length);

            var tokenBytes = new byte[header.Length + ciphertext.Length];

            Buffer.BlockCopy(header, 0, tokenBytes, 0, header.Length);
            Buffer.BlockCopy(ciphertext, 0, tokenBytes, header.Length, ciphertext.Length);

            return(Base62.Encode(tokenBytes));
        }
        public void ToBase62Chars8_WithOverlappingInputAndOutputSpans_ShouldReturnExpectedOutput(string text, string base62String)
        {
            Span <byte> bytes = stackalloc byte[11];

            System.Text.Encoding.UTF8.GetBytes(text, bytes);
            Base62.ToBase62Chars8(bytes, bytes);
            var outputString = System.Text.Encoding.UTF8.GetString(bytes);

            Assert.Equal(base62String, outputString);
        }
        public void FromBase62Chars11_Regularly_ShouldReturnExpectedOutput(string text, string base62String)
        {
            var         chars       = System.Text.Encoding.UTF8.GetBytes(base62String);
            Span <byte> outputBytes = stackalloc byte[text.Length];

            Base62.FromBase62Chars11(chars, outputBytes);
            var originalString = System.Text.Encoding.UTF8.GetString(outputBytes);

            Assert.Equal(text, originalString);
        }
        public void ToBase62Chars16_Regularly_ShouldReturnExpectedOutput(string text, string base62String)
        {
            var         bytes       = System.Text.Encoding.UTF8.GetBytes(text);
            Span <byte> outputChars = stackalloc byte[base62String.Length];

            Base62.ToBase62Chars16(bytes, outputChars);
            var outputString = System.Text.Encoding.UTF8.GetString(outputChars);

            Assert.Equal(base62String, outputString);
        }
Esempio n. 18
0
        public void ValidateToken_CiphertextModification_ExpectSecurityTokenException()
        {
            var handler = new BrancaTokenHandler();

            var token   = handler.CreateToken("test", key);
            var decoded = Base62.Decode(token);

            decoded[decoded.Length - 17] ^= 1; // Last byte before the Poly1305 tag

            Assert.Throws <CryptographicException>(() => handler.DecryptToken(Base62.Encode(decoded), key));
        }
        public void CreateToken_WhenTokenGenerated_ExpectBas62EncodedTokenWithCorrectLength()
        {
            var payload = Guid.NewGuid().ToString();
            var handler = new BrancaTokenHandler();

            var token = handler.CreateToken(payload, validKey);

            token.Any(x => !Base62.CharacterSet.Contains(x)).Should().BeFalse();
            Base62.Decode(token).Length.Should().Be(
                System.Text.Encoding.UTF8.GetBytes(payload).Length + 29 + 16);
        }
Esempio n. 20
0
        public void WithRandomBytes_ExpectCorrectValuesEncoded()
        {
            var bytes = new byte[128];
            var rng   = RandomNumberGenerator.Create();

            rng.GetBytes(bytes);

            var encodedBytes = Base62.Encode(bytes);

            Base62.Decode(encodedBytes).Should().BeEquivalentTo(bytes);
        }
        /// <summary>
        /// Branca specification level token decryption.
        /// </summary>
        /// <param name="token">Base62 encoded Branca token</param>
        /// <param name="key">32-byte private key used to encrypt and decrypt the Branca token</param>
        /// <returns>Pared and decrypted Branca Token</returns>
        public virtual BrancaToken DecryptToken(string token, byte[] key)
        {
            if (string.IsNullOrWhiteSpace(token))
            {
                throw new ArgumentNullException(nameof(token));
            }
            if (!CanReadToken(token))
            {
                throw new InvalidCastException("Unable to read token");
            }
            if (!IsValidKey(key))
            {
                throw new InvalidOperationException("Invalid decryption key");
            }

            var tokenBytes = Base62.Decode(token);

            using (var stream = new MemoryStream(tokenBytes, false))
            {
                // header
                var header = GuaranteedRead(stream, 29);

                byte[] nonce;
                uint   timestamp;
                using (var headerStream = new MemoryStream(header))
                {
                    // version
                    var version = headerStream.ReadByte();
                    if (version != 0xBA)
                    {
                        throw new SecurityTokenException("Unsupported Branca version");
                    }

                    // timestamp (big endian uint32)
                    var timestampBytes = GuaranteedRead(headerStream, 4).Reverse().ToArray();
                    timestamp = BitConverter.ToUInt32(timestampBytes, 0);

                    // nonce
                    nonce = GuaranteedRead(headerStream, 24);
                }

                // ciphertext
                var ciphertextLength = stream.Length - stream.Position - TagLength;
                var ciphertext       = GuaranteedRead(stream, (int)ciphertextLength);
                var tag = GuaranteedRead(stream, TagLength);

                var plaintext = new byte[ciphertextLength];
                new XChaCha20Poly1305(key).Decrypt(nonce, ciphertext, tag, plaintext, header);

                return(new BrancaToken(
                           Encoding.UTF8.GetString(plaintext),
                           timestamp));
            }
        }
Esempio n. 22
0
 public Request(
     string personId,
     int amount,
     string description,
     string[]?keywords = default)
     : this()
 {
     IsReadOnly = false;
     // Requests only need to be unique within a person, so we use that as the prefix to disambiguate
     // multiple requests at the same UtcNow. The high-precision time also helps make that unique too.
     Raise(new RequestCreated(personId + "-" + Base62.Encode(PreciseTime.UtcNow.Ticks), amount, description, keywords, personId: personId));
 }
Esempio n. 23
0
        public Link CreateShortUrl(string url)
        {
            Link link = new Link();

            link.Redir = url;
            db.Links.Add(link);
            db.SaveChanges();
            // Now we generate a Base36 string for the DB id:
            link.Hash = Base62.Encode(link.Id);
            db.SaveChanges();
            return(link);
        }
        /// <summary>
        /// <para>
        /// Outputs an 11-character alphanumeric string representation of the given ID.
        /// </para>
        /// <para>
        /// Throws if the output span is too short.
        /// </para>
        /// </summary>
        /// <param name="id">The ID to encode.</param>
        /// <param name="bytes">At least 11 bytes, to write the alphanumeric representation to.</param>
        public static void GetAlphanumeric(ulong id, Span <byte> bytes)
        {
            if (bytes.Length < 11)
            {
                throw new IndexOutOfRangeException("At least 11 output bytes are required.");
            }

            // Abuse the caller's output span as input space
            BinaryPrimitives.WriteUInt64BigEndian(bytes, id);

            Base62.ToBase62Chars8(bytes, bytes);
        }
Esempio n. 25
0
        public void WithUtf8Characters_ExpectCorrectValuesEncoded(string testValue, string expectedResult)
        {
            var testBytes = System.Text.Encoding.UTF8.GetBytes(testValue);

            var result = Base62.Encode(testBytes);

            result.Should().Be(expectedResult);

            var decodedBytes = Base62.Decode(result);

            decodedBytes.Should().BeEquivalentTo(testBytes);
        }
Esempio n. 26
0
 static void Main(string[] args)
 {
     for (int i = 0; i < 100; i++)
     {
         string str = Base62.Encode(i);
         Console.Write($"{str}:{Base62.Decode(str)}\t");
         if (i % 10 == 0)
         {
             Console.WriteLine();
         }
     }
     Console.ReadKey();
 }
Esempio n. 27
0
        public static string Decompress(string compressedUrl, Dictionary <string, string> hostConversions = null)
        {
            InitHuffmanTree();

            byte[] urlBytes = Base62.Decode(compressedUrl);
            urlBytes = ChecksumCheck(urlBytes);
            urlBytes = _huffmanTree.Decode(urlBytes);
            string url = Encoding.ASCII.GetString(urlBytes);

            Url oUrl = Url.CreateFromShortString(url);

            // "Decompress" protocol
            if (oUrl.Protocol == "#")
            {
                oUrl.Protocol = "http";
            }
            else if (oUrl.Protocol == "$")
            {
                oUrl.Protocol = "https";
            }
            else if (oUrl.Protocol == "F")
            {
                oUrl.Protocol = "ftp";
            }
            else
            {
                throw new Exception(string.Format("Unkown protocol \"{0}\"", oUrl.Protocol));
            }

            if (hostConversions != null)
            {
                // "Decompress" hosts
                string[] urlHostParts = oUrl.Host.Split('.');
                for (int i = 0; i < urlHostParts.Length; i++)
                {
                    foreach (KeyValuePair <string, string> hostConversion in hostConversions)
                    {
                        if (urlHostParts[i] == hostConversion.Value)
                        {
                            urlHostParts[i] = hostConversion.Key;
                            break;
                        }
                    }
                }
                oUrl.Host = string.Join(".", urlHostParts);
            }

            url = oUrl.ToString();

            return(url);
        }
        public Token(DateTime tokenDate)
        {
            var partitionKey = Base62.FromDate(tokenDate);

            if (partitionKey.Length < 4)
            {
                partitionKey = partitionKey.PadLeft(4, '0');
            }
            else if (partitionKey.Length > 4)
            {
                partitionKey = partitionKey.Substring(0, 4);
            }

            PartitionKey = partitionKey;
            RowKey       = Base62.Encode(RandomNumber.Next(1, 10_000_000));
        }
Esempio n. 29
0
        public async Task <IActionResult> OnGet(string shortenedUrl)
        {
            if (shortenedUrl.Length > 5)
            {
                var mapping = await _context.CustomMapping.FindAsync(Base62.Decode(shortenedUrl));

                if (mapping.MappingType == MappingType.URL)
                {
                    FormAction = "/VerifyPassword";
                }
                else if (mapping.MappingType == MappingType.IMAGE)
                {
                    FormAction = "/ImageContent";
                }
                else if (mapping.MappingType == MappingType.VIDEO)
                {
                    FormAction = "/VideoContent";
                }
                else if (mapping.MappingType == MappingType.AUDIO)
                {
                    FormAction = "/AudioContent";
                }
            }
            else
            {
                var mapping = await _context.Mapping.FindAsync(Base62.Decode(shortenedUrl));

                if (mapping.MappingType == MappingType.URL)
                {
                    FormAction = "/VerifyPassword";
                }
                else if (mapping.MappingType == MappingType.IMAGE)
                {
                    FormAction = "/ImageContent";
                }
                else if (mapping.MappingType == MappingType.VIDEO)
                {
                    FormAction = "/VideoContent";
                }
                else if (mapping.MappingType == MappingType.AUDIO)
                {
                    FormAction = "/AudioContent";
                }
            }
            ShortenedUrl = shortenedUrl;
            return(Page());
        }
        /// <summary>
        /// Branca specification-level token generation
        /// </summary>
        /// <param name="payload">The payload to be encrypted into the Branca token</param>
        /// <param name="timestamp">The timestamp included in the Branca token (iat: issued at)</param>
        /// <param name="key">32-byte private key used to encrypt and decrypt the Branca token</param>
        /// <returns>Base62 encoded Branca Token</returns>
        public virtual string CreateToken(string payload, uint timestamp, byte[] key)
        {
            if (string.IsNullOrWhiteSpace(payload))
            {
                throw new ArgumentNullException(nameof(payload));
            }
            if (!IsValidKey(key))
            {
                throw new InvalidOperationException("Invalid encryption key");
            }

            var nonce = new byte[24];

            using (var rng = RandomNumberGenerator.Create())
            {
                rng.GetBytes(nonce);
            }

            // header
            var header = new byte[29];

            using (var stream = new MemoryStream(header))
            {
                // version
                stream.WriteByte(0xBA);

                // timestamp (big endian uint32)
                stream.Write(BitConverter.GetBytes(timestamp).Reverse().ToArray(), 0, 4);

                // nonce
                stream.Write(nonce, 0, nonce.Length);
            }

            var plaintext  = Encoding.UTF8.GetBytes(payload);
            var ciphertext = new byte[plaintext.Length];
            var tag        = new byte[TagLength];

            new XChaCha20Poly1305(key).Encrypt(nonce, plaintext, ciphertext, tag, header);

            var tokenBytes = new byte[header.Length + ciphertext.Length + TagLength];

            Buffer.BlockCopy(header, 0, tokenBytes, 0, header.Length);
            Buffer.BlockCopy(ciphertext, 0, tokenBytes, header.Length, ciphertext.Length);
            Buffer.BlockCopy(tag, 0, tokenBytes, tokenBytes.Length - TagLength, tag.Length);

            return(Base62.Encode(tokenBytes));
        }