如何生成6位数的OTP号码

问题描述 投票:1回答:8

登录认证系统中的OTP号是多少?有没有使用java(android)生成OTP号码的特定算法。或者是OTP类似随机数?如何通过优化实现这一目标。

java android otp
8个回答
17
投票

请不要重新发明轮子 - 特别是在安全和加密的情况下。你可能最终处于一个非常糟糕的状态。

使用社区同意的算法,如Open Authentication Iniative指定的HOTP和TOTP算法。这些算法也由Google身份验证器使用并在这些RFC中指定。读它们。它们很简单。

http://tools.ietf.org/html/rfc4226

https://tools.ietf.org/html/rfc6238



2
投票

我也很难找到关于它的简单规则。

有很多关于OTP的内容解释如“时间同步”等...但是,我正在寻找一个简单的解决方案,但是,保持系统的安全性。

我是我的情况我保留了2FA(双因素身份验证),这已经提供了很多安全性。

有关随机生成器的JAVA的相关信息(请参阅:SecureRandom)如果您想要生成唯一的数字,请避免重复,这很重要。

例子:

https://www.securecoding.cert.org/confluence/display/java/MSC02-J.+Generate+strong+random+numbers

关于它的详细信息:http://resources.infosecinstitute.com/random-number-generation-java/

基于上面的示例,我实现了以下代码段:

public class SimpleOTPGenerator {


    protected SimpleOTPGenerator() {
    }

    public static String random(int size) {

        StringBuilder generatedToken = new StringBuilder();
        try {
            SecureRandom number = SecureRandom.getInstance("SHA1PRNG");
            // Generate 20 integers 0..20
            for (int i = 0; i < size; i++) {
                generatedToken.append(number.nextInt(9));
            }
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }

        return generatedToken.toString();
    }
}

2
投票
protected void onCreate(Bundle savedInstanceState)
 {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Random otp  =new Random();

        StringBuilder builder=new StringBuilder();
        for(int count=0; count<=10;count++) {
            builder.append(otp.nextInt(10));
        }
        Log.d("Number", " " + builder.toString());

        TextView txt = (TextView) findViewById(R.id.txt);

        txt.setText(builder.toString());
   }

0
投票
public static void main(String []args){
            java.util.Random r=new java.util.Random();
            int otp = r.nextInt(1000000); // no. of zeros depends on the OTP digit
            System.out.println(otp);
}

