Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Encryption and decryption without special character

I want to encrypt mail id. The encrypted mail id should not contain special characters. I send mail from console app. In console app I encode the mail id and attach it in link that will perform my click counts. In the web app I am decoding the mail id passed. So if encrypted mail id contains special character it is disturbing my link.

I am using following:

    string EncryptedEmailId;
    string EncryptionKey = "MAKV2SPBNI99212";
    byte[] EmailIdEncrypt = Encoding.Unicode.GetBytes(InvEmail);

    using (Aes encryptor = Aes.Create())
    {
          Rfc2898DeriveBytes pdbEncrypt = new Rfc2898DeriveBytes(EncryptionKey, new byte[] { 0x49, 0x76, 0x61, 0x6e, 0x20, 0x4d, 0x65, 0x64, 0x76, 0x65, 0x64, 0x65, 0x76 });
          encryptor.Key = pdbEncrypt.GetBytes(32);
          encryptor.IV = pdbEncrypt.GetBytes(16);
          using (MemoryStream msEncrypt = new MemoryStream())
          {
                 using (CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor.CreateEncryptor(), CryptoStreamMode.Write))
                 {
                         csEncrypt.Write(EmailIdEncrypt, 0, EmailIdEncrypt.Length);
                                    csEncrypt.Close();
                 }
                 EncryptedEmailId = Convert.ToBase64String(msEncrypt.ToArray());
          }
   }
   individualContent = individualContent.Replace("[MailId]", EncryptedEmailId);
like image 776
Ami Avatar asked Apr 22 '14 04:04

Ami


2 Answers

With the hint given by Nipun I got the answer.

a) Convert String to Hex

    public static string ConvertStringToHex(String input, System.Text.Encoding encoding)
    {
         Byte[] stringBytes = encoding.GetBytes(input);
        StringBuilder sbBytes = new StringBuilder(stringBytes.Length * 2);
        foreach (byte b in stringBytes)
         {
             sbBytes.AppendFormat("{0:X2}", b);
        }
        return sbBytes.ToString();
    }

b) Convert Hex to String

     public static string ConvertHexToString(String hexInput, System.Text.Encoding encoding)
    {
         int numberChars = hexInput.Length;
        byte[] bytes = new byte[numberChars / 2];
         for (int i = 0; i < numberChars; i += 2)
        {
            bytes[i / 2] = Convert.ToByte(hexInput.Substring(i, 2), 16);
         }
         return encoding.GetString(bytes);
    }

Sample usage code

    string testString = "MIKA@?&^";
    string hex = ConvertStringToHex(testString, System.Text.Encoding.Unicode);
    string normal = ConvertHexToString(hex, System.Text.Encoding.Unicode);
    Debug.Assert(testString.CompareTo(normal) == 0, "They are not identical");

Have a look at: http://www.nullskull.com/faq/834/convert-string-to-hex-and-hex-to-string-in-net.aspx

like image 142
Ami Avatar answered Oct 17 '22 22:10

Ami


You will need to try different Algo for the same

Try anyof the below methods and see if it works for you?

This won't be working you as you are using Console App, but can try other one. string EncryptedText = FormsAuthentication.HashPasswordForStoringInConfigFile("YourPlainText", "MD5");

Or, you may use the following encryption and decryption algorithm:

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

/// <summary>
/// Summary description for Pass
/// </summary>
public class CryptoSystem
{
    public string plainText;
    public string passPhrase = "Pas5pr@se";
    public string saltValue = "s@1tValue";
    public string hashAlgorithm = "MD5";
    public int passwordIterations = 2;
    public string initVector = "@1B2c3D4e5F6g7H8";
    public int keySize = 256;

    public string Encrypt(string plainText)
    {
        byte[] initVectorBytes = Encoding.ASCII.GetBytes(initVector);
        byte[] saltValueBytes = Encoding.ASCII.GetBytes(saltValue);
        byte[] plainTextBytes = Encoding.UTF8.GetBytes(plainText);
        PasswordDeriveBytes password = new PasswordDeriveBytes(passPhrase, saltValueBytes, hashAlgorithm, passwordIterations);
        byte[] keyBytes = password.GetBytes(keySize / 8);
        RijndaelManaged symmetricKey = new RijndaelManaged();
        symmetricKey.Mode = CipherMode.CBC;
        ICryptoTransform encryptor = symmetricKey.CreateEncryptor(keyBytes, initVectorBytes);
        MemoryStream memoryStream = new MemoryStream();
        CryptoStream cryptoStream = new CryptoStream(memoryStream, encryptor, CryptoStreamMode.Write);
        cryptoStream.Write(plainTextBytes, 0, plainTextBytes.Length);
        cryptoStream.FlushFinalBlock();
        byte[] cipherTextBytes = memoryStream.ToArray();
        memoryStream.Close();
        cryptoStream.Close();
        string cipherText = Convert.ToBase64String(cipherTextBytes);
        return cipherText;
    }

    public string Decrypt(string cipherText)
    {
        byte[] initVectorBytes = Encoding.ASCII.GetBytes(initVector);
        byte[] saltValueBytes = Encoding.ASCII.GetBytes(saltValue);        
        byte[] cipherTextBytes = Convert.FromBase64String(cipherText);
        PasswordDeriveBytes password = new PasswordDeriveBytes(passPhrase, saltValueBytes, hashAlgorithm, passwordIterations);
        byte[] keyBytes = password.GetBytes(keySize / 8);
        RijndaelManaged symmetricKey = new RijndaelManaged();
        symmetricKey.Mode = CipherMode.CBC;
        ICryptoTransform decryptor = symmetricKey.CreateDecryptor(keyBytes, initVectorBytes);
        MemoryStream memoryStream = new MemoryStream(cipherTextBytes);
        CryptoStream 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();
        string plainText = Encoding.UTF8.GetString(plainTextBytes, 0, decryptedByteCount);
        return plainText;
    }
}

Try out Hexadecimal as well http://www.string-functions.com/string-hex.aspx

To code follow this link Convert string to hex-string in C#

byte[] ba = Encoding.Default.GetBytes("sample");
var hexString = BitConverter.ToString(ba);
like image 24
Nipun Ambastha Avatar answered Oct 17 '22 23:10

Nipun Ambastha