【发布时间】:2018-03-24 03:36:52
【问题描述】:
我已经开发了以下程序来生成 OTP(一次性密码),现在请告知我是否可以在 OTP 上下文中使用其他更好和安全的方法
// Java code to explain how to generate OTP
// Here we are using random() method of util
// class in Java
import java.util.*;
public class NewClass
{
static char[] OTP(int len)
{
System.out.println("Generating OTP using random() : ");
System.out.print("You 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 = 4;
System.out.println(OTP(length));
}
}
【问题讨论】:
-
OTP 只是一个很短的真正随机数。用于验证新设备或路径。所以我建议你简单地使用 Random 类的 nextLong 方法,生成一个长整数而不是循环并为每个字符生成一个随机数。
-
@SamwellTarly 感谢请求您显示一个代码,以便我能掌握更多,前提是我必须生成 4 位数的 OTP
-
这个问题更适合代码审查stackoverflow。