协助伪随机函数?

时间:2013-03-25 20:06:21

标签: python python-2.7

我目前正在开发一个加密项目,我在我的程序中正确实现了一个Caesarian函数,但是我需要实现另一种加密方法。

说明:我们将使用一个名为Pseudo-random offset的修改版本。我们不需要预先分发一本书,只需一个密码,而且这些都是较短的,不需要写下来。然后,密码用于为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)

1 个答案:

答案 0 :(得分:3)

在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,我们会得到一系列不同的数字。如果这些数字是真正随机的,那么这种加密方法就没用了,因为接收方无法重新创建相同的流。

播种伪随机数生成器允许我们修复初始状态,以便结果可预测:

>>> random.seed(5)
>>> random.choice(range(100))
62
>>> random.choice(range(100))
74

现在,如果我重播它,我们将得到相同的确切数字:

>>> random.seed(5)
>>> random.choice(range(100))
62
>>> random.choice(range(100))
74

要迁移原始代码,您需要将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)
相关问题