如何在python中修改密文?

2024-04-30 07:01:21 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图同时学习python和密码学。你知道吗

我试图改变一点(或更多)的密文,看看它会对我的明文解密时产生的影响。你知道吗

例如:

from Crypto.Cipher import AES
import base64
import os

BLOCK_SIZE = 16
key = os.urandom(BLOCK_SIZE)

PADDING = '{'
pad = lambda s: s + (BLOCK_SIZE - len(s) % BLOCK_SIZE) * PADDING

EncodeAES = lambda c, s: base64.b64encode(c.encrypt(pad(s)))
DecodeAES = lambda c, e: c.decrypt(base64.b64decode(e)).rstrip(PADDING)

cipher = AES.new(key)

# encode a string
encoded = EncodeAES(cipher, 'This is some text.')
print 'Encrypted string:', encoded

# decode the encoded string
decoded = DecodeAES(cipher, encoded)
print 'Decrypted string:', decoded

所以我想再次解密,除了在解密之前修改了密文(“编码”)。你知道吗

谢谢。你知道吗


Tags: lambdakeyimportsizestringosblockaes
1条回答
网友
1楼 · 发布于 2024-04-30 07:01:21

我能想到的给encoded字符串引入一些噪声的最简单方法是改变其中的每n个字符。您可以使用字符串操作来引入或多或少的随机噪声(使第n个字符成为随机字符,在每次迭代中更改它,等等)。你知道吗

添加此函数并在代码之前导入:

import string
import random

def noise_every_n(input, n, first=0):
    output = ""
    for i, c in enumerate(input, -first):
        if i % n == 0: # using ascii_letters and digits is just what came to mind, there's other ways to get random characters.
            output += random.choice(string.ascii_letters + string.digits)
        else:
            output += c
    return output

然后在encodedecode之间调用以下命令:

every_n = random.randint(3, 5) # or just set it to a small integer
encoded = noise_every_n(encoded, every_n) 

上述函数改编自this Stack Overflow answer。你知道吗

相关问题 更多 >