伪随机函数?

2024-04-23 16:59:42 发布

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

我目前正在进行一个加密项目,我在我的程序中正确地实现了一个凯撒函数,但我需要实现另一个加密方法。在

说明:我们将使用名为伪随机偏移量的修改版本。我们不需要预先分发一本书,只需要一个密码,而且这些都比较短,不需要写下来。然后使用密码为python随机数生成器设定种子,如上所述。您应该从Caesarian代码开始,但是不要在函数的开头创建一个偏移量,而是为每个字符创建一个新的偏移量。

下面是我的剖腹产代码。有人能给我举一个例子来说明代码中的一个字符,这样我就可以了解到底发生了什么了?我是python新手,还在学习。在

def Caesarian(fin, fout, encrypt_or_decrypt_choice, alphabet):
    # Determine the offset by generating a random number in the correct range.
    # This will be the same random number, if the password sent to random.seed is the same.
    offset = random.randrange(1,len(alphabet))
    if encrypt_or_decrypt_choice=='d':
        offset = -offset
    print "Using the secret offset of", offset

    # Read every line of the input file.
    for line1 in fin:
        # Alter each character of the line1, putting the result into line2.
        line2 = ""
        for c in line1:
            if c in alphabet:
                pos1 = alphabet.find(c)
                pos2 = (pos1+offset)%len(alphabet)
                line2 += alphabet[pos2]
        # Write each resulting line2 to the output file.
        fout.write(line2)

Tags: ofthe函数代码in密码ifrandom
1条回答
网友
1楼 · 发布于 2024-04-23 16:59:42

在Ceaser密码中,每个字符的移位量都是固定的。在

Vigenère cipher是一种改进,通过在一小群中移动固定数量的每个字母。例如,一个123的密钥可能意味着“移动一次,然后移动两次,然后移动三次,然后重复”,因此消息“aaaaaa”将被加密为“bcdbcd”。在

Vigenère密码与Ceaser密码有一个共同的弱点——可以计算出最常见的字母模式的统计信息,并使用它们来优化密钥的暴力搜索。在

您正在构建的是稍微复杂一点的-一个简单的流密码。这里的目标是对每个字符加密不同的量,因此它几乎是一次性的,但不需要传输非常大的密钥。在

现在来看一下Python的random模块:

>>> import random
>>> random.choice(range(100))
42
>>> random.choice(range(100))
46
>>> random.choice(range(100))
92

如您所见,每个值都是不同的。如果我们重新运行Python,我们会得到一系列不同的数字。如果数字真的是随机的,那么对于这种加密方法来说,它们将是无用的,因为接收方将无法重新创建相同的流。在

通过设定伪随机数生成器,我们可以修复初始状态,以便结果是可预测的:

^{pr2}$

现在如果我重新播种,我们会得到相同的数字:

^{pr2}$

要迁移原始代码,您需要将offset的初始计算更改为设置种子,然后更新每个字符的偏移量。在

(我尝试更新粘贴的代码):

def streamCipher(fin, fout, encrypt_or_decrypt_choice, alphabet, seed):
    # Seed random with the shared secret
    random.seed(seed)

    # Read every line of the input file.
    for line1 in fin:
        # Alter each character of the line1, putting the result into line2.
        line2 = ""
        for c in line1:
            if c in alphabet:
                # Determine the offset by generating a random number in the correct range.
                # This will return the same sequence of random numbers, if the seed is the same.
                offset = random.randrange(1,len(alphabet))
                if encrypt_or_decrypt_choice=='d':
                    offset = -offset
                pos1 = alphabet.find(c)
                pos2 = (pos1+offset)%len(alphabet)
                line2 += alphabet[pos2]
        # Write each resulting line2 to the output file.
        fout.write(line2)

相关问题 更多 >