自己制作 github 2FA 的 Authenticator app
github 安全机制中引入了 Two-factor authentication,需要完成验证才能登陆。其中一种 2FA 方法就是使用 Authenticator app 扫码或者输入 two-factor secret 获取到验证码(一个 base32 的字符串)。我们可以自己写程序实现这个 Authenticator app。
使用 python3
安装 pyotp:
pip install pyotp
github 的 2FA 的 Authenticator app 的页面中有设置 key 的入口,点击即可获取到 github 给我们生成的 two-factor secret,然后再调用 pyotp 即可获取验证码:
import pyotp
import time
secret_key = '<换成自己的 two-factor secret>'
totp = pyotp.TOTP(secret_key)
verification_code = totp.now()
print(f"OTP: {verification_code}")
使用 java
也可以使用 java 调用三方库 java-otp 来实现,这样方便改成自己的 app。
- java-otp
- github: github.com/jchambers/j…
- maven 仓库: mvnrepository.com/artifact/co…
- 还需要使用 common-codec 对 base32 的密钥进行解码:
- github: github.com/apache/comm…
- maven 仓库: mvnrepository.com/artifact/co…
参考代码如下:
import com.eatthepath.otp.TimeBasedOneTimePasswordGenerator;
import org.apache.commons.codec.binary.Base32;
import javax.crypto.spec.SecretKeySpec;
import java.security.InvalidKeyException;
import java.security.Key;
import java.time.Instant;
public class Main {
public static void main(String[] args) throws InvalidKeyException {
// 提供的密钥,使用 Base32 编码
String base32EncodedKey = "<换成自己的 two-factor secret>";
Base32 base32 = new Base32();
byte[] secretDecoded = base32.decode(base32EncodedKey);
TimeBasedOneTimePasswordGenerator totp = new TimeBasedOneTimePasswordGenerator();
final Key key = new SecretKeySpec(secretDecoded, totp.getAlgorithm());
final Instant now = Instant.now();
String generatedOtp = totp.generateOneTimePasswordString(key, now);
System.out.println("OTP: " + generatedOtp);
}
}