I am trying to encode an email, send a link based on the token created and then decode the email, but my output is never the same as the input. I was wondering what I am doing wrongly here:
public IActionResult ResetPasswordLink(string email)
{
// Hash the email address
byte[] emailBytes = Encoding.UTF8.GetBytes(email);
byte[] hashedBytes;
using (var sha256 = System.Security.Cryptography.SHA256.Create())
{
hashedBytes = sha256.ComputeHash(emailBytes);
}
string hashedEmail = Convert.ToBase64String(hashedBytes);
string token =WebEncoders.Base64UrlEncode(Encoding.UTF8.GetBytes(hashedEmail));
string resetLink = $"{Request.Scheme}://{Request.Host}/resetpassword/{token}";
// Decode the token to get the hashed email
byte[] hashedEmailBytes = WebEncoders.Base64UrlDecode(token);
string decodedEmail = Encoding.UTF8.GetString(hashedEmailBytes);
Console.WriteLine("Original email: " + email);
Console.WriteLine("Decoded email: " + decodedEmail);
//SendEmail(email, resetLink);
Console.WriteLine("Token when encoding: " + token);
return Ok(resetLink);
}
The issue is that you are hashing the email address before encoding it, but you are trying to decode the encoded token directly to the hashed email address. Since the hashing process is irreversible, you won't get the original email address back from the hashed email.