HMAC-based one time password in C# (RFC 4226 - HOTP)

前端 未结 3 1597
猫巷女王i
猫巷女王i 2021-02-01 10:59

I am attempting to wrap my brain around generating a 6 digit/character non case sensitive expiring one-time password.

My source is http://tools.ietf.org/html/rfc4226#sec

3条回答
  •  隐瞒了意图╮
    2021-02-01 11:37

    This snippet should do what you are asking for:

      public class UniqueId
    {
        public static string GetUniqueKey()
        {
            int maxSize = 6; // whatever length you want
            char[] chars = new char[62];
            string a;
            a = "ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890";
               char[] chars = new char[a.Length];
            chars = a.ToCharArray();
            int size = maxSize;
            byte[] data = new byte[1];
            RNGCryptoServiceProvider crypto = new RNGCryptoServiceProvider();
            crypto.GetNonZeroBytes(data);
            size = maxSize;
            data = new byte[size];
            crypto.GetNonZeroBytes(data);
            StringBuilder result = new StringBuilder(size);
            foreach (byte b in data)
            { result.Append(chars[b % (chars.Length - 1)]); }
            return result.ToString();
        }
    }
    

提交回复
热议问题