我需要使某个URL仅在48小时内有效,此链接在服务器上生成并通过电子邮件发送给客户端.
我想做的是在服务器上嵌入编码的时间戳.
这种情况的最佳做法是什么?
如果你想像@craig1231 建议的那样实施你的检查,谁使用你的想法“编码”时间戳,你可以使用这样的代码:
private const string SECRET = "secret of your choice";
private string getSHA1Hash(string strToHash)
{
System.Security.Cryptography.SHA1CryptoServiceProvider sha1Obj = new System.Security.Cryptography.SHA1CryptoServiceProvider();
byte[] bytesToHash = System.Text.Encoding.Default.GetBytes(strToHash);
bytesToHash = sha1Obj.ComputeHash(bytesToHash);
string strResult = "";
foreach (byte b in bytesToHash)
{
strResult += b.ToString("x2");
}
return strResult.ToLower();
}
public bool IsValidRequest(long expiryTicks, string hash)
{
var expiried = new DateTime(expiryTicks);
var toHash = expiryTicks + SECRET;
if (expiried < DateTime.Now)
return false;
if (hash.ToLower() == getSHA1Hash(toHash))
return true;
return false;
}
public string GetHashForExpiryTicks(long expiryTicks)
{
var toHash = expiryTicks + SECRET;
return getSHA1Hash(toHash);
}
Run Code Online (Sandbox Code Playgroud)
要生成链接,您可以像这样获取哈希参数
var hash = GetHashForExpiryTicks(DateTime.Now.AddHours(48).Ticks);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1913 次 |
| 最近记录: |