Skip to main content

PHP - OTP驗證登入

安裝qrcode和oathtool

apt-get install qrencode oathtool -y

建立產生qrcode的bash檔

#!/bin/bash
secret=$(echo test123 | base32)
echo $secret
qrencode -t ANSI256 -o - $(echo otpauth://totp/CVG:wncvg?secret=${secret}&issuer=CVG&algorithm=SHA256&digits=6&period=30) -o qrcode.png -t png -s 5
test123 欲加密字串
CVG:wncvg  關聯標籤
issuer 發行人名稱
algorithm 演算法
digits OTP位數
period 時間更新

執行後會產生加密金鑰和qrcode

PHP設定OTP驗證

<?php
$otp = trim($_POST['otp']);
$otp_pswd = shell_exec('oathtool --totp=ANSI256 --base32 --digits=6 加密金鑰');
$stripped = preg_replace('/\D/', '', $otp_pswd);
$strippedotp = preg_replace('/\D/', '', $otp);
if(strcmp("$strippedotp", "$stripped") == 0){
 successfully
}else{
 fail
}
?>