本文主要讲述一下如何使用aerogear-otp生成otp,以及相关源码分析html
全称是one time password,一般用来支持双因素认证。主要能够分两类java
在RFC 4226规范中android
在RFC 6238规范中git
这里主要讲TOTP
其常见的手机客户端有Google Authenticator APP以及阿里云的身份宝。因为google的软件在国内被墙,所以可使用阿里云的身份宝github
服务端的话,google官方有c的代码,java的话不少第三方都有实现,这里选择jboss提供的aerogear-otp-java,其maven以下api
<dependency> <groupId>org.jboss.aerogear</groupId> <artifactId>aerogear-otp-java</artifactId> <version>1.0.0</version> </dependency>
主要的步骤以下:服务器
绑定secret以后,就可使用one time password进行验证了。app
String secret = Base32.random(); Totp totp = new Totp(secret); String uri = totp.uri(account);
将这个uri做为二维码的信息,便可。
/** * Prover - To be used only on the client side * Retrieves the encoded URI to generated the QRCode required by Google Authenticator * * @param name Account name * @return Encoded URI */ public String uri(String name) { try { return String.format("otpauth://totp/%s?secret=%s", URLEncoder.encode(name, "UTF-8"), secret); } catch (UnsupportedEncodingException e) { throw new IllegalArgumentException(e.getMessage(), e); } }
它的格式otpauth://totp/%s?secret=%s,Google Authenticator APP或阿里云的身份宝均支持这种格式的识别。
boolean isValid = totp.verify(code);
其源码以下dom
/** * Verifier - To be used only on the server side * <p/> * Taken from Google Authenticator with small modifications from * {@see <a href="http://code.google.com/p/google-authenticator/source/browse/src/com/google/android/apps/authenticator/PasscodeGenerator.java?repo=android#212">PasscodeGenerator.java</a>} * <p/> * Verify a timeout code. The timeout code will be valid for a time * determined by the interval period and the number of adjacent intervals * checked. * * @param otp Timeout code * @return True if the timeout code is valid * <p/> * Author: sweis@google.com (Steve Weis) */ public boolean verify(String otp) { long code = Long.parseLong(otp); long currentInterval = clock.getCurrentInterval(); int pastResponse = Math.max(DELAY_WINDOW, 0); for (int i = pastResponse; i >= 0; --i) { int candidate = generate(this.secret, currentInterval - i); if (candidate == code) { return true; } } return false; }
这里有个DELAY_WINDOW参数,是为了防止手机客户端与服务器端的时差引入的。默认值是1,即容许那个code在手机端过时30秒以内到服务端验证还有效。
aerogear-otp-java-1.0.0-sources.jar!/org/jboss/aerogear/security/otp/api/Clock.javamaven
public class Clock { private final int interval; private Calendar calendar; public Clock() { interval = 30; } public Clock(int interval) { this.interval = interval; } public long getCurrentInterval() { calendar = GregorianCalendar.getInstance(TimeZone.getTimeZone("UTC")); long currentTimeSeconds = calendar.getTimeInMillis() / 1000; return currentTimeSeconds / interval; } }
这个interval默认是30,固然你也能够改成1分钟那就是60.
另外这里先把毫秒转为秒,而后再除去interval,因为是使用/,所以是直接取整数部分,于是上面的DELAY_WINDOW的值=N,其实至关于容许过去的N个interval的code还能校验成功
aerogear-otp-java-1.0.0-sources.jar!/org/jboss/aerogear/security/otp/Totp.java
private int generate(String secret, long interval) { return hash(secret, interval); } private int hash(String secret, long interval) { byte[] hash = new byte[0]; try { //Base32 encoding is just a requirement for google authenticator. We can remove it on the next releases. hash = new Hmac(Hash.SHA1, Base32.decode(secret), interval).digest(); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } catch (InvalidKeyException e) { e.printStackTrace(); } catch (Base32.DecodingException e) { e.printStackTrace(); } return bytesToInt(hash); } private int bytesToInt(byte[] hash) { // put selected bytes into result int int offset = hash[hash.length - 1] & 0xf; int binary = ((hash[offset] & 0x7f) << 24) | ((hash[offset + 1] & 0xff) << 16) | ((hash[offset + 2] & 0xff) << 8) | (hash[offset + 3] & 0xff); return binary % Digits.SIX.getValue(); } /** * Retrieves the current OTP * * @return OTP */ public String now() { return leftPadding(hash(secret, clock.getCurrentInterval())); } private String leftPadding(int otp) { return String.format("%06d", otp); }
默认值为30,在Clock里头能够经过构造器修改interval。不过因为Google Authenticator APP或阿里云的身份宝均为30秒更换一次,所以这个参数能够按默认的来。
aerogear-otp-java自己不提供DELAY_WINDOW的修改,不过你能够继承Totp,本身扩展一下。