0
投票
First of all OTP stands for one time password it is used for the authentication and 
verification this is code is for java implemented in netbeans IDE
 You have to register on the msg91.com for the api genration and that gives free 250 
 msgs.
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Random;
import javax.swing.JOptionPane;
 public class SMS {
String num,otp;
SMS(String mob)
{
    num=mob;

}
 static String otpGenerator() 
{ 
    String numbers = "0123456789"; 
    String x="";
    Random rndm_method = new Random(); 
    char[] otp = new char[4]; 
    for (int i = 0; i <4; i++) 
    { 
        otp[i]=numbers.charAt(rndm_method.nextInt(numbers.length())); 
        x=x+otp[i];
    } 

    return x; 
}//this is the function for the random number generator for otp
 public void sms(String otp)
{
        try {

        String apiKey = "api key on msg91.com";
        String message = otp;
        String sender = "TESTIN";
        String numbers = num;
                    String a="http://api.msg91.com/api/sendhttp.php? 
          country=91&sender="+ sender +"&route=4&mobiles=" + numbers +"&authkey=api 
           key on msg91.com&message="+message+" ";
                    //System.out.println(a);
                    // Send data
        HttpURLConnection conn = (HttpURLConnection) new URL(a).openConnection();
        String data = apiKey + numbers + message + sender;
        conn.setDoOutput(true);
        conn.setRequestMethod("POST");
        conn.setRequestProperty("Content-Length", Integer.toString(data.length()));
        conn.getOutputStream().write(data.getBytes("UTF-8"));
        final BufferedReader rd = new BufferedReader(new 
         InputStreamReader(conn.getInputStream()));
        final StringBuffer stringBuffer = new StringBuffer();
        String line;
        while ((line = rd.readLine()) != null) {
            //stringBuffer.append(line);
                        //JOptionPane.showMessageDialog(null, "message"+line);
                        System.out.println("OTP SENT !");
        }
        rd.close();

        //return stringBuffer.toString();
    } catch (Exception e) {
                JOptionPane.showMessageDialog(null,e);

    }

}
//now you have to call this function and send your number as the parameter
 public Start() {
    this.setUndecorated(true);

    initComponents();

    jPasswordField1.setBackground(new Color(0, 0, 0, 0));

    jPasswordField1.setOpaque(false);  
    //jPasswordField1.setBorder(null); 
    this.setBounds(300, 200, 707, 390);
    SMS otp=new SMS("your number");
    x=otp.otpGenerator();
    otp.sms(x); 
    }

0
投票

最简单的方法是使用DecimalFormat和Random类。

String otp= new DecimalFormat("000000").format(new Random().nextInt(999999));
System.out.println(otp);

样本输出,

002428
445307
409185
989828
794486
213934

-1
投票
import java.util.*;

public class OTP2 {
  static char[] OTP(int len) {
    System.out.println("Generating OTP using random ()");
    System.out.print("Your OTP is:");

    // Using numeric values
    String numbers = "0123456789";

    // Using random method 
    Random rndm_method = new Random();
    char[] otp = new char[len];
    for(int i=0; i<len;i++) {
      // use of charAt() method : to get character value
      // use of nextInt() as it is scanning the value as int 
      otp[i] = numbers.charAt(rndm_method.nextInt(numbers.length()));
    }
    return otp;
  }

  public static void main(String args[]) {
    int length = 6;
    System.out.println(OTP(length));
  }
}

-3
投票
public class OTP 
{ 
public const int SECRET_LENGTH = 20; 
private const string 
MSG_SECRETLENGTH = "Secret must be at least 20 bytes", 
MSG_COUNTER_MINVALUE = "Counter min value is 1"; 

public OTP() 
{ 
} 

private static int[] dd = new int[10] { 0, 2, 4, 6, 8, 1, 3, 5, 7, 9 }; 

private byte[] secretKey = new byte[SECRET_LENGTH] 
{ 
0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 
0x3A, 0x3B, 0x3C, 0x3D, 0x3E, 0x3F, 0x40, 0x41, 0x42, 0x43 
}; 

private ulong counter = 0x0000000000000001; 

private static int checksum(int Code_Digits) 
{ 
int d1 = (Code_Digits/1000000) % 10; 
int d2 = (Code_Digits/100000) % 10; 
int d3 = (Code_Digits/10000) % 10; 
int d4 = (Code_Digits/1000) % 10; 
int d5 = (Code_Digits/100) % 10; 
int d6 = (Code_Digits/10) % 10; 
int d7 = Code_Digits % 10; 
return (10 - ((dd[d1]+d2+dd[d3]+d4+dd[d5]+d6+dd[d7]) % 10) ) % 10; 
} 

/// <summary> 
/// Formats the OTP. This is the OTP algorithm. 
/// </summary> 
/// <param name="hmac">HMAC value</param> 
/// <returns>8 digits OTP</returns> 
private 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 csum = checksum(Code_Digits); 
int OTP = Code_Digits * 10 + csum; 

return string.Format("{0:d08}", OTP); 
} 

public byte[] CounterArray 
{ 
get 
{ 
return BitConverter.GetBytes(counter); 
} 

set 
{ 
counter = BitConverter.ToUInt64(value, 0); 
} 
} 

/// <summary> 
/// Sets the OTP secret 
/// </summary> 
public byte[] Secret 
{ 
set 
{ 
if (value.Length < SECRET_LENGTH) 
{ 
throw new Exception(MSG_SECRETLENGTH); 
} 

secretKey = value; 
} 
} 

/// <summary> 
/// Gets the current OTP value 
/// </summary> 
/// <returns>8 digits OTP</returns> 
public string GetCurrentOTP() 
{ 
HmacSha1 hmacSha1 = new HmacSha1(); 

hmacSha1.Init(secretKey); 
hmacSha1.Update(CounterArray); 

byte[] hmac_result = hmacSha1.Final(); 

return FormatOTP(hmac_result); 
} 

/// <summary> 
/// Gets the next OTP value 
/// </summary> 
/// <returns>8 digits OTP</returns> 
public string GetNextOTP()  
{ 
// increment the counter 
++counter; 

return GetCurrentOTP(); 
} 

/// <summary> 
/// Gets/sets the counter value 
/// </summary> 
public ulong Counter 
{ 
get 
{ 
return counter; 
} 

set 
{ 
counter = value; 
} 
} 
}
© www.soinside.com 2019 - 2024. All rights reserved.