Created
January 24, 2014 11:36
-
-
Save llCorvinSll/8595813 to your computer and use it in GitHub Desktop.
TOTP: Time-Based One-Time Password Algorithm
http://tools.ietf.org/html/rfc6238#
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public static string GeneratePassword(string secret, long iterationNumber, int digits = 6) | |
{ | |
byte[] counter = BitConverter.GetBytes(iterationNumber); | |
if (BitConverter.IsLittleEndian) | |
Array.Reverse(counter); | |
byte[] key = Encoding.ASCII.GetBytes(secret); | |
HMACSHA1 hmac = new HMACSHA1(key, true); | |
byte[] hash = hmac.ComputeHash(counter); | |
int offset = hash[hash.Length - 1] & 0xf; | |
int binary = | |
((hash[offset] & 0x7f) << 24) | |
| ((hash[offset + 1] & 0xff) << 16) | |
| ((hash[offset + 2] & 0xff) << 8) | |
| (hash[offset + 3] & 0xff); | |
int password = binary % (int)Math.Pow(10, digits); // 6 digits | |
return password.ToString(new string('0', digits)); | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Security.Cryptography; | |
using System.Text; | |
public class Program | |
{ | |
public static string FormatOTP(byte[] hmac) | |
{ | |
int offset = hmac[19] & 0xf ; | |
int bin_code = (hmac[offset] & 0x7f) << 24 | |
| (hmac[offset+1] & 0xff) << 16 | |
| (hmac[offset+2] & 0xff) << 8 | |
| (hmac[offset+3] & 0xff) ; | |
int Code_Digits = bin_code % 10000000; | |
int OTP = Code_Digits * 10; | |
return string.Format("{0:d08}", OTP); | |
} | |
public static void Main() | |
{ | |
int TTL = 10; | |
Console.WriteLine("Hello World"); | |
//Get current unix time | |
TimeSpan CurrTime = (DateTime.UtcNow - new DateTime(1990, 1, 1)); | |
var sha1 = SHA1.Create(); | |
string secret = "aasaadsdasd"; //totaly rndom | |
string mail = "mymail@mail.com"; | |
int counter = ((int)CurrTime.TotalSeconds) / TTL; | |
string rawSeq = counter.ToString() + secret + mail; | |
Console.WriteLine(" == RAW data to generate == "); | |
Console.WriteLine(rawSeq); | |
byte[] hashBytes = sha1.ComputeHash(Encoding.UTF8.GetBytes(rawSeq)); | |
string rawHash = BitConverter.ToString(hashBytes); | |
Console.WriteLine(" == RAW hash == "); | |
Console.WriteLine(rawHash); | |
Console.WriteLine(FormatOTP(hashBytes)); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment