Create a unique key to stay in the application;
private const string Senha = "suaSenhaParaComparar";
Here you call the function to create the encryption-based token:
var token = Criptografar(login, senha);
This token you generated, you can use it throughout your application, you can still pass a date to compare and check if the token is still valid.
The function below will be responsible for encrypting the data and returning the token.
public string Criptografar(string login, string senha)
{
string passw = login + "&" + senha;
string EncryptionKey = Senha;
byte[] clearBytes = Encoding.Unicode.GetBytes(passw );
using (Aes encryptor = Aes.Create())
{
Rfc2898DeriveBytes pdb = new Rfc2898DeriveBytes(EncryptionKey, new byte[] { 0x49, 0x76, 0x61, 0x6e, 0x20, 0x4d, 0x65, 0x64, 0x76, 0x65, 0x64, 0x65, 0x76 });
encryptor.Key = pdb.GetBytes(32);
encryptor.IV = pdb.GetBytes(16);
using (MemoryStream ms = new MemoryStream())
{
using (CryptoStream cs = new CryptoStream(ms, encryptor.CreateEncryptor(), CryptoStreamMode.Write))
{
cs.Write(clearBytes, 0, clearBytes.Length);
cs.Close();
}
texto = Convert.ToBase64String(ms.ToArray());
}
}
return texto;
}
When you want to check the token, you can get it like this:
var verificaToken = Descriptografar(token);
string[] words = verificaToken.Split(&);
var usuario = words[0];
var senha = words[1];
public string Descriptografar(string texto)
{
try
{
string EncryptionKey = Senha;
texto = texto.Replace(" ", "+");
byte[] cipherBytes = Convert.FromBase64String(texto);
using (Aes encryptor = Aes.Create())
{
Rfc2898DeriveBytes pdb = new Rfc2898DeriveBytes(EncryptionKey, new byte[] { 0x49, 0x76, 0x61, 0x6e, 0x20, 0x4d, 0x65, 0x64, 0x76, 0x65, 0x64, 0x65, 0x76 });
encryptor.Key = pdb.GetBytes(32);
encryptor.IV = pdb.GetBytes(16);
using (MemoryStream ms = new MemoryStream())
{
using (CryptoStream cs = new CryptoStream(ms, encryptor.CreateDecryptor(), CryptoStreamMode.Write))
{
cs.Write(cipherBytes, 0, cipherBytes.Length);
cs.Close();
}
texto = Encoding.Unicode.GetString(ms.ToArray());
}
}
}
catch (Exception)
{
texto = null;
}
return texto;
}
In this example, I generated a simple token based on encrypted data, which in the future will be able to decrypt and log into the database based on the data ... As I said earlier, you can use an extra logic to make your token even more using dates and lifetime.