用C#写谷歌身份验证的时候,手机口令校验无法通过。私钥用的都是一样的。算法是
#region GenerateCode 生成验证码
public string GenerateCode(string accountSecretKey)
{
DateTime _epoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
TimeSpan ts = DateTime.UtcNow - _epoch;
long minutevalue = (long)(ts.TotalSeconds / 30);
byte[] key = Encoding.UTF8.GetBytes(accountSecretKey);
return GenerateHashedCode(key, minutevalue);
}
internal string GenerateHashedCode(byte[] key, long thisTime)
{
byte[] counter = BitConverter.GetBytes(thisTime);
if (BitConverter.IsLittleEndian)
{
Array.Reverse(counter);
}
HMACSHA1 hmac = new HMACSHA1(key, true);
//HMACSHA1 hmac = GetHMACSha1Algorithm(key);
byte[] hash = hmac.ComputeHash(counter);
int offset = hash[hash.Length - 1] & 0xf;
// 获取4个字节组成一个整数,其中第一个字节最高位为符号位,不获取,使用0x7f
// Convert the 4 bytes into an integer, ignoring the sign.
int binary =
((hash[offset] & 0x7f) << 24)
| (hash[offset + 1] << 16)
| (hash[offset + 2] << 8)
| (hash[offset + 3]);
int password = binary % (int)Math.Pow(10, 6);
return password.ToString(new string('0', 6));
}
#endregion