当前位置: 移动技术网 > IT编程>开发语言>Java > java使用google身份验证器实现动态口令验证的示例

java使用google身份验证器实现动态口令验证的示例

2019年07月19日  | 移动技术网IT编程  | 我要评论

最近有用户反应我们现有的短信+邮件验证,不安全及短信条数限制和邮件收验证码比较慢的问题,希望我们也能做一个类似银行动态口令的验证方式。经过对可行性的分析及慎重考虑,可以实现一个这样的功能。

怎么实现呢,是自己开发一个这样的app?这样成本太高了,为了节约成本,我们使用互联网使用比较多的google身份验证器。使用它,我们只需要开发服务端就可以了。

google身份验证器的原理是什么呢?客户端和服务器事先协商好一个密钥k,用于一次性密码的生成过程,此密钥不被任何第三方所知道。此外,客户端和服务器各有一个计数器c,并且事先将计数值同步。进行验证时,客户端对密钥和计数器的组合(k,c)使用hmac(hash-based message authentication code)算法计算一次性密码,公式如下:

hotp(k,c) = truncate(hmac-sha-1(k,c)) 

上面采用了hmac-sha-1,当然也可以使用hmac-md5等。hmac算法得出的值位数比较多,不方便用户输入,因
此需要截断(truncate)成为一组不太长十进制数(例如6位)。计算完成之后客户端计数器c计数值加1。用户将这一组十
进制数输入并且提交之后,服务器端同样的计算,并且与用户提交的数值比较,如果相同,则验证通过,服务器端将计数值
c增加1。如果不相同,则验证失败。

package com.auth.google; 
 
import java.security.invalidkeyexception; 
import java.security.nosuchalgorithmexception; 
import java.security.securerandom; 
import javax.crypto.mac; 
import javax.crypto.spec.secretkeyspec; 
import org.apache.commons.codec.binary.base32; 
import org.apache.commons.codec.binary.base64; 
 
/** 
 * 
 * 
 * google身份验证器,java服务端实现 
 * 
 * @author yangbo 
 * 
 * @version 创建时间:2017年8月14日 上午10:10:02 
 * 
 * 
 */ 
public class googleauthenticator { 
 
 // 生成的key长度( generate secret key length) 
 public static final int secret_size = 10; 
 
 public static final string seed = "g8gjevtbw5ovsv7avl47357438reyhreyuryetredldvks2m0qn7vxrs2im5mdancwgmcd2rvczx"; 
 // java实现随机数算法 
 public static final string random_number_algorithm = "sha1prng"; 
 // 最多可偏移的时间 
 int window_size = 3; // default 3 - max 17 
 
 /** 
 * set the windows size. this is an integer value representing the number of 
 * 30 second windows we allow the bigger the window, the more tolerant of 
 * clock skew we are. 
 * 
 * @param s 
 *  window size - must be >=1 and <=17. other values are ignored 
 */ 
 public void setwindowsize(int s) { 
 if (s >= 1 && s <= 17) 
  window_size = s; 
 } 
 
 /** 
 * generate a random secret key. this must be saved by the server and 
 * associated with the users account to verify the code displayed by google 
 * authenticator. the user must register this secret on their device. 
 * 生成一个随机秘钥 
 * 
 * @return secret key 
 */ 
 public static string generatesecretkey() { 
 securerandom sr = null; 
 try { 
  sr = securerandom.getinstance(random_number_algorithm); 
  sr.setseed(base64.decodebase64(seed)); 
  byte[] buffer = sr.generateseed(secret_size); 
  base32 codec = new base32(); 
  byte[] bencodedkey = codec.encode(buffer); 
  string encodedkey = new string(bencodedkey); 
  return encodedkey; 
 } catch (nosuchalgorithmexception e) { 
  // should never occur... configuration error 
 } 
 return null; 
 } 
 
 /** 
 * return a url that generates and displays a qr barcode. the user scans 
 * this bar code with the google authenticator application on their 
 * smartphone to register the auth code. they can also manually enter the 
 * secret if desired 
 * 
 * @param user 
 *  user id (e.g. fflinstone) 
 * @param host 
 *  host or system that the code is for (e.g. myapp.com) 
 * @param secret 
 *  the secret that was previously generated for this user 
 * @return the url for the qr code to scan 
 */ 
 public static string getqrbarcodeurl(string user, string host, string secret) { 
 string format = "http://www.google.com/chart?chs=200x200&chld=m%%7c0&cht=qr&chl=otpauth://totp/%s@%s?secret=%s"; 
 return string.format(format, user, host, secret); 
 } 
 
