Java 如何生成 6 位 OTP 号码
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/30953662/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to generate OTP Number with 6 digits
提问by Android Developer
What is an OTP number in a login authentication system? Is there any specific algorithm for generating OTP numbers using java (android). Or is an OTP something like random number? How can this be achieved, with optimization.
什么是登录认证系统中的 OTP 号码?是否有使用 java (android) 生成 OTP 号码的特定算法。还是 OTP 类似于随机数?如何通过优化实现这一点。
回答by Rajan Bhavsar
Check google authenticator. : https://github.com/google/google-authenticatorit is open source project with OTP functionality
检查谷歌身份验证器。:https: //github.com/google/google-authenticator它是具有 OTP 功能的开源项目
Source code for android app https://code.google.com/p/google-authenticator/source/browse/?repo=android
Android 应用程序的源代码https://code.google.com/p/google-authenticator/source/browse/?repo=android
Here is source code for server side https://github.com/chregu/GoogleAuthenticator.php
这是服务器端的源代码https://github.com/chregu/GoogleAuthenticator.php
Wikipedia article http://en.wikipedia.org/wiki/Time-based_One-time_Password_Algorithm
维基百科文章http://en.wikipedia.org/wiki/Time-based_One-time_Password_Algorithm
回答by Eduardo Fabricio
I have the same difficulty to find simple rule about it.
我也很难找到关于它的简单规则。
There are a lot of content explaining about OTP like "Time Synchronized" etc..., however I was looking for a simple solution while keeping the system's security.
有很多内容解释了关于 OTP 的内容,例如“时间同步”等......,但是我一直在寻找一个简单的解决方案,同时保持系统的安全性。
In my case I keep the 2FA (Two Factor Authentication), that already gives a lot of security.
就我而言,我保留了 2FA(双因素身份验证),这已经提供了很多安全性。
A relevant info about JAVA for random generator (see: SecureRandom) Important if you want a unique number generation, avoiding repeats.
有关随机生成器的 JAVA 的相关信息(请参阅:SecureRandom)如果您想要唯一的数字生成,避免重复,则很重要。
Examples:
例子:
https://www.securecoding.cert.org/confluence/display/java/MSC02-J.+Generate+strong+random+numbers
https://www.securecoding.cert.org/confluence/display/java/MSC02-J.+Generate+strong+random+numbers
Details about it: http://resources.infosecinstitute.com/random-number-generation-java/
关于它的详细信息:http: //resources.infosecinstitute.com/random-number-generation-java/
Based on examples above I implemented the following snippet:
基于上面的示例,我实现了以下代码段:
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();
}
}
回答by cornelinux
Please do not reinvent the wheel - especially in case of security and cryptography. You might end up in a really bad state.
请不要重新发明轮子 - 特别是在安全和密码学的情况下。你可能最终处于非常糟糕的状态。
Use algorithms, that the community agreed upon like the HOTP and TOTP algorithm specified by the Open Authentication Iniative. These algorithms are also used by the google authenticater and specified in these RFCs. Read them. They are simple.
使用社区同意的算法,如开放身份验证倡议指定的 HOTP 和 TOTP 算法。这些算法也被谷歌身份验证器使用并在这些 RFC 中指定。阅读它们。他们很简单。
http://tools.ietf.org/html/rfc4226
http://tools.ietf.org/html/rfc4226
回答by Aditya Vats
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());
}
回答by RAHUL KUMAR SINGHA
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));
}
}
回答by Zoha Irshad
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);
}
回答by Shivam Rajput
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);
}
回答by REMITH
Easiest way is to just use DecimalFormat with Random class.
最简单的方法是将 DecimalFormat 与 Random 类一起使用。
String otp= new DecimalFormat("000000").format(new Random().nextInt(999999));
System.out.println(otp);
Sample Outputs,
样本输出,
002428
445307
409185
989828
794486
213934
回答by Atul Rai
Java 8 introduced SplittableRandom
in it's java.util
package. You can use it's nextInt(int origin, int bound)
to get a random number between the specified bound.
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();
But I will recommend to use SecureRandom
class. It provides a cryptographicallystrong random number and available in the package java.security
.
但我会建议使用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();
You may get more info from Java 8- OTP Generator
您可以从Java 8- OTP Generator获得更多信息