Norgul
Norgul

Reputation: 4783

C# token parsing

I would like to combine date and user email to one base64 string, which now works like this:

public string GenerateUniqueToken(string email)
{
    byte[] time = BitConverter.GetBytes(DateTime.UtcNow.ToBinary());
    byte[] key = Encoding.ASCII.GetBytes(email);
    string encoded = Convert.ToBase64String(time.Concat(key).ToArray());
    return criptographyService.Encrypt(encoded);
}

I would like to parse it now so that I only get an email from the decoded string, but I am getting everything together:

public string TokenUserValid(string token)
{
    string decrypted = criptographyService.Decrypt(token);
    byte[] data = Convert.FromBase64String(decrypted);
    return Encoding.Default.GetString(data);
}

I get it in the form like this:

\�����[email protected]

Upvotes: 0

Views: 1025

Answers (2)

Scrobi
Scrobi

Reputation: 1200

As you know the length of the date you can read the time and email separately from the byte[]

//combine time and email
byte[] time = BitConverter.GetBytes(DateTime.UtcNow.ToBinary());
byte[] key = Encoding.ASCII.GetBytes("[email protected]");
string encoded = Convert.ToBase64String(time.Concat(key).ToArray());

//read time and email
byte[] data = Convert.FromBase64String(encoded);
DateTime date =  DateTime.FromBinary(BitConverter.ToInt64(data.Take(8).ToArray(), 0)); //read the date
string email  = Encoding.Default.GetString(data.Skip(8).ToArray()); //read the email

Upvotes: 3

Xeorge Xeorge
Xeorge Xeorge

Reputation: 462

Put a separator character between your date and your email name like # . Then use the string.Split(), to break them off and put them on an string array.

The email will be on the index[1], of your array, while the date on the Index[0].

Upvotes: 0

Related Questions