Click here to Skip to main content
15,887,683 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Need a sample code to create OTP - random number using System.Security.Cryptography.
Posted

Google has a lot of answers for you. But first of all you have to decide the hash you want to use, the password length, compexity, if you need to comply with a standard, and so on. But this is a good start:

C#
public static int CalculateHotp(byte[] key, byte[] counter)
{
    var hmacsha1 = new HMACSHA1(key);
    byte[] hmac_result = hmacsha1.ComputeHash(counter);
    int offset = hmac_result[19] & 0x0f;
    int bin_code = (hmac_result[offset]  & 0x7f) << 24
                   | (hmac_result[offset+1] & 0xff) << 16
                   | (hmac_result[offset+2] & 0xff) <<  8
                   | (hmac_result[offset+3] & 0xff);
    int hotp = bin_code % 1000000;
    return hotp;
}

(copied from here[^])

Update:
C#
using System;
using System.Security.Cryptography;
using System.Text;

namespace OTATest
{
    static class OTAGenerator
    {
        private static char[] pwdCharArray = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789`~!@#$%^&*()-_=+[]{}\\|;:'\",<.>/?".ToCharArray();

        public static string GenerateOTA(int keyLength = 10)
        {
            using (RNGCryptoServiceProvider rngCsp = new RNGCryptoServiceProvider())
            {
                StringBuilder sBuilder = new StringBuilder();
                byte[] key = new byte[1];

                for (int i = 0; i < keyLength; i++)
                {
                    do
                    {
                        rngCsp.GetNonZeroBytes(key);
                    }
                    while (key[0] > pwdCharArray.Length);
                    sBuilder.Append(pwdCharArray[key[0]]);
                }

                return sBuilder.ToString();
            }
        }
    }
}
 
Share this answer
 
v2
Comments
R.SIVAA 25-Jun-12 6:39am    
Thanks Zoltan. The above code is good to generate the encryption for a given word. But I really need to generate random numbers, not based on any input. I wanto use these random numbers for OTP(One Time Password). To be particular, want to use this "System.Security.Cryptography.RandomNumberGenerator".
Zoltán Zörgő 25-Jun-12 8:16am    
See my update
C#
public decimal Rand()
    {
        byte[] Salt = new byte[8];
        System.Security.Cryptography.RandomNumberGenerator.Create().GetBytes(Salt);
        decimal result = 0;
        foreach (byte b in Salt)
        {      result = result * 255 + b;  }
        while (result > 100)
        {      result /= 10;
        }
        return result;
    }



Hope this works...
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900