线性同余生成器使用python生成密钥流并对明文进行加密和解密

2024-06-28 11:13:14 发布

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

我正在使用线性同余生成器生成密钥流,然后我将使用此密钥流对明文进行加密和解密。我正在尝试生成47个伪随机数。明文将是“Meetmeattownhallatsevenpmforpaymentandbringbear” 密钥流的长度需要和明文的长度相同。 然后我们将生成的数字映射到查找字母表中的字母表

alphabet of letters

我正在创建一个python脚本来执行线性同余生成器来生成密钥流。我试图加密明文,“准备下午5点在市政厅见面”。我做这件事有困难。 我正在使用下面的线性同余生成器的算法

Xn+1 = (aXn + c) mod m

其中Xn是伪随机值序列,并且

• Modulus: m, 0 < m
• Multiplier: a, 0 < a < m
• Increment: c, 0 ≤ c < m
• Seed: X0, 0 ≤ X0 < m

Python代码

# Initialize the seed state
#!/usr/bin/env python#!/usr/bin/env python3
def linearCongruentialGenerator(Xo, m, a, c,randomNums,noOfRandomNums):

# Initialize the seed state
randomNums[0] = Xo

# Traverse to generate required
# numbers of random numbers
for i in range(1, noOfRandomNums):
     
    # Follow the linear congruential method
    randomNums[i] = ((randomNums[i - 1] * a) +
                                     c) % m

#Main function
if __name__ == '__main__':
 
# Seed value
Xo = 27
 
# Modulus parameter
m = 100
 
# Multiplier term
a = 17
 
# Increment term
c = 43

# Number of Random numbers
# to be generated
noOfRandomNums = 47

#Variable to declare the randomnumber
randomNums = [0] * (noOfRandomNums)

#Call the function
linearCongruentialGenerator(Xo, m, a, c,randomNums,noOfRandomNums)

# Print the generated random numbers
for i in randomNums:
    print(i, end = " ")

我希望输出像这样

Output of the script

请您在线性同余生成器python中帮助我生成密钥流以加密和解密明文,以及如何将生成的数字映射到明文的字符

多谢各位


Tags: theto线性数字字母表seednumbersmultiplier
1条回答
网友
1楼 · 发布于 2024-06-28 11:13:14

您对Linear Congruential Generator的实现看起来是正确的


所以剩下的任务是映射。您可以使用zip创建具有随机数的字符映射

plainttext = "randomtext"

unique = set(plainttext)

random_numbers = [37, 11, 23, 41, 28, 19, 27, 9, 31]

mapping = dict(zip(unique, random_numbers))
print(mapping)
{'o': 37, 'm': 11, 'a': 23, 'e': 41, 'x': 28, 'd': 19, 'r': 27, 'n': 9, 't': 31}

相关问题 更多 >