|
发表于 2023-12-23 17:26:29
|
显示全部楼层
哦,抱歉!让我现在补上食用过程。下面是加密和解密的完整代码示例:
- import random
- def encrypt(text, key):
- # 计算字符串密钥中每个字符的ASCII码和
- key_sum = sum(ord(ch) for ch in key)
-
- # 从和中提取四个信息
- info_1 = key_sum % 26
- info_2 = (key_sum // 26) % 26
- info_3 = (key_sum // (26**2)) % 26
- info_4 = (key_sum // (26**3)) % 26
-
- # 生成随机数种子
- random.seed(info_1)
-
- # 加密字符串
- encrypted_text = ""
- for ch in text:
- if ch.isalpha():
- shift = random.randint(1, 26)
- if ch.islower():
- encrypted_ch = chr((ord(ch) - ord('a') + shift) % 26 + ord('a'))
- else:
- encrypted_ch = chr((ord(ch) - ord('A') + shift) % 26 + ord('A'))
- encrypted_text += encrypted_ch
- else:
- encrypted_text += ch
-
- # 随机数交换值
- random.seed(info_2)
- for i in range(info_3):
- index_1 = random.randint(0, len(encrypted_text)-1)
- index_2 = random.randint(0, len(encrypted_text)-1)
- encrypted_text = list(encrypted_text)
- encrypted_text[index_1], encrypted_text[index_2] = encrypted_text[index_2], encrypted_text[index_1]
- encrypted_text = "".join(encrypted_text)
-
- return encrypted_text
- def decrypt(text, key):
- # 计算字符串密钥中每个字符的ASCII码和
- key_sum = sum(ord(ch) for ch in key)
-
- # 从和中提取四个信息
- info_1 = key_sum % 26
- info_2 = (key_sum // 26) % 26
- info_3 = (key_sum // (26**2)) % 26
- info_4 = (key_sum // (26**3)) % 26
-
- # 随机数交换值(反向)
- random.seed(info_2)
- for i in range(info_3):
- index_1 = random.randint(0, len(text)-1)
- index_2 = random.randint(0, len(text)-1)
- text = list(text)
- text[index_1], text[index_2] = text[index_2], text[index_1]
- text = "".join(text)
-
- # 生成随机数种子(反向)
- random.seed(info_1)
-
- # 解密字符串
- decrypted_text = ""
- for ch in text:
- if ch.isalpha():
- shift = random.randint(1, 26)
- if ch.islower():
- decrypted_ch = chr((ord(ch) - ord('a') - shift) % 26 + ord('a'))
- else:
- decrypted_ch = chr((ord(ch) - ord('A') - shift) % 26 + ord('A'))
- decrypted_text += decrypted_ch
- else:
- decrypted_text += ch
-
- return decrypted_text
- # 测试加密和解密过程
- plaintext = "Hello, World!"
- key = "secret"
- ciphertext = encrypt(plaintext, key)
- print("加密后的文本:", ciphertext)
- decrypted_text = decrypt(ciphertext, key)
- print("解密后的文本:", decrypted_text)
复制代码
希望以上代码可以帮到你!如果还有其他问题,请随时提问。
以上回复来自 FishC AI 小助理,如未能正确解答您的问题,请继续追问。 |
|