TOTP számítása bash-ben

Fórumok

Sziasztok!

Alábbi PHP kódot sikeresen használom egy ideje:

function getOtp($key) {

    $alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567";
    /* Base32 decoder */
    // Remove spaces from the given public key and converting to an array
    $key = str_split(str_replace(" ","",$key));

    $n = 0;
    $j = 0;
    $binary_key = "";
    // Decode public key's each character to base32 and save into binary chunks
    foreach($key as $char) {
        $n = $n << 5;
        $n = $n + stripos($alphabet, $char);
        $j += 5;

        if($j >= 8) {
            $j -= 8;
            $binary_key .= chr(($n & (0xFF << $j)) >> $j);
        }
    }
    /* End of Base32 decoder */
    // current unix time 30sec period as binary
    $binary_timestamp = pack('N*', 0) . pack('N*', floor(microtime(true)/30));
    // generate keyed hash
    $hash = hash_hmac('sha1', $binary_timestamp, $binary_key, true);

    // generate otp from hash
    $offset = ord($hash[19]) & 0xf;
    $otp = (
        ((ord($hash[$offset+0]) & 0x7f) << 24 ) |
        ((ord($hash[$offset+1]) & 0xff) << 16 ) |
        ((ord($hash[$offset+2]) & 0xff) << 8 ) |
        (ord($hash[$offset+3]) & 0xff)
    ) % pow(10, 6);

   return $otp;
}

Szeretném ugyanazt a funktionalitást elérni bash-ben, de nem tartok még ott.

#!/bin/bash

T=$(echo $(date +%s) / 30 | bc)
export T
TB=$(perl -e "print pack(\"N*\", 0).pack(\"N*\", $T)")
echo $TB | od
K="TITOK123"
keyhex=$(printf '%s' "$TB" | openssl dgst -sha1 -hmac $K | cut -d' ' -f2 )
echo $keyhex
dec=$(echo "ibase=16; $(echo $keyhex | tr '[:lower:]' '[:upper:]')" | bc)
echo $dec
key=$(echo "$dec % 1000000" | bc)
echo "$key"

Erre a soora gyanakszom a leginkább:

TB=$(perl -e "print pack(\"N*\", 0).pack(\"N*\", $T)")

Hozzászólások

Mi ertelme van annak, hogy az egyik scriptnyelvet (php) lecsereled arra, hogy bash-bol perl-t (masik scriptnyelvet) hivogatsz?

Van php-cli csomag, gyonyoruen mukodik. A $_SERVER["argv"];-bol kinyered a kulcsot, meghivod a fuggvenyed, vegen echo-zod, es orulsz.

A strange game. The only winning move is not to play. How about a nice game of chess?