You need to enable JavaScript to run this app. 如何使用Python实现Scytale密码的编码与解码
优惠活动
大模型
产品
解决方案
定价
更多

如何使用Python实现Scytale密码的编码与解码

Scytale密码Python实现教程

基础原理

Scytale是古希腊时期使用的换位类密码,核心逻辑依赖行数(即密钥)实现字符换位:

  • 加密时将明文按行写入密钥行的网格,不足位可自定义填充字符补全,再按列顺序读取所有字符得到密文
  • 解密时反向操作,将密文按列写入密钥行的网格,再按行读取去除填充后得到明文

加密实现

def scytale_encrypt(plaintext: str, key: int) -> str:
    # 可选:移除明文中的空格,不需要可注释该行
    plaintext = plaintext.replace(" ", "")
    # 计算填充长度,保证明文长度是key的整数倍
    padding_len = (key - len(plaintext) % key) % key
    # 自定义填充字符,这里用'X',可按需修改
    plaintext += "X" * padding_len
    col_num = len(plaintext) // key
    ciphertext = ""
    # 按列遍历读取字符
    for col in range(col_num):
        for row in range(key):
            ciphertext += plaintext[row * col_num + col]
    return ciphertext

解密实现

def scytale_decrypt(ciphertext: str, key: int) -> str:
    col_num = len(ciphertext) // key
    plaintext_list = [""] * len(ciphertext)
    char_idx = 0
    # 按列写入字符到网格
    for col in range(col_num):
        for row in range(key):
            plaintext_list[row * col_num + col] = ciphertext[char_idx]
            char_idx += 1
    # 拼接明文并移除末尾填充的'X'
    return "".join(plaintext_list).rstrip("X")

测试用例

if __name__ == "__main__":
    original_text = "THIS IS A TEST FOR SCYTALE"
    secret_key = 4
    encrypted_text = scytale_encrypt(original_text, secret_key)
    print(f"加密结果: {encrypted_text}")
    decrypted_text = scytale_decrypt(encrypted_text, secret_key)
    print(f"解密结果: {decrypted_text}")

输出示例:

加密结果: TSSSCTIEIAEAHITTRFSLOEENXTX
解密结果: THISISATESTFORSCYTALE

未知密钥暴力破解(可选)

如果拿到密文不知道对应密钥,可遍历所有合法取值的密钥输出结果,人工筛选有意义的明文:

def brute_force_scytale(ciphertext: str) -> None:
    # 密钥取值范围为2到密文长度,可按需缩小范围
    for possible_key in range(2, len(ciphertext)):
        if len(ciphertext) % possible_key != 0:
            continue
        decrypt_result = scytale_decrypt(ciphertext, possible_key)
        print(f"密钥为{possible_key}时解密结果: {decrypt_result}")

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.13 08:42:01