[英]TOTP creating using bash and HMAC
我正在嘗試編寫一個bash代碼以生成6位TOTP。 我寫了以下代碼:
##!/bin/bash
T=`date '+%Y%m%d%H%M'`
K="secret"
prefix="(stdin)= "
keyhex=$(echo -n $T | openssl dgst -sha1 -hmac $K | sed -e "s/^$prefix//")
dec=$((echo $(( 16#$keyhex )) ))
key=$((echo $(($dec % 1000000))))
echo $key
有時它可以工作,有時我會遇到以下錯誤:
./auth.sh: line 6: echo 4076818289415231324 : syntax error in expression (error token is "4076818289415231324 ")
./auth.sh: line 7: % 1000000: syntax error: operand expected (error token is "% 1000000")
我究竟做錯了什么?
您嘗試在應該使用$(command substitution)
地方使用$((arithmetic expansion))
$(command substitution)
:
代替
dec=$((echo $(( 16#$keyhex )) ))
采用
dec=$(echo $(( 16#$keyhex )) )
甚至更好,只是
dec=$(( 16#$keyhex ))
這是您的腳本,其中包含以下這些調整:
#!/bin/bash
T=$(date '+%Y%m%d%H%M')
K="secret"
prefix="(stdin)= "
keyhex=$(printf '%s' "$K" | openssl dgst -sha1 -hmac $K | sed -e "s/^$prefix//")
dec=$(( 16#$keyhex ))
key=$((dec % 1000000))
echo "$key"
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.