依赖
<!-- 谷歌验证 -->
<dependency>
<groupId>com.warrenstrange</groupId>
<artifactId>googleauth</artifactId>
<version>1.1.2</version>
</dependency>
配置谷歌认证器使用验证码
package com.diasit.base.Google;
import com.warrenstrange.googleauth.GoogleAuthenticator;
import com.warrenstrange.googleauth.GoogleAuthenticatorKey;
public class GoogleCode {
/**
* 谷歌密钥生成器
* @return
*/
public static String generate() {
// 用户注册时使用
// 获取一个新的密钥,默认16位,该密钥与商户绑定
GoogleAuthenticator gAuth = new GoogleAuthenticator();
final GoogleAuthenticatorKey key = gAuth.createCredentials();
String key1 = key.getKey();
return key1;
}
/**
* 判断谷歌验证码
* @param key 密钥
* @param validation 验证码
* @return
*/
public static boolean isCodeValid(String key,int validation) {
// 根据用户密钥和用户输入的密码,验证是否一致。(近3个密码都有效:前一个,当前,下一个)
GoogleAuthenticator gAuth = new GoogleAuthenticator();
boolean isCodeValid = gAuth.authorize(key,validation);
return isCodeValid;
}
/**
* 测试
* @param args
*/
public static void main(String[] args) {
// 根据密钥,获取最新密码(后台用不到,用来开发 谷歌身份验证器 客户端)
GoogleAuthenticator gAuth = new GoogleAuthenticator();
//生成密钥
final GoogleAuthenticatorKey key = gAuth.createCredentials();
System.out.println(key.getKey());
//测试 获取验证码
int code = gAuth.getTotpPassword("QCNK3HKB77L65IVX");
System.out.println(code);
boolean isCodeValid = gAuth.authorize("QCNK3HKB77L65IVX",123456);
System.out.println(isCodeValid);
}
}