9

什么是登录认证系统中的 OTP 号码?是否有使用 java (android) 生成 OTP 号码的特定算法。还是 OTP 类似于随机数?如何通过优化来实现这一点。

4

11 回答 11

23

请不要重新发明轮子——尤其是在安全和密码学的情况下。你最终可能会处于非常糟糕的状态。

使用社区同意的算法,如开放身份验证倡议指定的 HOTP 和 TOTP 算法。这些算法也被 google 身份验证器使用并在这些 RFC 中指定。阅读它们。它们很简单。

https://www.rfc-editor.org/rfc/rfc4226

https://www.rfc-editor.org/rfc/rfc6238

于 2015-09-08T22:40:20.063 回答
5

检查谷歌身份验证器。: https://github.com/google/google-authenticator它是具有 OTP 功能的开源项目

安卓应用程序源代码https://code.google.com/p/google-authenticator/source/browse/?repo=android

这是服务器端的源代码https://github.com/chregu/GoogleAuthenticator.php

维基百科文章http://en.wikipedia.org/wiki/Time-based_One-time_Password_Algorithm

于 2015-06-20T11:58:17.087 回答
5

最简单的方法是将 DecimalFormat 与 Random 类一起使用。

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

样本输出,

002428
445307
409185
989828
794486
213934
于 2019-08-21T05:21:36.187 回答
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());
   }
于 2017-02-28T11:33:37.730 回答
1

如其他答案所述,如何生成 TOTP (RFC 6238) 和 HOTP (RFC 4226) 代码的规则在 RFC 中定义。但是,如果您不想手动实现它们。你总是可以使用图书馆。

例如,我创建了一个用于创建一次性密码的库:OTP-Java

或者,如果您更喜欢自己实现代码,您还可以查看代码如何生成代码。

于 2021-03-07T16:58:54.610 回答
1

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

有很多关于 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();
    }
}
于 2015-09-08T20:05:26.230 回答
0

免责声明:不确定实施的安全性。如果您正在生成短暂的 OTP,这可能是一个可行的解决方案。

该方法可用于生成特定长度的随机数。

RandomStringUtils.randomNumeric(length)

参考: https ://commons.apache.org/proper/commons-lang/javadocs/api-3.9/org/apache/commons/lang3/RandomStringUtils.html#randomNumeric-int-

于 2021-08-17T18:32:42.370 回答
0

Java 8SplittableRandom在它的java.util包中引入。您可以使用它nextInt(int origin, int bound)来获取指定范围之间的随机数。

StringBuilder generatedOTP = new StringBuilder();
SplittableRandom splittableRandom = new SplittableRandom();

for (int i = 0; i < lengthOfOTP; i++) {

    int randomNumber = splittableRandom.nextInt(0, 9);
    generatedOTP.append(randomNumber);
}
return generatedOTP.toString();

但我会推荐使用SecureRandom类。它提供了一个加密的强随机数,并且在包中可用java.security

StringBuilder generatedOTP = new StringBuilder();
SecureRandom secureRandom = new SecureRandom();

try {

    secureRandom = SecureRandom.getInstance(secureRandom.getAlgorithm());

    for (int i = 0; i < lengthOfOTP; i++) {
        generatedOTP.append(secureRandom.nextInt(9));
    }
} catch (NoSuchAlgorithmException e) {
    e.printStackTrace();
}

return generatedOTP.toString();

您可以从Java 8-OTP Generator获得更多信息

于 2020-04-28T15:36:23.130 回答
-1
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); 
    }
于 2019-03-09T16:45:04.917 回答
-1
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);
}
于 2018-11-23T05:32:09.573 回答
-2
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));
  }
}
于 2017-10-21T16:10:42.563 回答