我正在尝试弄清楚如何解密在以下帖子中创建的下载令牌https://stackoverflow.com/a/4324115/487892
public static string GetDownloadToken(int fileId)
{
byte[] idbytes = BitConverter.GetBytes(fileId); // 4 bytes
byte[] dateTimeBytes = BitConverter.GetBytes(DateTime.Now.ToBinary()); // 8 bytes
byte[] buffer = new byte[16]; // minimum for an encryption block
string password = "password";
byte[] passwordBytes = Encoding.ASCII.GetBytes(password);
Array.Copy(idbytes, 0, buffer, 0, idbytes.Length);
Array.Copy(dateTimeBytes, 0, buffer, idbytes.Length, dateTimeBytes.Length);
byte[] encryptedBuffer = new byte[256];
using (SHA1CryptoServiceProvider sha1 = new SHA1CryptoServiceProvider())
{
int count = sha1.TransformBlock(buffer, 0, buffer.Length, encryptedBuffer, 0);
return Convert.ToBase64String(encryptedBuffer, 0, count);
}
}
我的主要兴趣是如何获取日期以便我可以将其与当前日期进行比较,以便我可以在一段时间后使令牌过期?这不是一个单向哈希?
答案 0 :(得分:3)
这里的“加密”并不是真正的加密,而是“哈希”。使用加密,您可以加密(使数据不可读)和解密(使其再次可读)。
使用散列过程是不可逆的,即你无法从散列函数计算的值中检索原始数据,在本例中为sha1.TransformBlock(..)。
如果你真的想加密并具有解密能力,你需要使用不同的机制 - 即不是散列函数。
这是一个非常详细的SO链接,提供了更多信息:Fundamental difference between Hashing and Encryption algorithms
对我来说,你的选择似乎是: