// // sharpmotp.cs // // Author: // Andreas Albang // // Copyright (c) 2014 Andreas Albang // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU Lesser General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public License // along with this program. If not, see . using System; using System.Security.Cryptography; using System.Text; namespace sharpmotp { public class SharpMotp { public static decimal timeWindowInSeconds = 600; //10 Minutes time to use the otp public static decimal timeStampEpoch = (decimal) Math.Round((DateTime.UtcNow.Subtract(new DateTime(1970, 1, 1))).TotalSeconds,0); //Unix timestamp public static string phpMd5Hash(string inputString) { using (MD5 md5 = MD5.Create()) { byte[] input = Encoding.UTF8.GetBytes(inputString); byte[] hash = md5.ComputeHash(input); return BitConverter.ToString(hash).Replace("-", ""); } } public static bool checkOTP(String otp, String otpPin, String otpInitSecret){ bool otpCorrect = false; String otpCheckValueMD5 = ""; for (decimal i = timeStampEpoch - timeWindowInSeconds; i <= timeStampEpoch + timeWindowInSeconds; i++) { otpCheckValueMD5 = (phpMd5Hash(((i.ToString()).Substring(0, (i.ToString()).Length - 1) + otpInitSecret + otpPin))).Substring(0,6); if (otp.ToLower() == otpCheckValueMD5.ToLower()) { otpCorrect = true; } } return otpCorrect; } } }