我想在asp.net c#中生成alfa数字otp

本文关键字:alfa 数字 otp asp net | 更新日期: 2023-09-27 18:04:37

public void generate()
{
    string alphabets = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
    string small_alphabets = "abcdefghijklmnopqrstuvwxyz";
    string numbers = "1234567890";
    string characters = numbers;
    characters += alphabets + small_alphabets + numbers;
    int length =6;
    string opt = string.Empty;
    for (int i = 0; i < length; i++)
    {
        string character = string.Empty;
        do
        {
            int index = new Random().Next(0, characters.Length);
            character = characters.ToCharArray()[index].ToString();
        } while (otp.IndexOf(character) != -1);
        otp += character;
    }
    string str= otp;
}

这是我的代码,这是不为我工作。我想尝试小写字母,大写字母和0到9的数字组合。

我想在asp.net c#中生成alfa数字otp

代码如下:

var chars1 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890";
var stringChars1 = new char[6];
var random1 = new Random();
for (int i = 0; i < stringChars1.Length; i++)
{
    stringChars1[i] = chars1[random1.Next(chars1.Length)];
}
var str= new String(stringChars1);

此代码将为您提供n位数字的数字otp。

public static int GenerateOTP(int digits)
    {
        if (digits < 3)
            return new Random().Next(10, 99);
        else
            return new Random().Next(MultiplyNTimes(digits), MultiplyNTimes(digits + 1) - 1);
    }
private static int MultiplyNTimes(int n)
    {
        if (n == 1)
            return 1;
        else
            return 10 * MultiplyNTimes(n - 1);
    }