Extract OTP Key using regex

1.7k views Asked by At

I have a script that enables OTP / Google Auth via SSH keys and OTP on linux systems. Once OTP is enabled I send the user a SMS with an otpauth URL. I need to extract the ( normally 16 digit key ) from the otpauth URL.

If they want a visible QR code, an example of the URL is below:

https://www.google.com/chart?chs=200x200&chld=M|0&cht=qr&chl=otpauth://totp/[email protected]%3Fsecret%3DWFHGHUFAUYXZFA44%26issuer%3DCOMPANY

If they want an otpauth url they can click on to import into a Token / Password Manager, I use the following:

otpauth://totp/[email protected]%3Fsecret%3DWFHGHUFAUYXZFA44%26issuer%3DCOMPANY

How can I extract the Secret Key from the URL ?

2

There are 2 answers

3
anubhava On BEST ANSWER

Using grep -oP:

url='https://www.google.com/chart?chs=200x200&chld=M|0&cht=qr&chl=otpauth://totp/[email protected]%3Fsecret%3DWFHGHUFAUYXZFA44%26issuer%3DCOMPANY'

grep -ioP '[?&]chl=.+?%3Fsecret%3D\K[^%]+' <<< "$url"
WFHGHUFAUYXZFA44
0
OnlineCop On

secret%3D(.*?)(?=%|$) will find 'secret', the %3D, then the number up until it reaches the end of the line or another % character.

Regex101.com example