如何生成6位数的OTP号码

时间:2015-06-20 11:52:14

标签: java android otp

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

11 个答案:

答案 0 :(得分:13)

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

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

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

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

答案 1 :(得分:3)

答案 2 :(得分:2)

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

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

我是我的情况我保留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();
    }
}

答案 3 :(得分: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());
   }

答案 4 :(得分: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);
}

答案 5 :(得分: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); 
    }

答案 6 :(得分:0)

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

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

样本输出

002428
445307
409185
989828
794486
213934

答案 7 :(得分:0)

Java 8在SplittableRandom软件包中引入了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获得更多信息

答案 8 :(得分:0)

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

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

或者,如果您更喜欢自己实现代码,也可以查看代码的生成方式。

答案 9 :(得分:-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));
  }
}

答案 10 :(得分:-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; 
} 
} 
}