I want to generate a link
http://site/?code=xxxxxxxxxx
Where xxxxxxxxxx
is an encrypted string generated from the string user01
. And I will need to convert it back later.
Is there a simple way to encrypt and decrypt a string like this?
I want to generate a link
http://site/?code=xxxxxxxxxx
Where xxxxxxxxxx
is an encrypted string generated from the string user01
. And I will need to convert it back later.
Is there a simple way to encrypt and decrypt a string like this?
What you need to do is to look into the System.Security.Cryptography namespace.
Edit:
In one line of code? OK:
class Program
{
static void Main(string[] args)
{
Console.WriteLine(Decrypt(Encrypt("This is a sample", "thisismypassword"), "thisismypassword"));
}
public static string Encrypt(string plaintext, string password)
{
return Convert.ToBase64String((new AesManaged { Key = Encoding.UTF8.GetBytes(password), Mode = CipherMode.ECB }).CreateEncryptor().TransformFinalBlock(Encoding.UTF8.GetBytes(plaintext), 0, Encoding.UTF8.GetBytes(plaintext).Length));
}
public static string Decrypt(string ciphertext, string password)
{
return Encoding.UTF8.GetString((new AesManaged { Key = Encoding.UTF8.GetBytes(password), Mode = CipherMode.ECB }).CreateDecryptor().TransformFinalBlock(Convert.FromBase64String(ciphertext), 0, Convert.FromBase64String(ciphertext).Length));
}
}
you can try this to convert your string. It is going to convert to Base64
and to then hex allowing you to put on the URL.
var inputString = "xxxxx";
var code = Convert.ToBase64String((new ASCIIEncoding()).GetBytes(inputString)).ToCharArray().Select(x => String.Format("{0:X}", (int)x)).Aggregate(new StringBuilder(), (x, y) => x.Append(y)).ToString();
and this to get the string back, from hex to Base64
and from Base64
to your original string
var back = (new ASCIIEncoding()).GetString(Convert.FromBase64String(Enumerable.Range(0, code.Length / 2).Select(i => code.Substring(i * 2, 2)).Select(x => (char)Convert.ToInt32(x, 16)).Aggregate(new StringBuilder(), (x, y) => x.Append(y)).ToString()));