Python3을 사용하여 OTP 생성

WBOY
풀어 주다: 2024-09-03 17:03:02
원래의
736명이 탐색했습니다.

Since we were not allowed to have MFA together with the same application we are using, I got an idea from my leader to just have a generated OTPs.

import time
import hmac
import base64
import struct
import hashlib

def generate_otp(secret, interval=30, digits=6):
    # Decode the base32 encoded secret
    key = base64.b32decode(secret)

    # Calculate the number of time intervals since the Unix epoch
    counter = int(time.time()) // interval

    # Convert the counter to bytes
    msg= struct.pack(">Q", counter)

    # Create the HMAC hash using SHA-1
    hmac_hash = hmac.new(key, msg, hashlib.sha1).digest()

    # Get the dynamic offset from the last nibble of the hash
    offset = hmac_hash[-1] & 0x0F

    # Extract a 4-byte dynamic binary code form the hash using the offset
    code = struct.unpack(">I", hmac_hash[offset:offset + 4]) [0] & 0x7FFFFFFF

    # Modulus operation to get the final OTP
    otp = code % (10 ** digits)

    return str(otp).zfill(digits)

# Lists for secret keys and remarks
secret_keys_with_titles = {
    "[name]": "[secret_key]",
    "VAR": "ABDCDEFGHIJKLMNO",
    "VER": "PQRSTUVWXYZ12345",
    "VIR": "6789101112131415"
}

# ANSI escape codes for different color
colors = [
    "\033[91m", # Red
    "\033[92m", # Green
    "\033[94m", # Blue
    "\033[93m", # Yellow
    "\033[96m", # Cyan
]
print()
# Generate the OTPs for all secret keys
otps = {title: generate_otp(secret) for title, secret in secret_keys_with_titles.items()}

# Output the OTPs in horizontal way
output = []
for i, (title, otp) in enumerate(otps.items()):
    color = colors[i % len(colors)] # Rotate through colors
    output.append(f"{color}{title}: {otp}\033[0m") #\033[0m resets the color

print(" | ".join(output))
print()

로그인 후 복사

So, this is how it look on your terminal:

Generated OTP using python3

위 내용은 Python3을 사용하여 OTP 생성의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

원천:dev.to
본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
인기 튜토리얼
더>
최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿
회사 소개 부인 성명 Sitemap
PHP 중국어 웹사이트:공공복지 온라인 PHP 교육,PHP 학습자의 빠른 성장을 도와주세요!