Created
June 29, 2023 10:42
-
-
Save pitermarx/242a42f39c56d4eafefd069636847e01 to your computer and use it in GitHub Desktop.
Powershell OTP function
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function otp($SECRET="ABCDEFGHIJKLMNOP", $LENGTH=6, $WINDOW=30){ | |
$span = (New-TimeSpan -Start (Get-Date -Year 1970 -Month 1 -Day 1 -Hour 0 -Minute 0 -Second 0) -End (Get-Date).ToUniversalTime()).TotalSeconds | |
$unixTime = [Convert]::ToInt64([Math]::Floor($span/$WINDOW)) | |
$timeBytes = [BitConverter]::GetBytes($unixTime) | |
[array]::Reverse($timeBytes) | |
$enc = [System.Text.Encoding]::UTF8 | |
$hmac = New-Object -TypeName System.Security.Cryptography.HMACSHA1 | |
$hmac.key = Convert-Base32ToBytes($SECRET.ToUpper()) | |
$randHash = $hmac.ComputeHash($timeBytes) | |
$offset = $randhash[($randHash.Length-1)] -band 0xf | |
$fullOTP = ($randhash[$offset] -band 0x7f) * [math]::pow(2, 24) | |
$fullOTP += ($randHash[$offset + 1] -band 0xff) * [math]::pow(2, 16) | |
$fullOTP += ($randHash[$offset + 2] -band 0xff) * [math]::pow(2, 8) | |
$fullOTP += ($randHash[$offset + 3] -band 0xff) | |
$modNumber = [math]::pow(10, $LENGTH) | |
$otp = $fullOTP % $modNumber | |
$otp = $otp.ToString("0" * $LENGTH) | |
set-clipboard $otp | |
return $otp | |
} | |
function Convert-Base32ToBytes($base32) { | |
$base32chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567"; | |
$bits = ""; | |
$hex = ""; | |
for ($i = 0; $i -lt $base32.Length; $i++) { | |
$val = $base32chars.IndexOf($base32.Chars($i)); | |
$binary = [Convert]::ToString($val, 2) | |
$bits += $binary.ToString().PadLeft(5, '0') | |
} | |
for ($i = 0; $i+4 -le $bits.Length; $i+=4) { | |
$chunk = $bits.Substring($i, 4) | |
# Write-Host $chunk | |
$intChunk = [Convert]::ToInt32($chunk, 2) | |
# Write-Host $hexChunk | |
$hex = $hex + ('{0:x}' -f $intChunk) | |
} | |
return $hex -replace '^0x', '' -split "(?<=\G\w{2})(?=\w{2})" | %{ [Convert]::ToByte( $_, 16 ) } | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment