我正在使用Google身份验证器进行两步验证。它在本地工作正常。生产代码不匹配。因为我的服务器和我的移动时区不匹配。如何将我的服务器时区同步到我的移动应用程序。我正在使用基于时间的代码。
调用函数IsValid(密码,密码)
我的代码
public static class TimeBasedOneTimePassword
{
public static readonly DateTime UNIX_EPOCH = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
private static MemoryCache _cache;
static TimeBasedOneTimePassword()
{
_cache = new MemoryCache("TimeBasedOneTimePassword");
}
public static string GetPassword(string secret)
{
return GetPassword(secret, GetCurrentCounter());
}
public static string GetPassword(string secret, DateTime epoch, int timeStep)
{
long counter = GetCurrentCounter(DateTime.UtcNow, epoch, timeStep);
return GetPassword(secret, counter);
}
public static string GetPassword(string secret, DateTime now, DateTime epoch, int timeStep, int digits)
{
long counter = GetCurrentCounter(now, epoch, timeStep);
return GetPassword(secret, counter, digits);
}
private static string GetPassword(string secret, long counter, int digits = 6)
{
return HashedOneTimePassword.GeneratePassword(secret, counter, digits);
}
private static long GetCurrentCounter()
{
return GetCurrentCounter(DateTime.UtcNow, UNIX_EPOCH, 30);
}
private static long GetCurrentCounter(DateTime now, DateTime epoch, int timeStep)
{
return (long)(now - epoch).TotalSeconds / timeStep;
}
public static bool IsValid(string secret, string password, int checkAdjacentIntervals = 1)
{
string cache_key = string.Format("{0}_{1}", secret, password);
if (_cache.Contains(cache_key))
{
throw new OneTimePasswordException("You cannot use the same secret/iterationNumber combination more than once.");
}
_cache.Add(cache_key, cache_key, new CacheItemPolicy { SlidingExpiration = TimeSpan.FromMinutes(2) });
string strpass = GetPassword(secret);
if (password ==strpass )
return true;
for (int i = 1; i <= checkAdjacentIntervals; i++)
{
if (password == GetPassword(secret, GetCurrentCounter() + i))
return true;
if (password == GetPassword(secret, GetCurrentCounter() - i))
return true;
}
return false;
}
}
谢谢,
SOMU