[英]How to pull specific data from a Base64String?
这与如何生成在24小时后失效的唯一令牌直接相关吗?
我正在尝试做的是嵌入以下内容:
到目前为止,我的代码是:
private string GenerateToken(Int32 pageNumber)
{
byte[] currentTimeStamp = BitConverter.GetBytes(DateTime.UtcNow.ToBinary());
byte[] key = Guid.NewGuid().ToByteArray();
byte[] newPageNumber = BitConverter.GetBytes(pageNumber);
string token = Convert.ToBase64String(newPageNumber.Concat(currentTimeStamp).Concat(key).ToArray());
return token;
}
private tokenClass TokenAuthenticates(string token)
{
byte[] data = Convert.FromBase64String(token);
tokenClass _token = new tokenClass()
{
PageNumber = 0,
TokenDateTimeStamp = DateTime.FromBinary(BitConverter.ToInt64(data, 1)),
TokenKey = new Guid(),
Validates = (DateTime.FromBinary(BitConverter.ToInt64(data, 1)) < DateTime.UtcNow.AddHours(-2))
};
return _token;
}
解码器中的page和Guid参数尚未确定,因此它们基本上是虚拟的。
我需要做些什么才能使这项工作?
像这样生成令牌:
private static string GenerateToken(Int32 pageNumber)
{
byte[] currentTimeStamp = BitConverter.GetBytes(DateTime.UtcNow.ToBinary());
var keyGuid = Guid.NewGuid();
byte[] key = keyGuid.ToByteArray();
byte[] newPageNumber = BitConverter.GetBytes(pageNumber);
// date plus page number plus key
string token = Convert.ToBase64String(currentTimeStamp.Concat(newPageNumber).Concat(key).ToArray());
return token;
}
像这样读取令牌(在TokenAuthenticates
方法中):
byte[] data = Convert.FromBase64String(token);
// It will take eight bytes starting at index 0
DateTime when = DateTime.FromBinary(BitConverter.ToInt64(data, 0));
// 8 first bytes was taken by date so lets skip 8 and then take 4 since page number is an integer and takes 4 bytes
int pageNumber = BitConverter.ToInt32(data.Skip(8).Take(4).ToArray(), 0);
// 8 bytes for date + 4 bytes for page number so we skip 12 and then take 16 for Guid
// Guid can be generated directly from the bytes
Guid key = new Guid(data.Skip(12).Take(16).ToArray());
这样您就不必对数字进行硬编码或确定大小。 使用sizeof
运算符可以为您确定:
int pageNumber = BitConverter.ToInt32(data.Skip(sizeof(long))
.Take(sizeof(int)).ToArray(), 0);
// Skip date and pageNumber, the rest is Guid
Guid key = new Guid(data.Skip(sizeof(long) + sizeof(int)).ToArray());
我将其称为AuthenticateToken
方法,因为它是一个动作动词,听起来更易读和清晰。 阅读令牌后,您可以执行进一步的验证。 您可能还需要考虑加密令牌。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.