依赖
<!-- 谷歌验证码 -->
<dependency>
<groupId>com.warrenstrange</groupId>
<artifactId>googleauth</artifactId>
<version>1.2.0</version>
</dependency>
场景:
验证身份
一般是重要的网站或平台 需要在登录的时候强校验身份, 每个用户绑定一个 安全码,这个码 会根据时间变化生成不同的验证码,只有该用户掌握了对应的安全码,绑定在 google 身份验证器app 中,可以查询到,然后与后台算法生成的进行对比,验证身份
具体代码:
package com.util;
import com.warrenstrange.googleauth.GoogleAuthenticator;
import com.warrenstrange.googleauth.GoogleAuthenticatorKey;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
/**
* 增加google 动态验证码工具类
* 增加googleauth-1.1.2.jar
*
* account,会员账号, secret 安全码, issuer 服务名称,如印象笔记等, 除了安全码非空外,都可为空
* Google Authenticator 约定的二维码信息格式 : otpauth://totp/{account}?secret={secret}&issuer={issuer}
*/
public class GoogleAuth {
public static void main(String[] args) {
String key = getKeyStr();//P3IBV7BGUR3BKVCL //2TRXIQBK3SGJ5EQN
// String key = "P3IBV7BGUR3BKVCL";//16 位由Base32 的密码组成的服务码
int code = getVercode(key);
boolean isPattern = isPattern(key,code);
}
/**
* 防止生成重复安全码
* @param list 已生成的安全码
* @return
*/
public static String getRepetitionKeyStr(List<String> list) {
AtomicInteger integer = new AtomicInteger(0);
String code = "";
while (integer.get() < 1) {
code = getKeyStr();
if((null == list || list.size() == 0) || !list.contains(code)) {
integer.incrementAndGet();//原子自增
}
}
return code;
}
/**
* 获得为用户随机生成的安全码
* @return
*/
public static String getKeyStr() {
GoogleAuthenticator gAuth = new GoogleAuthenticator();
final GoogleAuthenticatorKey key = gAuth .createCredentials();
String keyStr = key.getKey();
// System.out.println(keyStr);
return keyStr;
}
/**
* 判断输入的验证码是否符合
* @param key 安全码
* @param password 验证码,根据时间来生成的验证码
* @return
*/
public static boolean isPattern(String key,int password) {
GoogleAuthenticator gAuth = new GoogleAuthenticator();
boolean isPattern = gAuth.authorize(key,password);
// System.out.println(isPattern);
return isPattern;
}
/**
* 获得TOTF算法生成的验证码,根据时间产生
* @param secretKey 安全码
* @return
*/
public static int getVercodeTime(String secretKey) {
GoogleAuthenticator gAuth = new GoogleAuthenticator();
int code = gAuth.getTotpPassword(secretKey);
// System.out.println(code);
return code;
}
}