 /** 
 * 生成一个google身份验证器,识别的字符串,只需要把该方法返回值生成二维码扫描就可以了。 
 * 
 * @param user 
 *  账号 
 * @param secret 
 *  密钥 
 * @return 
 */ 
 public static string getqrbarcode(string user, string secret) { 
 string format = "otpauth://totp/%s?secret=%s"; 
 return string.format(format, user, secret); 
 } 
 
 /** 
 * check the code entered by the user to see if it is valid 验证code是否合法 
 * 
 * @param secret 
 *  the users secret. 
 * @param code 
 *  the code displayed on the users device 
 * @param t 
 *  the time in msec (system.currenttimemillis() for example) 
 * @return 
 */ 
 public boolean check_code(string secret, long code, long timemsec) { 
 base32 codec = new base32(); 
 byte[] decodedkey = codec.decode(secret); 
 // convert unix msec time into a 30 second "window" 
 // this is per the totp spec (see the rfc for details) 
 long t = (timemsec / 1000l) / 30l; 
 // window is used to check codes generated in the near past. 
 // you can use this value to tune how far you're willing to go. 
 for (int i = -window_size; i <= window_size; ++i) { 
  long hash; 
  try { 
  hash = verify_code(decodedkey, t + i); 
  } catch (exception e) { 
  // yes, this is bad form - but 
  // the exceptions thrown would be rare and a static 
  // configuration problem 
  e.printstacktrace(); 
  throw new runtimeexception(e.getmessage()); 
  // return false; 
  } 
  if (hash == code) { 
  return true; 
  } 
 } 
 // the validation code is invalid. 
 return false; 
 } 
 
 private static int verify_code(byte[] key, long t) throws nosuchalgorithmexception, invalidkeyexception { 
 byte[] data = new byte[8]; 
 long value = t; 
 for (int i = 8; i-- > 0; value >>>= 8) { 
  data[i] = (byte) value; 
 } 
 secretkeyspec signkey = new secretkeyspec(key, "hmacsha1"); 
 mac mac = mac.getinstance("hmacsha1"); 
 mac.init(signkey); 
 byte[] hash = mac.dofinal(data); 
 int offset = hash[20 - 1] & 0xf; 
 // we're using a long because java hasn't got unsigned int. 
 long truncatedhash = 0; 
 for (int i = 0; i < 4; ++i) { 
  truncatedhash <<= 8; 
  // we are dealing with signed bytes: 
  // we just keep the first byte. 
  truncatedhash |= (hash[offset + i] & 0xff); 
 } 
 truncatedhash &= 0x7fffffff; 
 truncatedhash %= 1000000; 
 return (int) truncatedhash; 
 } 
} 

测试代码:

package com.auth.google; 
 
import org.junit.test; 
 
/** 
 * 
 * 
 * 身份认证测试 
 * 
 * @author yangbo 
 * 
 * @version 创建时间:2017年8月14日 上午11:09:23 
 * 
 * 
 */ 
public class authtest { 
 //当测试authtest时候,把gensecrettest生成的secret值赋值给它 
 private static string secret="r2q3s52rnxbtftom"; 
 
 //@test 
 public void gensecrettest() {// 生成密钥 
  secret = googleauthenticator.generatesecretkey(); 
 // 把这个qrcode生成二维码,用google身份验证器扫描二维码就能添加成功 
 string qrcode = googleauthenticator.getqrbarcode("2816661736@qq.com", secret); 
 system.out.println("qrcode:" + qrcode + ",key:" + secret); 
 } 
 /** 
 * 对app的随机生成的code,输入并验证 
 */ 
 @test 
 public void verifytest() { 
 long code = 807337; 
 long t = system.currenttimemillis(); 
 googleauthenticator ga = new googleauthenticator(); 
 ga.setwindowsize(5); 
 boolean r = ga.check_code(secret, code, t); 
 system.out.println("检查code是否正确?" + r); 
 } 
} 

具体使用方式(ios演示):

第一步:进入iphone的appstore,在搜索框中输入google身份验证器,如下图:

选择上图中的google authenticator 并安装。

第二步:运行下面链接中下载的demo中的authtest的gensecrettest方法,控制台打印的结果如下图:

key:为app与服务端约定的秘钥,用于双方的认证。

qrcode:是app扫码能够识别的就是二维码值,把它生成二维码如下图:

第三步:打开google authenticator app软件选择扫描条形码按扭打开相机对二维码扫描加入账号,如下图:

第四步:把app中的数字,在authtest的verifytest进行验证,如下图:

通过上面给大家分享了google身份认证器服务端key的生成和它生成的随机密码的验证。

上面使用的代码已上传到码云,下载地址:

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持移动技术网。

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网