Is there a way to shorten a URL QueryString?

Donald Symmons 3,066 Reputation points
2023-05-04T08:14:48.1033333+00:00

In trying to shorten url QueryString, I bumped into an article that encrypts a url. May I please know if this is best way for this or shortening the url is preferred?

If it is to shorten a url, Please how do I do this?

Thank you.

Here is the code that encrypts url

 protected void Button1_Click(object sender, EventArgs e)
        {
            string PageNumber = "00637";
            Session["PageID"] = PageNumber;

            var plaintextBytes = Encoding.UTF8.GetBytes("Max");

            //---- Encrypt text.
            var encryptedValue = Convert.ToBase64String(MachineKey.Protect(plaintextBytes, PageNumber));

            //--- URL encode to make encrypted value URL compatible.
            encryptedValue = HttpUtility.UrlEncode(encryptedValue);

            //---- Send encrypted value as query string.
            Response.Redirect("Default3.aspx?Id=" + encryptedValue);
        }
        public static string Decrypt(string TextToBeDecrypted)
        {
            RijndaelManaged RijndaelCipher = new RijndaelManaged();

            string Password = "CSC";
            string DecryptedData;

            try
            {
                byte[] EncryptedData = Convert.FromBase64String(TextToBeDecrypted);

                byte[] Salt = Encoding.ASCII.GetBytes(Password.Length.ToString());
                //Making of the key for decryption
                PasswordDeriveBytes SecretKey = new PasswordDeriveBytes(Password, Salt);
                //Creates a symmetric Rijndael decryptor object.
                ICryptoTransform Decryptor = RijndaelCipher.CreateDecryptor(SecretKey.GetBytes(32), SecretKey.GetBytes(16));

                MemoryStream memoryStream = new MemoryStream(EncryptedData);
                //Defines the cryptographics stream for decryption.THe stream contains decrpted data
                CryptoStream cryptoStream = new CryptoStream(memoryStream, Decryptor, CryptoStreamMode.Read);

                byte[] PlainText = new byte[EncryptedData.Length];
                int DecryptedCount = cryptoStream.Read(PlainText, 0, PlainText.Length);
                memoryStream.Close();
                cryptoStream.Close();

                //Converting to string
                DecryptedData = Encoding.Unicode.GetString(PlainText, 0, DecryptedCount);
            }
            catch
            {
                DecryptedData = TextToBeDecrypted;
            }
            return DecryptedData;
        }

        public static string Encrypt(string TextToBeEncrypted)
        {
            RijndaelManaged RijndaelCipher = new RijndaelManaged();
            string Password = "CSC";
            byte[] PlainText = System.Text.Encoding.Unicode.GetBytes(TextToBeEncrypted);
            byte[] Salt = Encoding.ASCII.GetBytes(Password.Length.ToString());
            PasswordDeriveBytes SecretKey = new PasswordDeriveBytes(Password, Salt);
            //Creates a symmetric encryptor object. 
            ICryptoTransform Encryptor = RijndaelCipher.CreateEncryptor(SecretKey.GetBytes(32), SecretKey.GetBytes(16));
            MemoryStream memoryStream = new MemoryStream();
            //Defines a stream that links data streams to cryptographic transformations
            CryptoStream cryptoStream = new CryptoStream(memoryStream, Encryptor, CryptoStreamMode.Write);
            cryptoStream.Write(PlainText, 0, PlainText.Length);
            //Writes the final state and clears the buffer
            cryptoStream.FlushFinalBlock();
            byte[] CipherBytes = memoryStream.ToArray();
            memoryStream.Close();
            cryptoStream.Close();
            string EncryptedData = Convert.ToBase64String(CipherBytes);

            return EncryptedData;
        }

And on the next page where the url points to, the url is decrypted

protected void Page_Load(object sender, EventArgs e)
        {
            if (!string.IsNullOrEmpty(Request.QueryString.ToString()))
            {
                var bytes = Convert.FromBase64String(Request.QueryString["Id"].ToString());
                var output = MachineKey.Unprotect(bytes, PageNumber);
                Response.Write(Encoding.UTF8.GetString(output));
            }
        }
Developer technologies .NET Other
Developer technologies ASP.NET Other
Developer technologies C#
{count} votes

Accepted answer
  1. QiYou-MSFT 4,326 Reputation points Microsoft External Staff
    2023-05-08T06:31:52.76+00:00

    Hi @Donald Symmons

    Based on the code you gave, I think you want to use the MD5 algorithm for the 16-base string and 0x3fffffff (30-bit 1) AND operation.Due to the algorithm, multiple results will end up and there may be duplicate results. Finally, the effect is achieved by saving to the database for mapping.

    Code:

    static void Main(string[] args)
              {
                  Random rd = new Random();
                string url = "https://localhost:44316/regpage.aspx";
                string str = "https://localhost:44316/regpage.aspx?id=321321321";
                string[] resAry = str.Split(new string[] { url }, StringSplitOptions.None);
                Console.WriteLine(resAry[1]);
                for (int i = 0; i< 100; i++)
                 {
                     int index = rd.Next(0, 4);
                     var stortUrls = ShortUrl(resAry[1]);
                     Console.WriteLine( url+'/'+stortUrls[index]);
                 }
                 Console.Read();
             }
             public static string[] ShortUrl(string url)
             {        
                 string key = "key";
                 string[] chars = new string[]
                 {
                    "a", "b", "c", "d", "e", "f", "g", "h",
                     "i", "j", "k", "l", "m", "n", "o", "p",
                     "q", "r", "s", "t", "u", "v", "w", "x",
                     "y", "z", "0", "1", "2", "3", "4", "5",
                     "6", "7", "8", "9", "A", "B", "C", "D",
                     "E", "F", "G", "H", "I", "J", "K", "L",
                     "M", "N", "O", "P", "Q", "R", "S", "T",
                     "U", "V", "W", "X", "Y", "Z"
                 };
                 string hex = FormsAuthentication.HashPasswordForStoringInConfigFile(key + url, "md5");
                     string[] resUrl = new string[4];
                     for (int i = 0; i < 4; i++)
                         {
                             
                     int hexint = 0x3FFFFFFF & Convert.ToInt32("0x" + hex.Substring(i * 8, 8), 16);
                             string outChars = string.Empty;
                             for (int j = 0; j < 6; j++)
                                 {
                                     
                         int index = 0x0000003D & hexint;
                                     
                         outChars += chars[index];
                                     
                         hexint = hexint >> 5;
                                 }
                             
                     resUrl[i] = outChars;
                         }
                     return resUrl;
                 }
    

    Output:

    Picture1

    Best Regards

    Qi You


    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.


1 additional answer

Sort by: Most helpful
  1. Bruce (SqlWork.com) 77,686 Reputation points Volunteer Moderator
    2023-05-04T14:35:07.2+00:00

    Your question is not clear. An encrypted string will be longer, not shorter. You use encrypted values in a url when you don’t want the actual value exposed or modified.

    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.