You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用Python实现One-Time Pad(一次性密码本)加密算法

One-Time Pad(一次性密码本)Python 实现

一次性密码本的加密逻辑本质是明文与等长真随机密钥逐字节做异或运算,只要满足密钥等长、真随机、仅使用一次三个条件,理论上无法被破解。

实现代码

import secrets
import base64

def generate_otp_key(byte_length: int) -> bytes:
    """生成指定字节长度的真随机OTP密钥"""
    return secrets.token_bytes(byte_length)

def otp_encrypt(plaintext: str, key: bytes) -> bytes:
    """OTP加密:输入明文字符串、密钥字节,返回密文字节"""
    plain_bytes = plaintext.encode("utf-8")
    if len(plain_bytes) != len(key):
        raise ValueError("密钥字节长度必须与明文编码后的字节长度一致")
    return bytes([p ^ k for p, k in zip(plain_bytes, key)])

def otp_decrypt(cipher_bytes: bytes, key: bytes) -> str:
    """OTP解密:输入密文字节、密钥字节,返回明文字符串"""
    if len(cipher_bytes) != len(key):
        raise ValueError("密钥字节长度必须与密文字节长度一致")
    plain_bytes = bytes([c ^ k for c, k in zip(cipher_bytes, key)])
    return plain_bytes.decode("utf-8")

# 示例用法
if __name__ == "__main__":
    test_plaintext = "这是需要加密的敏感内容123@abc"
    # 先计算明文编码后的字节长度,生成对应长度的密钥
    plain_byte_length = len(test_plaintext.encode("utf-8"))
    otp_key = generate_otp_key(plain_byte_length)

    # 加密
    cipher = otp_encrypt(test_plaintext, otp_key)
    # 密文转base64方便存储/传输
    cipher_base64 = base64.b64encode(cipher).decode("utf-8")
    print(f"Base64编码后的密文:{cipher_base64}")

    # 解密
    cipher_raw = base64.b64decode(cipher_base64)
    decrypted_result = otp_decrypt(cipher_raw, otp_key)
    print(f"解密得到的明文:{decrypted_result}")

注意事项

  • 必须使用真随机源生成密钥:禁止使用random这类伪随机数生成器,secrets模块调用的是操作系统级的真随机接口,符合OTP的安全要求。
  • 密钥绝对不能重复使用:同一个密钥加密多条明文会直接破坏OTP的安全性,攻击者可通过密文关联分析破解内容。
  • 密钥需要和明文同等保密:密钥泄露等同于明文泄露,使用后必须彻底销毁,不能留存。
  • 实际使用时如果需要传输密文和密钥,必须走完全隔离的不同通道,避免同时被截获。

内容的提问来源于stack exchange,提问作者Farshid Ashouri

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.25 22:15:04