views:

135

answers:

4

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?

+3  A: 

What you need to do is to look into the System.Security.Cryptography namespace.

Edit:
In one line of code? OK*:

public static string Encrypt(string plaintext, string password)
{
  return Convert.ToBase64String((new AesManaged {Key = Encoding.UTF8.GetBytes(password)}).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) }).CreateDecryptor().TransformFinalBlock(Convert.FromBase64String(ciphertext), 0, Convert.FromBase64String(ciphertext).Length));
}

*Code not tested

Sani Huttunen
Most of it generate arrays of bytes that converted to a string doesn't look pretty to put in a url. And I couldn't find a simple way to do it.
BrunoLM
Just convert the array byte to Base64. That is the usual approach. It's one line of code.
Sani Huttunen
+2  A: 
  • ROT13
  • ROT26
  • reverse-the-order-of-the-characters
  • application/x-www-form-urlencoded
  • encode_hex(aes_256(secret_key, known_iv, to_utf_8(value)))
  • store the string and a randomly-generated lookup key in a persistent dictionary (like a database table with columns string and lookup_key)
Justice
+1  A: 

Check a similar question here.

Eugene Mayevski 'EldoS Corp
+4  A: 

Hi BrunoLM, 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()));
André Gadonski
Seems there isn't an easier way. I was going to do that if I couldn't find another way. Thanks for posting it!
BrunoLM