How to encrypt to a url safe string...


Hello,

Here's a helper that can be used to encrypt/decrypt ids that are url safe.

For example, if your user needs to download an invoice, it's clearly more secure to provide a url like 

http://yousite.com/download-invoice/TVZiSlU0a0VHWnlZR2NTOTRwYy9Sdz09

instead of:

http://yousite.com/download-invoice/13

As there can be a malicious user that will try to download invoices from others, or you don't want the user to know what the invoice id is.

Example, in your controller:



[ActionName("download-invoice")]
        public FileResult downloadInvoice(string id)
        {
            var decodeId =int.Parse(id.DecryptBase64());
            var invoice = MainService.getInvoiceById(decodeId);
            if (invoice == null)
                throw new HttpException(404, "Not Found");
            return File(MainService.generateInvoicePDF(decodeId), "application/pdf");
        }      


In your view:

<li>Invoice<a target="_blank" href="/download-invoice/@Model.invoiceId.ToString().EncryptBase64()"><img src="~/Content/img/MyAccount/download_document.png" width="20" /></a></li>


In your helpers class or whatsoever:

        static readonly string PasswordHash = "mySecretHash";
        static readonly string SaltKey = "S@LT&KEY";
        static readonly string VIKey = "@1B2c3D4e5F6g7H8"; 


public static string EncryptBase64(this string plainText)
        {
            byte[] plainTextBytes = Encoding.UTF8.GetBytes(plainText);

            byte[] keyBytes = new Rfc2898DeriveBytes(PasswordHash, Encoding.ASCII.GetBytes(SaltKey)).GetBytes(256 / 8);
            var symmetricKey = new RijndaelManaged() { Mode = CipherMode.CBC, Padding = PaddingMode.Zeros };
            var encryptor = symmetricKey.CreateEncryptor(keyBytes, Encoding.ASCII.GetBytes(VIKey));

            byte[] cipherTextBytes;

            using (var memoryStream = new MemoryStream())
            {
                using (var cryptoStream = new CryptoStream(memoryStream, encryptor, CryptoStreamMode.Write))
                {
                    cryptoStream.Write(plainTextBytes, 0, plainTextBytes.Length);
                    cryptoStream.FlushFinalBlock();
                    cipherTextBytes = memoryStream.ToArray();
                    cryptoStream.Close();
                }
                memoryStream.Close();
            }
            return Convert.ToBase64String(cipherTextBytes).Base64Encode();
        }

       
        public static string DecryptBase64(this string encryptedText)
        {   
            byte[] cipherTextBytes = Convert.FromBase64String(encryptedText.Base64Decode());
            byte[] keyBytes = new Rfc2898DeriveBytes(PasswordHash, Encoding.ASCII.GetBytes(SaltKey)).GetBytes(256 / 8);
            var symmetricKey = new RijndaelManaged() { Mode = CipherMode.CBC, Padding = PaddingMode.None };

            var decryptor = symmetricKey.CreateDecryptor(keyBytes, Encoding.ASCII.GetBytes(VIKey));
            var memoryStream = new MemoryStream(cipherTextBytes);
            var cryptoStream = new CryptoStream(memoryStream, decryptor, CryptoStreamMode.Read);
            byte[] plainTextBytes = new byte[cipherTextBytes.Length];

            int decryptedByteCount = cryptoStream.Read(plainTextBytes, 0, plainTextBytes.Length);
            memoryStream.Close();
            cryptoStream.Close();
            return Encoding.UTF8.GetString(plainTextBytes, 0, decryptedByteCount).TrimEnd("\0".ToCharArray());
        }

     public static string Base64Encode(this string plainText)
        {
            var plainTextBytes = System.Text.Encoding.UTF8.GetBytes(plainText);
            return System.Convert.ToBase64String(plainTextBytes);
        }

public static string Base64Decode(this string base64EncodedData)
        {
            var base64EncodedBytes = System.Convert.FromBase64String(base64EncodedData);
            return System.Text.Encoding.UTF8.GetString(base64EncodedBytes);
        }


Enjoy!!!

Commentaires

Posts les plus consultés de ce blog

How to delete many-to-many relationship in Entity Framework...

Html to Image...