Пример #1
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());
         }
     }
 }
Пример #2
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));
         }
     }
 }
Пример #3
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());
         }
     }
 }
Пример #4
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
            }
        }
Пример #6
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('?'))));
        }
Пример #7
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());
             }
         }
     }
 }
        /// <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));
            }
        }
Пример #9
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);
        }
        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);
        }
Пример #11
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));
        }
Пример #12
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);
        }
Пример #13
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();
 }
Пример #14
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);
        }
Пример #15
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());
        }
Пример #16
0
        public async Task <IActionResult> OnPost(string shortenedUrl, string password)
        {
            if (shortenedUrl.Length > 5)
            {
                var mapping = await _context.CustomMapping.FindAsync(Base62.Decode(shortenedUrl));

                if (mapping == null)
                {
                    return(NotFound());
                }
                else if (mapping.Password == password)
                {
                    return(Redirect(mapping.Original));
                }
                else
                {
                    ShortenedUrl = shortenedUrl;
                    ErrorMessage = "Wrong Password!";
                    return(Page());
                }
            }
            else
            {
                var mapping = await _context.Mapping.FindAsync(Base62.Decode(shortenedUrl));

                if (mapping == null)
                {
                    return(NotFound());
                }
                else if (mapping.Password == password)
                {
                    return(Redirect(mapping.Original));
                }
                else
                {
                    ShortenedUrl = shortenedUrl;
                    ErrorMessage = "Wrong Password!";
                    return(Page());
                }
            }
        }
Пример #17
0
        /// <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
                    var timestampBytes = GuaranteedRead(headerStream, 4);
                    timestamp = BitConverter.ToUInt32(timestampBytes, 0);

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

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

                // tag
                var tag = GuaranteedRead(stream, 16);

                // XChaCha20-Poly1305
                var keyMaterial = new KeyParameter(key);
                var parameters  = new ParametersWithIV(keyMaterial, nonce);

                var headerMac = new byte[16];
                var poly1305  = new Poly1305();
                poly1305.Init(keyMaterial);
                poly1305.BlockUpdate(header, 0, header.Length);
                poly1305.DoFinal(headerMac, 0);

                if (!headerMac.SequenceEqual(tag))
                {
                    throw new SecurityTokenException("Invalid message authentication code");
                }

                var engine = new XChaChaEngine();
                engine.Init(false, parameters);
                var decryptedPlaintext = new byte[ciphertext.Length];
                engine.ProcessBytes(ciphertext, 0, ciphertext.Length, decryptedPlaintext, 0);

                return(new BrancaToken(
                           Encoding.UTF8.GetString(decryptedPlaintext),
                           timestamp));
            }
        }