如何从Base64String中提取特定数据?

时间:2016-12-21 04:32:59

标签: c#

这与how to generate a unique token which expires after 24 hours?

直接相关

我试图做的是嵌入以下内容:

  1. 页码(0到6)
  2. UTC格式的当前日期/时间戳
  3. 和唯一GUID
  4. 到目前为止我的代码是:

    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;
    }
    

    解码器中的页面和Guid参数还没有找到,所以它们基本上都是假的。

    我需要做些什么来完成这项工作?

1 个答案:

答案 0 :(得分:3)

像这样生成你的令牌:

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,因为它是一个动词动词,听起来更清晰可读。您可以在阅读令牌后执行进一步的验证。您也可以考虑加密令牌。