简体   繁体   中英

convert integer into encrypted string and vice versa

I want to pass pid as querystring parameter in URL, but instead of int like ?pid=102 or ?pid=493 , I want to pass these pid in encrypted form like ?pid=D109150A13F0EA4 or other encrypted string. I tried build-in Encrypt method but they give long length string like ?pid=F3D165BAF8D84FB17CF8E5B4A04AC9022BFF5F987A6EDC42D109150A13F0EA4D847527287C8013154E2E8A2D8DAB6B686751C079092713C0DDA3E2E932D5892361E1B486FE2F46C2E288EA54F64B8B4C

I want small alpha numeric string like ?pid=D109150A13F0EA4 or similar

Have you tried using Guid ?

var g = Guid.NewGuid(productId.ToString());

It will produce a result of 38 characters: 8 hexadecimal digits, followed by three groups of 4 hexadecimal digits each, followed by one group of 12 hexadecimal digits.

An example of a Guid: 6B29FC40-CA47-1067-B31D-00DD010662DA

So it is in fact quite short in comparison with your example. The only drawback of the Guid is that you cannot decrypt it back to int (but you can compare whether two Guids represent the same int value).

In case you need both encryption and decryption, apart from the inbuilt encrypting (I assume you have used the Encrypt method in your above example), there are many additional encryption algorithms available in System.Security.Cryptography namespace, like:

  • DES , example: 2120357ccd3e0142
  • Aes , example: 73054ef012f6ea6d47757a37a84381f7
  • HMACSHA256 , example: 6723ace2ec7b0348e1270ccbaab802bfa5c1bbdddd108aece88c739051a8a767

For those things I use a small EncryptDecrypt Class, maybe this help for your approach.

Simle usage like EncryptDecrypt.ToEncrypt(yourstring) and EncryptDecrypt.ToDecrypt(yourEncryptedString) . So you should be able to encrypt before add to your querystring. Integer and numbers, etc. you have to convert to string first then.

Hope this helps.

using System;
using System.Security.Cryptography;
using System.IO;

namespace YourNameSpace

{
    public class EncryptDecrypt
    {
        #region Declaration

        static readonly byte[] TripleDesKey1 = new byte[] { 15, 11, 7, 21, 34, 32, 33, 5, 23, 13, 23, 41, 43, 41, 7, 19, 91, 91, 47, 7, 37, 13, 19, 41 };
        static readonly byte[] TripleDesiv1 = new byte[] { 5, 23, 13, 23, 41, 43, 41, 7 };

        #endregion


        /// <summary>
        /// To Encrypt String
        /// </summary>
        /// <param name="value">String To Encrypt</param>
        /// <returns>Returns Encrypted String</returns>
        public static string ToEncrypt(string value)
        {
            TripleDESCryptoServiceProvider des = new TripleDESCryptoServiceProvider
                                                     {
                                                         Key = TripleDesKey1,
                                                         IV = TripleDesiv1
                                                     };

            MemoryStream ms;

            if (value.Length >= 1)
                ms = new MemoryStream(((value.Length * 2) - 1));
            else
                ms = new MemoryStream();

            ms.Position = 0;
            CryptoStream encStream = new CryptoStream(ms, des.CreateEncryptor(), CryptoStreamMode.Write);
            byte[] plainBytes = System.Text.Encoding.UTF8.GetBytes(value);
            encStream.Write(plainBytes, 0, plainBytes.Length);
            encStream.FlushFinalBlock();
            encStream.Close();

            return Convert.ToBase64String(plainBytes);
        }

        /// <summary>
        /// To Decrypt Data Encrypted From TripleDEC Algoritham
        /// </summary>
        /// <param name="value">String Value To Decrypt</param>
        /// <returns>Return Decrypted Data</returns>
        public static string ToDecrypt(string value)
        {
            TripleDESCryptoServiceProvider des = new TripleDESCryptoServiceProvider();
            //System.IO.MemoryStream ms = new System.IO.MemoryStream(((value.Length * 2) - 1));
            MemoryStream ms;
            if (value.Length >= 1)
                ms = new MemoryStream(((value.Length * 2) - 1));
            else
                ms = new MemoryStream();

            ms.Position = 0;
            CryptoStream encStream = new CryptoStream(ms, des.CreateDecryptor(TripleDesKey1, TripleDesiv1), CryptoStreamMode.Write);
            byte[] plainBytes = Convert.FromBase64String(value);
            encStream.Write(plainBytes, 0, plainBytes.Length);
            return System.Text.Encoding.UTF8.GetString(plainBytes);
        }

    }
}

This method is used to generate a random string

private string GetRandomString(int iStringLength)
    {
        string allowedChars = "abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNOPQRSTUVWXYZ0123456789!@$?_-";
        char[] chars = new char[iStringLength];           
            Random rd = new Random();    
            for (int i = 0; i < iStringLength; i++)
            {
                chars[i] = allowedChars[rd.Next(0, allowedChars.Length)];
            }       
            return new string(chars);           
    }

or use

var gid = Guid.NewGuid(productId.ToString());

Below method encrypts a string. just pass a normal/ random string to encrypt the string.

 protected string EncryptString(String strString)
    {            
            UnicodeEncoding uEncode = new UnicodeEncoding();
            Byte[] bytstrString = uEncode.GetBytes(strString);
            SHA256Managed sha1 = new SHA256Managed();
            Byte[] hash = sha1.ComputeHash(bytstrString);

            return Convert.ToBase64String(hash);

    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM