二次认证
在互联网应用场合,对于重要数据保护啊,目前一种比较流行的方案是采用二次认证的手段。什么是二次认证?
二次认证通常指的是用户输入账号密码之外,需要额外输入一串一次性的随机数字,服务器依据于账号密码及随机数字来确认登录者的身份。其实银行在很早就使用类似的手段来进行访问控制,比如之前U盾及口令卡等产物,近几年随着手机app的流行,这个动态密码生成转移到手机App来进行生成,比如网易游戏出的将军令。与谷歌认证器类似,手机app不用联网,就生成了随机数字,服务器校验随机数字来保证客户数据安全。
原理
上文提到了手机app不用联网,为什么生成的随机数字,服务器就认识呢。这说明,客户端(手机app)与服务器肯定使用了相同或者配套的算法。寿险客户端和服务器事先协商好秘钥K,然后客户端对秘钥K进行Hash运算,可以得到一个随机数字。服务器接收到随机数字然后进行反向运算得到秘钥K,据此来确认客户身份。
这个算法的关键其实是秘钥K的算法,如何在保证随机的同时,还能让服务器认识并反向运算回来。
其实公开的算法其实就是两个:
- HOTP:(An HMAC-Based One-Time Password Algorithm)https://tools.ietf.org/html/rfc4226
- TOTP: (Time-Based One-Time Password Algorithm) https://tools.ietf.org/html/rfc6238
其实原理差不多,是基于时间维度来进行运算的(也就是客户端的时钟和服务器的时钟务必保质一致),TOTP可以视为HOTP的改良版本。
实践
第一步 :下载客户端
IOS版本:https://itunes.apple.com/cn/app/google-authenticator-aka-a.m.x./id388497605?mt=8
安卓版本:https://shouji.baidu.com/software/22417419.html
使用手册:https://www.jianshu.com/p/f03641c255e3>
第二步:服务器端编码集成
谷歌认证器其实有各种版本的代码,github上去找,下面只展示一个java版本
import org.apache.commons.codec.binary.Base32;
import org.apache.commons.codec.binary.Base64;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
/**
* 谷歌验证器
*/
public class GoogleAuthenticator {
// taken from Google pam docs - we probably don't need to mess with these
public static final int SECRET_SIZE = 10;
public static final String SEED = "4124HJHGFDDAADKLADGAALDAADKAD";
public static final String RANDOM_NUMBER_ALGORITHM = "SHA1PRNG";
int window_size = 3; // default 3 - max 17 (from google docs)最多可偏移的时间
/**
* 设置最多可偏移的时间
*/
public void setWindowSize(int s) {
if (s >= 1 && s <= 17)
window_size = s;
}
/**
* 默认生成一个秘钥,此方法其实跟TOTP算法没有直接关系,主要作用就是生成一个秘钥用
*/
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;
}
/**
* 获取二维码的URL,可以供谷歌验证器App直接扫码,如果不扫,也可以手动输入秘钥
* user:用户标志,主要是谷歌验证器的标识用,不参与计算
* host:hots标志,主要是谷歌验证器的标识用,不参与计算
* secret: 秘钥,参与计算,务必保密
*/
public static String getQRBarcodeURL(String user, String host, String secret) {
String format = "https://www.google.com/chart?chs=200x200&chld=M%%7C0&cht=qr&chl=otpauth://totp/%s@%s%%3Fsecret%%3D%s";
return String.format(format, user, host, secret);
}
/**
* 检查随机码的正确性
* secret: 秘钥
* code :随机码
*/
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;
}
}
参考
https://www.infoq.cn/article/2014/09/system-verification
https://awtqty-zhang.iteye.com/blog/1986275