mirror of
https://github.com/InternLM/InternBootcamp.git
synced 2026-04-25 17:10:49 +00:00
init-commit
This commit is contained in:
commit
18a552597a
3461 changed files with 1150579 additions and 0 deletions
54
internbootcamp/libs/cipher/Asc2Environment.py
Executable file
54
internbootcamp/libs/cipher/Asc2Environment.py
Executable file
|
|
@ -0,0 +1,54 @@
|
|||
from .BaseCipherEnvironment import BaseCipherEnvironment
|
||||
|
||||
class Asc2Environment(BaseCipherEnvironment):
|
||||
def __init__(self, *args, **kwargs):
|
||||
problem_description = ''
|
||||
super().__init__(problem_description, *args, **kwargs)
|
||||
|
||||
@property
|
||||
def cipher_name(self):
|
||||
return "ASCII"
|
||||
def encode(self, text):
|
||||
# 初始化一个空列表,用于存储ASCII编码
|
||||
ascii_list = []
|
||||
# 遍历输入字符串中的每个字符
|
||||
for char in text:
|
||||
# 获取字符的ASCII编码
|
||||
ascii_code = ord(char)
|
||||
# 将ASCII编码添加到列表中
|
||||
ascii_list.append(ascii_code)
|
||||
# 打印字符及其对应的ASCII编码
|
||||
print(f"Character: {char}, ASCII Code: {ascii_code}")
|
||||
# print(f"Current ASCII List: {ascii_list}\n")
|
||||
print("ASCII List:", ascii_list)
|
||||
# 返回ASCII编码列表
|
||||
return ascii_list
|
||||
|
||||
def get_encode_rule(self, ):
|
||||
return """加密方案概述:将字符串转换为ASCII编码。"""
|
||||
|
||||
|
||||
def decode(self, text):
|
||||
"""
|
||||
将ASCII编码列表转换为字符串,并打印每个ASCII码及其对应的字符。
|
||||
:param ascii_list: 包含ASCII编码的列表
|
||||
:return: 转换后的字符串
|
||||
"""
|
||||
|
||||
result = ""
|
||||
for ascii_code in text:
|
||||
# 检查ASCII码是否在可打印字符的范围内
|
||||
if 32 <= ascii_code <= 126:
|
||||
# 将ASCII码转换为字符,并添加到结果字符串中
|
||||
result += chr(ascii_code)
|
||||
# 打印ASCII码及其对应的字符
|
||||
print(f"ASCII Code: {ascii_code}, Character: {chr(ascii_code)}")
|
||||
else:
|
||||
# 如果ASCII码不在可打印字符的范围内,打印警告信息
|
||||
print(f"Warning: ASCII Code {ascii_code} is not a printable character.")
|
||||
print("Result:", result)
|
||||
return result
|
||||
|
||||
def get_decode_rule(self, ):
|
||||
return """解密方案概述:遍历ASCII编码字符串,返回转换后的字符串"""
|
||||
|
||||
107
internbootcamp/libs/cipher/AtbashCipherEnvironment.py
Executable file
107
internbootcamp/libs/cipher/AtbashCipherEnvironment.py
Executable file
|
|
@ -0,0 +1,107 @@
|
|||
from .BaseCipherEnvironment import BaseCipherEnvironment
|
||||
|
||||
class AtbashCipher:
|
||||
"""实现 Atbash 密码的类,用于字符串转换。
|
||||
|
||||
Atbash 密码是一种简单的替换密码,其中每个字母都被其在字母表中的反向对应字母所替换。
|
||||
"""
|
||||
|
||||
def __init__(self):
|
||||
"""初始化 AtbashCipher 对象。"""
|
||||
pass
|
||||
|
||||
def transform(self, text: str) -> str:
|
||||
"""使用 Atbash 密码转换输入文本。
|
||||
|
||||
Args:
|
||||
text (str): 要转换的输入文本。
|
||||
|
||||
Returns:
|
||||
str: 应用 Atbash 密码后转换的文本。
|
||||
"""
|
||||
result = [] # 存储转换后的字符
|
||||
words = text.split() # 将文本拆分成单词
|
||||
|
||||
# 逐个处理每个单词
|
||||
for word in words:
|
||||
print(f"转换单词: {word}")
|
||||
transformed_word = [] # 存储单词中转换后的字符
|
||||
|
||||
# 转换单词中的每个字符
|
||||
for char in word:
|
||||
if char.isalpha(): # 检查字符是否为字母
|
||||
if char.islower():
|
||||
transformed_char = chr(219 - ord(char)) # 小写字母转换
|
||||
else:
|
||||
transformed_char = chr(155 - ord(char)) # 大写字母转换
|
||||
print(f" '{char}' -> '{transformed_char}'")
|
||||
else:
|
||||
transformed_char = char # 非字母字符保持不变
|
||||
print(f" '{char}' 保持不变")
|
||||
|
||||
transformed_word.append(transformed_char)
|
||||
|
||||
# 将单词中转换后的字符重新组合并添加到结果中
|
||||
result.append(''.join(transformed_word))
|
||||
|
||||
# 将转换后的单词重新组合成句子并返回
|
||||
return ' '.join(result)
|
||||
|
||||
|
||||
class AtbashCipherEnvironment(BaseCipherEnvironment):
|
||||
def __init__(self, *args, **kwargs):
|
||||
problem_description = ''
|
||||
super().__init__(problem_description, *args, **kwargs)
|
||||
|
||||
@property
|
||||
def cipher_name(self) -> str:
|
||||
"""返回密码的名称。
|
||||
"""
|
||||
return "AtbashCipher"
|
||||
def encode(self, text: str, **kwargs) -> str:
|
||||
"""使用 Atbash 密码对输入文本进行编码。
|
||||
|
||||
Args:
|
||||
text (str): 要编码的输入文本。
|
||||
|
||||
Returns:
|
||||
str: 应用 Atbash 密码后编码的文本。
|
||||
"""
|
||||
print("编码过程:")
|
||||
cipher = AtbashCipher()
|
||||
encode_text = cipher.transform(text)
|
||||
print(f"编码后的文本: {encode_text}")
|
||||
return encode_text
|
||||
|
||||
def decode(self, text: str, **kwargs) -> str:
|
||||
"""使用 Atbash 密码对输入文本进行解码。
|
||||
|
||||
Args:
|
||||
text (str): 要解码的输入文本。
|
||||
|
||||
Returns:
|
||||
str: 应用 Atbash 密码后解码的文本。
|
||||
"""
|
||||
print("解码过程:")
|
||||
cipher = AtbashCipher()
|
||||
decode_text = cipher.transform(text)
|
||||
print(f"解码后的文本: {decode_text}")
|
||||
return decode_text
|
||||
|
||||
def get_encode_rule(self, ) -> str:
|
||||
"""返回编码规则的自然语言描述。
|
||||
|
||||
Returns:
|
||||
str: 编码规则的自然语言描述。
|
||||
"""
|
||||
return "Atbash 密码的编码规则是将每个字母替换为其在字母表中的反向对应字母。例如,'A' 变成 'Z','B' 变成 'Y',依此类推。非字母字符保持不变。"
|
||||
|
||||
def get_decode_rule(self, ) -> str:
|
||||
"""返回解码规则的自然语言描述。
|
||||
|
||||
Returns:
|
||||
str: 解码规则的自然语言描述。
|
||||
"""
|
||||
return "Atbash 密码的解码规则是将每个字母替换为其在字母表中的反向对应字母。由于 Atbash 密码是对称的,解码过程与编码过程相同。例如,'Z' 变成 'A','Y' 变成 'B',依此类推。非字母字符保持不变。"
|
||||
|
||||
|
||||
100
internbootcamp/libs/cipher/BaseCipherEnvironment.py
Executable file
100
internbootcamp/libs/cipher/BaseCipherEnvironment.py
Executable file
|
|
@ -0,0 +1,100 @@
|
|||
from abc import abstractmethod
|
||||
from .BaseEnvironment import BaseEnvironment
|
||||
from bootcamp_utils import catch_print
|
||||
|
||||
|
||||
class BaseCipherEnvironment(BaseEnvironment):
|
||||
"""
|
||||
Cipher环境基类
|
||||
"""
|
||||
|
||||
def __init__(self,problem_description, *args, **kwargs):
|
||||
super().__init__(problem_description, *args, **kwargs)
|
||||
def generator(self, plaintext: str = "", **kwargs) -> tuple:
|
||||
"""
|
||||
根据问题描述生成或加载题目数据,这里使用给定的明文,并加密它。
|
||||
"""
|
||||
self.plaintext = plaintext
|
||||
self.gen_steps,self.ciphertext = catch_print(self.encode,text=self.plaintext,**kwargs)
|
||||
for k,v in kwargs.items():
|
||||
setattr(self,k,v)
|
||||
return self.gen_steps,self.ciphertext
|
||||
|
||||
def solver(self, **kwargs) -> tuple:
|
||||
"""
|
||||
解题函数,执行解题逻辑并返回结果。
|
||||
"""
|
||||
self.solve_steps,self.decodetext = catch_print(self.decode,text=self.ciphertext,**kwargs)
|
||||
return self.solve_steps,self.decodetext
|
||||
|
||||
@abstractmethod
|
||||
def encode(self,text, **kwargs) -> str:
|
||||
"""
|
||||
编码函数
|
||||
|
||||
参数:
|
||||
text: 需要加密的文本(字符串)
|
||||
|
||||
返回:
|
||||
加密后的文本(字符串)
|
||||
"""
|
||||
pass
|
||||
|
||||
|
||||
@abstractmethod
|
||||
def decode(self, text, **kwargs) -> str:
|
||||
"""
|
||||
解码函数
|
||||
|
||||
参数:
|
||||
text: 需要解密的文本(字符串)
|
||||
|
||||
返回:
|
||||
解密后的文本(字符串)
|
||||
"""
|
||||
pass
|
||||
|
||||
|
||||
@abstractmethod
|
||||
def get_encode_rule(self) -> str:
|
||||
"""
|
||||
获取编码规则。
|
||||
"""
|
||||
pass
|
||||
|
||||
@abstractmethod
|
||||
def get_decode_rule(self) -> str:
|
||||
"""
|
||||
获取解码规则。
|
||||
"""
|
||||
pass
|
||||
|
||||
@property
|
||||
@abstractmethod
|
||||
def cipher_name(self) -> str:
|
||||
"""
|
||||
获取密码名称。
|
||||
"""
|
||||
pass
|
||||
|
||||
|
||||
def check_solution(self, solution: object) -> bool:
|
||||
"""
|
||||
检查提供的解答是否正确。
|
||||
"""
|
||||
return solution == self.plaintext
|
||||
|
||||
@property
|
||||
def is_solved(self) -> bool:
|
||||
"""
|
||||
获取题目是否已被解决的状态。
|
||||
"""
|
||||
return self.plaintext and self.decodetext
|
||||
|
||||
def reset(self) -> None:
|
||||
"""
|
||||
重置环境到初始状态。
|
||||
"""
|
||||
self.plaintext = ""
|
||||
self.ciphertext = ""
|
||||
|
||||
89
internbootcamp/libs/cipher/BaseEnvironment.py
Executable file
89
internbootcamp/libs/cipher/BaseEnvironment.py
Executable file
|
|
@ -0,0 +1,89 @@
|
|||
from abc import ABC, abstractmethod
|
||||
|
||||
class BaseEnvironment(ABC):
|
||||
def __init__(self, problem_description: str = None, *args, **kwargs):
|
||||
"""
|
||||
构造函数接收题目描述和其他参数,初始化环境。
|
||||
|
||||
:param problem_description: 题目描述文本
|
||||
:param args: 其他位置参数
|
||||
:param kwargs: 其他关键字参数
|
||||
"""
|
||||
self.problem_description = problem_description
|
||||
self.kwargs = kwargs
|
||||
for k,v in self.kwargs.items():
|
||||
setattr(self, k, v)
|
||||
@abstractmethod
|
||||
def generator(self) -> object:
|
||||
"""
|
||||
构建具体的题目实例,生成或加载题目数据。
|
||||
"""
|
||||
pass
|
||||
|
||||
@abstractmethod
|
||||
def solver(self) -> object:
|
||||
"""
|
||||
解题函数,执行解题逻辑并返回结果。
|
||||
"""
|
||||
pass
|
||||
|
||||
@abstractmethod
|
||||
def check_solution(self, solution: object) -> bool:
|
||||
"""
|
||||
检查提供的解答是否正确。
|
||||
|
||||
:param solution: 提供的答案对象
|
||||
:return: 如果解答正确返回True,否则False
|
||||
"""
|
||||
pass
|
||||
|
||||
@abstractmethod
|
||||
def reset(self) -> None:
|
||||
"""
|
||||
重置环境到初始状态。
|
||||
"""
|
||||
pass
|
||||
|
||||
@property
|
||||
@abstractmethod
|
||||
def is_solved(self) -> bool:
|
||||
"""
|
||||
获取题目是否已被解决的状态。
|
||||
"""
|
||||
pass
|
||||
|
||||
def get_question(self) -> str:
|
||||
"""
|
||||
提供生成题目的问题或解决题目的问题。
|
||||
"""
|
||||
return "No question available."
|
||||
|
||||
def get_question_following(self) -> str:
|
||||
"""
|
||||
提供题目回答的可替换后缀,如回复格式规范等。
|
||||
"""
|
||||
followings = []
|
||||
followings.append("""\n请以如下格式输出结果:
|
||||
```json
|
||||
{
|
||||
'final_answer': <your answer>
|
||||
}
|
||||
```""")
|
||||
|
||||
def get_hint(self) -> str:
|
||||
"""
|
||||
提供关于如何生成或解决问题的提示信息(可选)。
|
||||
"""
|
||||
return "No hint available."
|
||||
|
||||
def get_additional_resources(self) -> list:
|
||||
"""
|
||||
返回可用于解决问题的额外资源列表(可选)。
|
||||
"""
|
||||
return []
|
||||
|
||||
def __str__(self) -> str:
|
||||
"""
|
||||
返回环境的字符串表示,通常包含当前环境的状态信息。
|
||||
"""
|
||||
return f"Environment for problem: {self.problem_description}"
|
||||
91
internbootcamp/libs/cipher/CeaserCipherEnvironment.py
Executable file
91
internbootcamp/libs/cipher/CeaserCipherEnvironment.py
Executable file
|
|
@ -0,0 +1,91 @@
|
|||
from .BaseCipherEnvironment import BaseCipherEnvironment
|
||||
|
||||
|
||||
class CeaserCipherEnvironment(BaseCipherEnvironment):
|
||||
def __init__(self, *args, **kwargs):
|
||||
problem_description = ''
|
||||
super().__init__(problem_description, *args, **kwargs)
|
||||
|
||||
def encode(self, text, shift):
|
||||
"""
|
||||
编码函数:将输入文本中的字母向后移动指定的位数(shift)
|
||||
|
||||
参数:
|
||||
text: 需要加密的文本(字符串)
|
||||
shift: 移动的位数(整数)
|
||||
|
||||
返回:
|
||||
加密后的文本(字符串)
|
||||
"""
|
||||
print(f"开始编码过程,文本为: {text},位移数为: {shift}")
|
||||
result = [] # 用于存储加密后的字符
|
||||
for char in text:
|
||||
if char.isalpha(): # 判断是否是字母
|
||||
print(f"处理字符: {char}")
|
||||
start = ord('A') if char.isupper() else ord('a') # 计算字母的起始ASCII码
|
||||
new_char = chr((ord(char) - start + shift) % 26 + start) # 移动并保持在字母表范围内
|
||||
print(f"字符 {char} 向后移动 {shift} 位,变为 {new_char}")
|
||||
result.append(new_char) # 添加加密后的字母
|
||||
else:
|
||||
print(f"字符 {char} 不是字母,保持不变")
|
||||
result.append(char) # 非字母字符不做改变,直接添加到结果中
|
||||
encoded_text = ''.join(result) # 将列表转化为字符串
|
||||
print(f"编码完成,结果为: {encoded_text}")
|
||||
return encoded_text
|
||||
|
||||
def decode(self, text, shift):
|
||||
"""
|
||||
解码函数:将输入文本中的字母向前移动指定的位数(shift),以还原原始文本
|
||||
|
||||
参数:
|
||||
text: 需要解密的文本(字符串)
|
||||
shift: 移动的位数(整数)
|
||||
|
||||
返回:
|
||||
解密后的文本(字符串)
|
||||
"""
|
||||
print(f"开始解码过程,文本为: {text},位移数为: {shift}")
|
||||
result = [] # 用于存储解密后的字符
|
||||
for char in text:
|
||||
if char.isalpha(): # 判断是否是字母
|
||||
print(f"处理字符: {char}")
|
||||
start = ord('A') if char.isupper() else ord('a') # 计算字母的起始ASCII码
|
||||
new_char = chr((ord(char) - start - shift) % 26 + start) # 向前移动并保持在字母表范围内
|
||||
print(f"字符 {char} 向前移动 {shift} 位,变为 {new_char}")
|
||||
result.append(new_char) # 添加解密后的字母
|
||||
else:
|
||||
print(f"字符 {char} 不是字母,保持不变")
|
||||
result.append(char) # 非字母字符不做改变,直接添加到结果中
|
||||
decoded_text = ''.join(result) # 将列表转化为字符串
|
||||
print(f"解码完成,结果为: {decoded_text}")
|
||||
return decoded_text
|
||||
|
||||
def get_encode_rule(self) -> str:
|
||||
return """加密规则:
|
||||
1. 将输入文本中的每个字母向后移动指定的位数(shift)。
|
||||
2. 输出加密后的文本。"""
|
||||
|
||||
def get_decode_rule(self) -> str:
|
||||
return """解码规则:
|
||||
1. 将输入文本中的每个字母向前移动指定的位数(shift)。
|
||||
2. 输出解密后的文本。"""
|
||||
|
||||
@property
|
||||
def cipher_name(self) -> str:
|
||||
return "Caesar_Cipher"
|
||||
def get_question(self, is_gen) -> str:
|
||||
if is_gen:
|
||||
return self.get_encode_rule() + f"Generate a ciphertext using a Caesar cipher with a shift of {self.shift}."
|
||||
else:
|
||||
return self.get_decode_rule+ f"decode the following ciphertext using a Caesar cipher with a shift of {self.shift}: {self.ciphertext}"
|
||||
def get_hint(self) -> str:
|
||||
"""
|
||||
提供关于如何解决问题的提示信息。
|
||||
"""
|
||||
return "Try to think about how letters can be shifted in the alphabet."
|
||||
|
||||
def get_additional_resources(self) -> list:
|
||||
"""
|
||||
返回可用于解决问题的额外资源列表。
|
||||
"""
|
||||
return ["https://en.wikipedia.org/wiki/Caesar_cipher"]
|
||||
110
internbootcamp/libs/cipher/DoubleCeaserEnvironment.py
Executable file
110
internbootcamp/libs/cipher/DoubleCeaserEnvironment.py
Executable file
|
|
@ -0,0 +1,110 @@
|
|||
from .BaseCipherEnvironment import BaseCipherEnvironment
|
||||
import random
|
||||
|
||||
|
||||
class DoubleCeaserEnvironment(BaseCipherEnvironment):
|
||||
def __init__(self, *args, **kwargs):
|
||||
problem_description = "对于每一个编码前的字母,计算其在字母表中的位置,然后找到两个可能的原始字母位置,这些位置的平均值等于编码后的字母位置。选择一个合理的字母对作为编码结果。"
|
||||
self.problem_description = problem_description
|
||||
super().__init__(problem_description, *args, **kwargs)
|
||||
|
||||
@property
|
||||
def cipher_name(self) -> str:
|
||||
return "DoubleCeaser"
|
||||
|
||||
def decode(self, text, **kwargs):
|
||||
# 将文本转换为大写以保持一致性
|
||||
text = text.upper()
|
||||
encoded_text = ""
|
||||
letters = text
|
||||
print
|
||||
print("开始解码过程:")
|
||||
print("密文: ",text)
|
||||
i = 0
|
||||
pair = ""
|
||||
print("去除非字母字符得到字母对: ", end='')
|
||||
letters = ''.join(filter(str.isalpha, letters))
|
||||
for i in range(0, len(letters), 2):
|
||||
pair = letters[i] + letters[i + 1]
|
||||
print(pair, end=' ')
|
||||
i += 2
|
||||
print('\n')
|
||||
i = 0
|
||||
pair = ""
|
||||
while i < len(text):
|
||||
# 若字母对里有非英文字符,则将该字符添加到解码结果中,然后将字母对里面的字母与下一个字母拼接得到字母对
|
||||
if not text[i].isalpha():
|
||||
encoded_text += text[i]
|
||||
print(f"添加非英文字符 {text[i]} 到解码结果\n")
|
||||
i += 1
|
||||
continue
|
||||
# 获取字母对
|
||||
pair += text[i]
|
||||
if len(pair) < 2:
|
||||
i += 1
|
||||
continue
|
||||
else:
|
||||
i += 1
|
||||
print(f"处理字母对: {pair}")
|
||||
|
||||
|
||||
|
||||
# 计算每个字母的位置
|
||||
position1 = ord(pair[0]) - ord('A') + 1
|
||||
position2 = ord(pair[1]) - ord('A') + 1
|
||||
print(f"字母 {pair[0]} 的位置: {position1}, 字母 {pair[1]} 的位置: {position2}")
|
||||
|
||||
# 计算位置平均值
|
||||
average_position = (position1 + position2) // 2
|
||||
print(f"计算平均位置 = {average_position}")
|
||||
|
||||
# 转换回字母
|
||||
encoded_char = chr(average_position + ord('A') - 1)
|
||||
print(f"转换成字母: {encoded_char}\n")
|
||||
|
||||
# 添加到结果中
|
||||
encoded_text += encoded_char
|
||||
# print(f"当前解码结果: {encoded_text}\n")
|
||||
|
||||
pair = ""
|
||||
print(f"解码结果: {encoded_text}\n")
|
||||
|
||||
return encoded_text
|
||||
|
||||
def encode(self, text, **kwargs):
|
||||
# 将文本转换为大写以保持一致性
|
||||
text = text.upper()
|
||||
decoded_text = ""
|
||||
|
||||
print("开始编码过程:")
|
||||
print(f"明文:{text}\n")
|
||||
for char in text:
|
||||
# 计算原始字母的位置
|
||||
position = ord(char) - ord('A') + 1
|
||||
print(f"处理字符: {char}, 位置: {position}")
|
||||
if position < 0 or position > 26:
|
||||
print(f"\n字符 {char} 不在字母表中,保持不变\n")
|
||||
decoded_text += char
|
||||
# 因为我们不知道原始字母的确切位置,我们假设它们是对称的
|
||||
# 这里我们使用两种可能的组合来恢复原始字母
|
||||
original_positions = [(position + randomint, position - randomint) for randomint in range(-6, 7)]
|
||||
# 乱序位置
|
||||
original_positions = random.sample(original_positions, len(original_positions))
|
||||
# 恢复原始字母
|
||||
for pos1, pos2 in original_positions:
|
||||
if 1 <= pos1 <= 26 and 1 <= pos2 <= 26:
|
||||
original_pair = chr(pos1 + ord('A') - 1) + chr(pos2 + ord('A') - 1)
|
||||
print(f"编码成基于该位置对称字母对: {original_pair} (位置: {pos1} 和 {pos2})\n")
|
||||
decoded_text += original_pair
|
||||
break
|
||||
|
||||
# print(f"当前编码结果: {decoded_text}\n")
|
||||
print("解码完成。结果:", decoded_text)
|
||||
|
||||
return decoded_text
|
||||
|
||||
def get_decode_rule(self, ):
|
||||
return "对于每一对字母,计算它们在字母表中的位置,然后取这两个位置的平均值,再转换成对应的字母。"
|
||||
|
||||
def get_encode_rule(self, ):
|
||||
return "对于每一个编码前的字母,计算其在字母表中的位置,然后找到两个可能的原始字母位置,这些位置的平均值等于编码后的字母位置。选择一个合理的字母对作为编码结果。"
|
||||
221
internbootcamp/libs/cipher/FourSquareCipherEnvironment.py
Executable file
221
internbootcamp/libs/cipher/FourSquareCipherEnvironment.py
Executable file
|
|
@ -0,0 +1,221 @@
|
|||
from .BaseCipherEnvironment import BaseCipherEnvironment
|
||||
|
||||
def create_cipher_matrix(key):
|
||||
"""
|
||||
根据给定的密钥构建5x5的加密矩阵。
|
||||
参数:
|
||||
- key: 用于构建矩阵的字符串
|
||||
|
||||
返回:
|
||||
- 5x5加密矩阵
|
||||
"""
|
||||
unique_key = "".join(dict.fromkeys(key.upper()))
|
||||
alphabet = "ABCDEFGHIJKLMNOPRSTUVWXYZ" # delete Q
|
||||
remaining_letters = "".join([ch for ch in alphabet if ch not in unique_key])
|
||||
full_key = unique_key + remaining_letters
|
||||
matrix = [list(full_key[i:i + 5]) for i in range(0, 25, 5)]
|
||||
return matrix
|
||||
|
||||
|
||||
def find_position(matrix, char):
|
||||
"""
|
||||
查找字符在给定矩阵中的位置。
|
||||
参数:
|
||||
- matrix: 5x5的矩阵
|
||||
- char: 需要查找的字符
|
||||
|
||||
返回:
|
||||
- 字符在矩阵中的行列位置(tuple)
|
||||
"""
|
||||
if char == 'Q':
|
||||
return (4, 2)
|
||||
for i, row in enumerate(matrix):
|
||||
if char in row:
|
||||
return (i, row.index(char))
|
||||
return (-1, -1)
|
||||
|
||||
class FourSquareCipherEnvironment(BaseCipherEnvironment):
|
||||
def __init__(self, *args, **kwargs):
|
||||
problem_description = ''
|
||||
super().__init__(problem_description, *args, **kwargs)
|
||||
|
||||
@property
|
||||
def cipher_name(self) -> str:
|
||||
return "FourSquareCipher"
|
||||
|
||||
def encode(self, text, str1, str2, ):
|
||||
"""
|
||||
使用Four-square Cipher算法加密文本。
|
||||
参数:
|
||||
- str1: 第一个密钥字符串,用于构建第一个加密矩阵
|
||||
- str2: 第二个密钥字符串,用于构建第二个加密矩阵
|
||||
- text: 待加密的明文字符串
|
||||
|
||||
返回:
|
||||
- 加密后的字符串
|
||||
"""
|
||||
# 打印解题方案
|
||||
print("解题方案:")
|
||||
print("1. 构建3个矩阵:默认字母表矩阵M_T,加密矩阵M1和M2(由str1和str2生成)。")
|
||||
print("2. 将明文文本转换为大写字母,仅保留字母字符并分成两个字母一组。")
|
||||
print("3. 对每对字母进行加密:")
|
||||
print(" - 查找每个字母在默认矩阵中的位置,交换其y坐标,")
|
||||
print(" - 根据新坐标从M1和M2矩阵中取出加密后的字母对。")
|
||||
print("4. 输出加密后的文本。\n")
|
||||
# 创建默认字母表矩阵(去除Q)
|
||||
default_matrix = create_cipher_matrix("ABCDEFGHIJKLMNOPRSTUVWXYZ")
|
||||
print("Step 1: 创建默认字母表矩阵 M_T (去除Q):")
|
||||
for row in default_matrix:
|
||||
print(" ".join(row))
|
||||
print()
|
||||
|
||||
# 使用str1和str2创建两个加密矩阵
|
||||
matrix1 = create_cipher_matrix(str1)
|
||||
matrix2 = create_cipher_matrix(str2)
|
||||
|
||||
print("Step 2: 使用密钥构建加密矩阵 M1 和 M2")
|
||||
print("M1 矩阵 (根据密钥 str1):")
|
||||
for row in matrix1:
|
||||
print(" ".join(row))
|
||||
print("\nM2 矩阵 (根据密钥 str2):")
|
||||
for row in matrix2:
|
||||
print(" ".join(row))
|
||||
print()
|
||||
|
||||
# 将明文转换为大写并移除非字母字符
|
||||
text = ''.join(filter(str.isalpha, text.upper()))
|
||||
|
||||
# 如果明文字符个数为奇数,补一个字符 'X'
|
||||
if len(text) % 2 != 0:
|
||||
print('明文字符个数为奇数,补一个字符 X')
|
||||
text += "X"
|
||||
|
||||
# 两个字母一组分组
|
||||
pairs = [text[i:i + 2] for i in range(0, len(text), 2)]
|
||||
print("Step 3: 将明文分成两个字母一组:", pairs)
|
||||
print()
|
||||
|
||||
encrypted_text = []
|
||||
|
||||
# 遍历每对字母进行加密
|
||||
for idx, pair in enumerate(pairs):
|
||||
print(f"Step 4.{idx + 1}: 加密字母对 {pair}")
|
||||
|
||||
# 查找两个字母在默认字母表矩阵中的位置
|
||||
pos1 = find_position(default_matrix, pair[0])
|
||||
pos2 = find_position(default_matrix, pair[1])
|
||||
|
||||
print(f" - {pair[0]} 在 M_T 中的位置: {pos1}")
|
||||
print(f" - {pair[1]} 在 M_T 中的位置: {pos2}")
|
||||
|
||||
# 交换y坐标,得到新位置
|
||||
new_pos1 = (pos1[0], pos2[1])
|
||||
new_pos2 = (pos2[0], pos1[1])
|
||||
|
||||
print(f" - 交换列索引后新位置: {new_pos1} 和 {new_pos2}")
|
||||
|
||||
# 从第一个和第二个加密矩阵中取出新位置上的字母
|
||||
encrypted_char1 = matrix1[new_pos1[0]][new_pos1[1]]
|
||||
encrypted_char2 = matrix2[new_pos2[0]][new_pos2[1]]
|
||||
|
||||
print(f" - 在 M1 中查找位置 {new_pos1} 的字母: {encrypted_char1}")
|
||||
print(f" - 在 M2 中查找位置 {new_pos2} 的字母: {encrypted_char2}")
|
||||
print(f" - 加密结果为: {encrypted_char1 + encrypted_char2}\n")
|
||||
|
||||
# 将加密后的字母添加到结果列表中
|
||||
encrypted_text.append(encrypted_char1 + encrypted_char2)
|
||||
|
||||
# 返回加密结果,每两个字母用空格分隔
|
||||
final_result = " ".join(encrypted_text)
|
||||
print("加密完成!最终加密结果为:", final_result)
|
||||
return final_result
|
||||
|
||||
|
||||
def decode(self, text, str1, str2):
|
||||
"""
|
||||
使用Four-square Cipher算法解密文本。
|
||||
参数:
|
||||
- str1: 第一个密钥字符串,用于构建第一个加密矩阵
|
||||
- str2: 第二个密钥字符串,用于构建第二个加密矩阵
|
||||
- text: 待解密的密文字符串
|
||||
|
||||
返回:
|
||||
- 解密后的字符串
|
||||
"""
|
||||
# 打印解题方案
|
||||
print("解题方案:")
|
||||
print("1. 构建3个矩阵:默认字母表矩阵M_T,加密矩阵M1和M2(由str1和str2生成)。")
|
||||
print("2. 将密文按两个字母一组分组。")
|
||||
print("3. 对每对加密字母进行解密:")
|
||||
print(" - 在M1和M2中找到加密字母的位置,交换列坐标")
|
||||
print(" - 从默认矩阵中获取对应的明文字母。")
|
||||
print("4. 输出解密后的文本。\n")
|
||||
|
||||
# 创建默认字母表矩阵(去除Q)
|
||||
default_matrix = create_cipher_matrix("ABCDEFGHIJKLMNOPRSTUVWXYZ") # delete Q
|
||||
print("Step 1: 创建默认字母表矩阵 M_T (去除Q):")
|
||||
for row in default_matrix:
|
||||
print(" ".join(row))
|
||||
print()
|
||||
|
||||
# 使用str1和str2创建两个加密矩阵
|
||||
matrix1 = create_cipher_matrix(str1)
|
||||
matrix2 = create_cipher_matrix(str2)
|
||||
|
||||
print("Step 2: 使用密钥构建加密矩阵 M1 和 M2")
|
||||
print("M1 矩阵 (根据密钥 str1):")
|
||||
for row in matrix1:
|
||||
print(" ".join(row))
|
||||
print("\nM2 矩阵 (根据密钥 str2):")
|
||||
for row in matrix2:
|
||||
print(" ".join(row))
|
||||
print()
|
||||
|
||||
# 将密文转换为大写并按两个字母一组分组
|
||||
text = ''.join(filter(str.isalpha, text.upper()))
|
||||
pairs = [text[i:i + 2] for i in range(0, len(text), 2)]
|
||||
print("Step 3: 将密文分成两个字母一组:", pairs)
|
||||
print()
|
||||
|
||||
decrypted_text = []
|
||||
|
||||
# 遍历每对字母进行解密
|
||||
for idx, pair in enumerate(pairs):
|
||||
print(f"Step 4.{idx + 1}: 解密字母对 {pair}")
|
||||
|
||||
# 在M1和M2中找到两个加密字母的位置
|
||||
pos1 = find_position(matrix1, pair[0])
|
||||
pos2 = find_position(matrix2, pair[1])
|
||||
|
||||
print(f" - {pair[0]} 在 M1 中的位置: {pos1}")
|
||||
print(f" - {pair[1]} 在 M2 中的位置: {pos2}")
|
||||
|
||||
try:
|
||||
# 交换列坐标得到新位置
|
||||
new_pos1 = (pos1[0], pos2[1])
|
||||
new_pos2 = (pos2[0], pos1[1])
|
||||
except Exception as e:
|
||||
print(e)
|
||||
print(f" - 交换列索引后新位置: {new_pos1} 和 {new_pos2}")
|
||||
|
||||
# 从默认矩阵中取出新位置上的字母
|
||||
decrypted_char1 = default_matrix[new_pos1[0]][new_pos1[1]]
|
||||
decrypted_char2 = default_matrix[new_pos2[0]][new_pos2[1]]
|
||||
|
||||
print(f" - 在 M_T 中查找位置 {new_pos1} 的字母: {decrypted_char1}")
|
||||
print(f" - 在 M_T 中查找位置 {new_pos2} 的字母: {decrypted_char2}")
|
||||
print(f" - 解密结果为: {decrypted_char1 + decrypted_char2}\n")
|
||||
|
||||
# 将解密后的字母添加到结果列表中
|
||||
decrypted_text.append(decrypted_char1 + decrypted_char2)
|
||||
|
||||
# 返回解密结果,去除多余空格
|
||||
final_result = "".join(decrypted_text).strip()
|
||||
print("解密完成!最终解密结果为:", final_result)
|
||||
return final_result
|
||||
|
||||
def get_encode_rule(self):
|
||||
return "解题方案:\n1. 构建3个矩阵:默认字母表矩阵M_T,加密矩阵M1和M2(由str1和str2生成)。\n2. 将明文文本转换为大写字母,仅保留字母字符并分成两个字母一组。\n3. 对每对字母进行加密:\n - 查找每个字母在默认矩阵中的位置,交换其y坐标,\n - 根据新坐标从M1和M2矩阵中取出加密后的字母对。\n4. 输出加密后的文本。"
|
||||
|
||||
def get_decode_rule(self):
|
||||
return "解题方案:\n1. 构建3个矩阵:默认字母表矩阵M_T,加密矩阵M1和M2(由str1和str2生成)。\n2. 将密文按两个字母一组分组。\n3. 对每对加密字母进行解密:\n - 在M1和M2中找到加密字母的位置,交换列坐标\n - 从默认矩阵中获取对应的明文字母。\n4. 输出解密后的文本。"
|
||||
158
internbootcamp/libs/cipher/KorADFGVXCipherEnvironment.py
Executable file
158
internbootcamp/libs/cipher/KorADFGVXCipherEnvironment.py
Executable file
|
|
@ -0,0 +1,158 @@
|
|||
from .BaseCipherEnvironment import BaseCipherEnvironment
|
||||
|
||||
from random import randint
|
||||
|
||||
ALPHABET_CZ = "ABCDEFGHIJKLMNOPQRSTUVXYZ"
|
||||
ALPHABET_EN = "ABCDEFGHIKLMNOPQRSTUVWXYZ"
|
||||
ALPHABET_ALL = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
|
||||
|
||||
class Matrix:
|
||||
def __init__(self, matrixType=""):
|
||||
self.matrix = []
|
||||
self.setType(matrixType)
|
||||
|
||||
def setType(self, matrixType):
|
||||
self.type = matrixType
|
||||
if self.type == "cz":
|
||||
self.length = 5
|
||||
self.alphabet = ALPHABET_CZ
|
||||
elif self.type == "en":
|
||||
self.length = 5
|
||||
self.alphabet = ALPHABET_EN
|
||||
else:
|
||||
self.length = 6
|
||||
self.alphabet = ALPHABET_ALL
|
||||
self.clean()
|
||||
self.fill()
|
||||
|
||||
def fill(self):
|
||||
remains = self.alphabet
|
||||
for i in range(self.length):
|
||||
for j in range(self.length):
|
||||
self.matrix[i][j] = remains[randint(0, len(remains) - 1)]
|
||||
remains = remains.replace(self.matrix[i][j], '')
|
||||
|
||||
def clean(self):
|
||||
self.matrix = [['' for i in range(self.length)] for j in range(self.length)]
|
||||
|
||||
def find(self, letter):
|
||||
for i in range(self.length):
|
||||
for j in range(self.length):
|
||||
if self.matrix[i][j] == letter:
|
||||
return (i, j)
|
||||
|
||||
matrix = Matrix()
|
||||
matrix.matrix = [['R', 'U', 'A', '0', 'Q', 'B'],
|
||||
['D', '2', 'W', 'K', 'S', '1'],
|
||||
['H', '4', '5', 'F', 'T', 'Z'],
|
||||
['Y', 'C', 'G', 'X', '7', 'L'],
|
||||
['9', '8', 'I', '3', 'P', 'N'],
|
||||
['6', 'J', 'V', 'O', 'E', 'M']]
|
||||
|
||||
|
||||
class KorADFGVXCipherEnvironment(BaseCipherEnvironment):
|
||||
def __init__(self, *args, **kwargs):
|
||||
problem_description = ''
|
||||
super().__init__(problem_description, *args, **kwargs)
|
||||
|
||||
@property
|
||||
def cipher_name(self) -> str:
|
||||
return 'Kor_rule19_ADFGVX'
|
||||
|
||||
def encode(self, text, **kwargs):
|
||||
# 将输入转换为大写字母,并移除非字母数字字符
|
||||
text = ''.join([char.upper() for char in text if char.isalnum()])
|
||||
print(f"处理后的输入文本: {text}")
|
||||
|
||||
line = "ADFGVX"
|
||||
encrypted = ""
|
||||
print("\n加密过程:")
|
||||
|
||||
# 第一步:获取每个字符的行列位置并转换
|
||||
print("1. 获取每个字符的行列位置并转换为加密字符:")
|
||||
binary_pairs = []
|
||||
for i in text:
|
||||
row, col = matrix.find(i)
|
||||
row_char = line[row]
|
||||
col_char = line[col]
|
||||
binary_pairs.append((row_char, col_char))
|
||||
print(f"字符 {i} 在矩阵中的位置是 ({row},{col}),转换为加密二元组 ({row_char},{col_char})")
|
||||
|
||||
# 第二步:合并所有行和列
|
||||
print("\n2. 合并所有加密二元组的行和列:")
|
||||
for pair in binary_pairs:
|
||||
encrypted += pair[0]
|
||||
for pair in binary_pairs:
|
||||
encrypted += pair[1]
|
||||
print(f"先读取所有行: {''.join([pair[0] for pair in binary_pairs])}")
|
||||
print(f"再读取所有列: {''.join([pair[1] for pair in binary_pairs])}")
|
||||
print(f"最终密文: {encrypted}")
|
||||
|
||||
return encrypted
|
||||
|
||||
def decode(self, text, **kwargs):
|
||||
line = "ADFGVX"
|
||||
print(f"输入密文: {text}")
|
||||
|
||||
print("\n解密过程:")
|
||||
# 第一步:将密文分成两半
|
||||
half_length = len(text) // 2
|
||||
first_half = text[:half_length]
|
||||
second_half = text[half_length:]
|
||||
print(f"1. 将密文分成两半:")
|
||||
print(f"前半部分: {first_half}")
|
||||
print(f"后半部分: {second_half}")
|
||||
|
||||
# 第二步:配对解密
|
||||
print("\n2. 将前后半部分配对并解密:")
|
||||
decryptedText = ""
|
||||
for i, (first, second) in enumerate(zip(first_half, second_half)):
|
||||
row = line.index(first)
|
||||
col = line.index(second)
|
||||
char = matrix.matrix[row][col]
|
||||
decryptedText += char
|
||||
print(f"配对 ({first},{second}) 对应矩阵位置 ({row},{col}),解密为字符: {char}")
|
||||
|
||||
print(f"\n最终明文: {decryptedText}")
|
||||
return decryptedText
|
||||
|
||||
def get_encode_rule(self, ):
|
||||
return """加密规则:
|
||||
- 输入:
|
||||
- 明文: 不含标点和空格的大写字母字符串
|
||||
- 输出:
|
||||
- 密文: 不含标点和空格的大写字母字符串
|
||||
- 准备:
|
||||
- 6x6矩阵 (矩阵中的行和列从0开始计数)
|
||||
[['R', 'U', 'A', '0', 'Q', 'B'],
|
||||
['D', '2', 'W', 'K', 'S', '1'],
|
||||
['H', '4', '5', 'F', 'T', 'Z'],
|
||||
['Y', 'C', 'G', 'X', '7', 'L'],
|
||||
['9', '8', 'I', '3', 'P', 'N'],
|
||||
['6', 'J', 'V', 'O', 'E', 'M']]
|
||||
- 加密字符集: "ADFGVX"
|
||||
- 加密步骤:
|
||||
- 对明文中的每个字符:
|
||||
- 在6X6矩阵中找到该字符的行数和列数。例如,A的行数为0,列数为2。
|
||||
- 加密字符集中的字符位置标记为0-6。使用加密字符集中对应位置的字符替换行数和列数得到加密二元组。
|
||||
- 例如,A的行数为0对应加密字符集中的A,列数为2对应加密字符集中的F,所以A的加密二元组为(A,F)。
|
||||
- 读取所有加密二元组的行,然后读取所有加密二元组的列得到最终密文。
|
||||
- 例如,加密二元组为(A,F)(X,V),最后读取为AXFV,所以最终密文为AXFV。"""
|
||||
|
||||
def get_decode_rule(self, ):
|
||||
return """解密规则:
|
||||
- 输入:
|
||||
- 密文: 不含标点和空格的大写字母字符串
|
||||
- 输出:
|
||||
- 明文: 不含标点和空格的大写字母字符串
|
||||
- 准备:
|
||||
- 6x6矩阵 (与加密相同)
|
||||
- 加密字符集 (与加密相同)
|
||||
- 解密步骤:
|
||||
- 将密文分成两半
|
||||
- 每次从上半部分和下半部分各取一个字母作为解密二元组:
|
||||
- 加密字符集中的字符位置标记为0-6,使用加密字符集中对应字符的位置解密出解密二元组代表的行数和列数。
|
||||
- 例如,解密二元组为加密二元组(A,F),A的位置为0,F的位置为2,所以行数为0,列数为2,得到(0,2)。
|
||||
- 使用得到的行数和列数在6x6矩阵中找到对应位置的字母作为解密后的字符。
|
||||
- 例如,(0,2)位置的字符为A,所以AF解密后的字符为A。
|
||||
- 连接所有解密后的字符得到最终明文。"""
|
||||
108
internbootcamp/libs/cipher/KorAffineCipherEnvironment.py
Executable file
108
internbootcamp/libs/cipher/KorAffineCipherEnvironment.py
Executable file
|
|
@ -0,0 +1,108 @@
|
|||
from .BaseCipherEnvironment import BaseCipherEnvironment
|
||||
|
||||
class KorAffineCipherEnvironment(BaseCipherEnvironment):
|
||||
def __init__(self, *args, **kwargs):
|
||||
problem_description = ''
|
||||
super().__init__(problem_description=problem_description,*args, **kwargs)
|
||||
|
||||
@property
|
||||
def cipher_name(self) -> str:
|
||||
return "Kor_rule5_AffineCipher"
|
||||
|
||||
def encode(self, text, **kwargs):
|
||||
# 将输入转换为大写字母并移除非字母字符
|
||||
text = ''.join([char.upper() for char in text if char.isalpha()])
|
||||
|
||||
print(f"原始文本: {text}")
|
||||
print("开始加密过程...")
|
||||
print("使用仿射字母表: XMJQUDONPRGTVBWFAKSHZCYEIL")
|
||||
print("参数 A=3, B=5")
|
||||
|
||||
alphabet = "XMJQUDONPRGTVBWFAKSHZCYEIL"
|
||||
A = 3
|
||||
B = 5
|
||||
n = len(alphabet)
|
||||
letter_to_index = {char: idx for idx, char in enumerate(alphabet)}
|
||||
encrypted_message = []
|
||||
|
||||
for char in text:
|
||||
if char in letter_to_index:
|
||||
x = letter_to_index[char]
|
||||
y = (A * x + B) % n
|
||||
print(f"字符 {char} -> 位置 {x} -> 计算(3*{x}+5)%26={y} -> 加密为 {alphabet[y]}")
|
||||
encrypted_message.append(alphabet[y])
|
||||
|
||||
result = ''.join(encrypted_message)
|
||||
print(f"加密完成,结果: {result}")
|
||||
return result
|
||||
|
||||
def decode(self, text, **kwargs):
|
||||
print(f"加密文本: {text}")
|
||||
print("开始解密过程...")
|
||||
print("使用仿射字母表: XMJQUDONPRGTVBWFAKSHZCYEIL")
|
||||
print("参数 A=3, B=5, A的逆元=9")
|
||||
|
||||
alphabet = "XMJQUDONPRGTVBWFAKSHZCYEIL"
|
||||
A = 3
|
||||
B = 5
|
||||
n = len(alphabet)
|
||||
letter_to_index = {char: idx for idx, char in enumerate(alphabet)}
|
||||
A_inv = 9
|
||||
decrypted_message = []
|
||||
|
||||
for char in text:
|
||||
if char in letter_to_index:
|
||||
y = letter_to_index[char]
|
||||
x = A_inv * (y - B) % n
|
||||
print(f"字符 {char} -> 位置 {y} -> 计算9*({y}-5)%26={x} -> 解密为 {alphabet[x]}")
|
||||
decrypted_message.append(alphabet[x])
|
||||
|
||||
result = ''.join(decrypted_message)
|
||||
print(f"解密完成,结果: {result}")
|
||||
return result
|
||||
|
||||
def get_encode_rule(self, ):
|
||||
return """加密规则:
|
||||
- 输入:
|
||||
- 明文: 仅包含大写字母的字符串,不含标点和空格
|
||||
- 输出:
|
||||
- 密文: 大写字母字符串
|
||||
- 准备:
|
||||
- 仿射字母表 = "XMJQUDONPRGTVBWFAKSHZCYEIL"
|
||||
- 将每个字母与其在仿射字母表中的位置关联(从0开始):
|
||||
X->0, M->1, J->2, Q->3, U->4, D->5, O->6, N->7,
|
||||
P->8, R->9, G->10, T->11, V->12, B->13, W->14, F->15,
|
||||
A->16, K->17, S->18, H->19, Z->20, C->21, Y->22, E->23, I->24, L->25
|
||||
- A: 3
|
||||
- B: 5
|
||||
- A_inv: 9
|
||||
- 加密步骤:
|
||||
- 对于每个明文字符p:
|
||||
- 设x为其在仿射字母表中的位置
|
||||
- 应用仿射编码函数计算y:
|
||||
- y = (Ax + B) mod 26
|
||||
- 在仿射字母表中找到位置y对应的字母,形成加密消息"""
|
||||
|
||||
def get_decode_rule(self, ):
|
||||
return """解密规则:
|
||||
- 输入:
|
||||
- 密文: 大写字母字符串
|
||||
- 输出:
|
||||
- 明文: 大写字母字符串
|
||||
- 准备:
|
||||
- 仿射字母表 = "XMJQUDONPRGTVBWFAKSHZCYEIL"
|
||||
- 将每个字母与其在仿射字母表中的位置关联(从0开始):
|
||||
X->0, M->1, J->2, Q->3, U->4, D->5, O->6, N->7,
|
||||
P->8, R->9, G->10, T->11, V->12, B->13, W->14, F->15,
|
||||
A->16, K->17, S->18, H->19, Z->20, C->21, Y->22, E->23, I->24, L->25
|
||||
- A: 3
|
||||
- B: 5
|
||||
- A_inv: 9
|
||||
- 解密步骤:
|
||||
- 对于每个密文字符c:
|
||||
- 设y为其在仿射字母表中的位置
|
||||
- 计算x:
|
||||
- x = A_inv * (y - B) % n
|
||||
- 用仿射字母表中位置x处的字母替换c,形成解密消息"""
|
||||
|
||||
|
||||
146
internbootcamp/libs/cipher/KorAlbertiCipherEnvironment.py
Executable file
146
internbootcamp/libs/cipher/KorAlbertiCipherEnvironment.py
Executable file
|
|
@ -0,0 +1,146 @@
|
|||
from .BaseCipherEnvironment import BaseCipherEnvironment
|
||||
|
||||
class AlbertiCipher:
|
||||
def __init__(self, period, increment):
|
||||
self.outer_disk = "QWERTYUIOPASDFGHJZXCVBNMKL"
|
||||
self.inner_disk = "JKLZXCVBNMASDFGHJQWERTYUIO"
|
||||
self.initial_offset = 0
|
||||
self.period = period
|
||||
self.increment = increment
|
||||
self.reset_disks()
|
||||
|
||||
def reset_disks(self):
|
||||
self.current_inner_disk = self.inner_disk[self.initial_offset:] + self.inner_disk[:self.initial_offset]
|
||||
|
||||
def encrypt_char(self, char):
|
||||
if char in self.outer_disk:
|
||||
index = self.outer_disk.index(char)
|
||||
return self.current_inner_disk[index]
|
||||
else:
|
||||
return char
|
||||
|
||||
def decrypt_char(self, char):
|
||||
if char in self.current_inner_disk:
|
||||
index = self.current_inner_disk.index(char)
|
||||
return self.outer_disk[index]
|
||||
else:
|
||||
return char
|
||||
|
||||
def rotate_disk(self, increment):
|
||||
self.current_inner_disk = self.current_inner_disk[increment:] + self.current_inner_disk[:increment]
|
||||
|
||||
def encrypt(self, plaintext):
|
||||
self.reset_disks()
|
||||
ciphertext = []
|
||||
for i, char in enumerate(plaintext):
|
||||
ciphertext.append(self.encrypt_char(char))
|
||||
if (i + 1) % self.period == 0:
|
||||
self.rotate_disk(self.increment)
|
||||
return ''.join(ciphertext)
|
||||
|
||||
def decrypt(self, ciphertext):
|
||||
self.reset_disks()
|
||||
plaintext = []
|
||||
for i, char in enumerate(ciphertext):
|
||||
plaintext.append(self.decrypt_char(char))
|
||||
if (i + 1) % self.period == 0:
|
||||
self.rotate_disk(self.increment)
|
||||
return ''.join(plaintext)
|
||||
|
||||
|
||||
class KorAlbertiCipherEnvironment(BaseCipherEnvironment):
|
||||
def __init__(self, *args, **kwargs):
|
||||
problem_description = ''
|
||||
super().__init__(problem_description, *args, **kwargs)
|
||||
|
||||
@property
|
||||
def cipher_name(self) -> str:
|
||||
return 'Kor_rule9_AlertiCipher'
|
||||
|
||||
def encode(self,text, period=5, increment=4):
|
||||
# 将输入转换为大写字母,去除标点和空格
|
||||
text = ''.join([char.upper() for char in text if char.isalpha()])
|
||||
print(f"处理后的输入文本: {text}")
|
||||
|
||||
cipher = AlbertiCipher(period, increment)
|
||||
print(f"初始化Alberti密码盘:")
|
||||
print(f"外圈: {cipher.outer_disk}")
|
||||
print(f"内圈: {cipher.inner_disk}")
|
||||
print(f"周期: {period} (每处理{period}个字符后旋转内圈)")
|
||||
print(f"增量: {increment} (每次旋转{increment}个位置)")
|
||||
|
||||
encoded = cipher.encrypt(text)
|
||||
print("\n加密过程:")
|
||||
for i, (p, c) in enumerate(zip(text, encoded)):
|
||||
print(f"字符 {p} 在外圈位置 {cipher.outer_disk.index(p)} 对应内圈字符 {c}")
|
||||
if (i + 1) % period == 0:
|
||||
print(f"已处理{period}个字符,内圈向右旋转{increment}个位置")
|
||||
|
||||
print(f"\n最终加密结果: {encoded}")
|
||||
return encoded
|
||||
|
||||
def decode(self, text, period=5, increment=4):
|
||||
cipher = AlbertiCipher(period, increment)
|
||||
print(f"初始化Alberti密码盘:")
|
||||
print(f"外圈: {cipher.outer_disk}")
|
||||
print(f"内圈: {cipher.inner_disk}")
|
||||
print(f"周期: {period} (每处理{period}个字符后旋转内圈)")
|
||||
print(f"增量: {increment} (每次旋转{increment}个位置)")
|
||||
|
||||
decoded = cipher.decrypt(text)
|
||||
print("\n解密过程:")
|
||||
for i, (c, p) in enumerate(zip(text, decoded)):
|
||||
print(f"字符 {c} 在内圈位置 {cipher.current_inner_disk.index(c)} 对应外圈字符 {p}")
|
||||
if (i + 1) % period == 0:
|
||||
print(f"已处理{period}个字符,内圈向右旋转{increment}个位置")
|
||||
|
||||
print(f"\n最终解密结果: {decoded}")
|
||||
return decoded
|
||||
|
||||
def get_encode_rule(self):
|
||||
encode_rule = """
|
||||
加密规则:
|
||||
|
||||
输入:
|
||||
- 明文: 大写字母字符串,不含标点和空格
|
||||
- period: 定义内圈多久旋转一次。周期性表示在加密过程中每处理指定数量的字符后,内圈将根据增量值旋转一次
|
||||
- increment: 定义内圈每次旋转的字符数。在每个周期结束时,内圈将根据增量值向右旋转相应数量的字符
|
||||
|
||||
输出:
|
||||
- 密文: 大写字母字符串
|
||||
|
||||
准备:
|
||||
- outer_disk = "QWERTYUIOPASDFGHJZXCVBNMKL"
|
||||
- inner_disk = "JKLZXCVBNMASDFGHJQWERTYUIO"
|
||||
|
||||
加密步骤:
|
||||
- 对明文中的每个字符p:
|
||||
- 在外圈找到该字符
|
||||
- 用内圈对应位置的字符替换它
|
||||
- 每加密period个字符后,将内圈向右旋转increment个字符。例如,将'ZXCVBNMASDFGHJKLQWERTYUIOP'旋转4位得到'BNMASDFGHJKLQWERTYUIOPZXCV'
|
||||
"""
|
||||
return encode_rule
|
||||
|
||||
def get_decode_rule(self):
|
||||
decode_rule = """
|
||||
解密规则:
|
||||
|
||||
输入:
|
||||
- 密文: 大写字母字符串
|
||||
- period (与加密相同)
|
||||
- increment (与加密相同)
|
||||
|
||||
输出:
|
||||
- 明文: 大写字母字符串
|
||||
|
||||
准备:
|
||||
- outer_disk = "QWERTYUIOPASDFGHJZXCVBNMKL"
|
||||
- inner_disk = "JKLZXCVBNMASDFGHJQWERTYUIO"
|
||||
|
||||
解密步骤 (与加密步骤完全相反):
|
||||
- 对密文中的每个字符c:
|
||||
- 在内圈找到该字符
|
||||
- 用外圈对应位置的字符替换它
|
||||
- 每解密period个字符后,将内圈向右旋转increment个字符。例如,将'ZXCVBNMASDFGHJKLQWERTYUIOP'旋转4位得到'BNMASDFGHJKLQWERTYUIOPZXCV'
|
||||
"""
|
||||
return decode_rule
|
||||
203
internbootcamp/libs/cipher/KorBifidCipherEnvironment.py
Executable file
203
internbootcamp/libs/cipher/KorBifidCipherEnvironment.py
Executable file
|
|
@ -0,0 +1,203 @@
|
|||
from .BaseCipherEnvironment import BaseCipherEnvironment
|
||||
|
||||
def checkRepeat(secretKey):
|
||||
nonRepeated = ""
|
||||
for char in secretKey:
|
||||
if nonRepeated == "":
|
||||
nonRepeated += char
|
||||
continue
|
||||
if char in nonRepeated:
|
||||
continue
|
||||
else:
|
||||
nonRepeated += char
|
||||
return(nonRepeated)
|
||||
|
||||
def fillMatrix(nonRepeated):
|
||||
nonRepeated.replace("J", "I")
|
||||
alphabet = "ABCDEFGHIKLMNOPQRSTUVWXYZ"
|
||||
row = 0
|
||||
col = 0
|
||||
matrix = [[0 for i in range(5)] for j in range(5)]
|
||||
for letter in nonRepeated:
|
||||
if col == 5:
|
||||
row += 1
|
||||
col = 0
|
||||
matrix[row][col] = letter
|
||||
col += 1
|
||||
for letter in alphabet:
|
||||
if col == 5:
|
||||
row += 1
|
||||
col = 0
|
||||
if letter in nonRepeated:
|
||||
continue
|
||||
else:
|
||||
matrix[row][col] = letter
|
||||
col += 1
|
||||
return(matrix)
|
||||
|
||||
def getCoords(message, matrix):
|
||||
coordsRow = list()
|
||||
coordsCol = list()
|
||||
for letters in message:
|
||||
for i in range(5):
|
||||
for j in range(5):
|
||||
if matrix[i][j] == letters:
|
||||
coordsRow.append(i)
|
||||
coordsCol.append(j)
|
||||
continue
|
||||
finalCoords = list()
|
||||
for letters in coordsRow:
|
||||
finalCoords.append(letters)
|
||||
for letters in coordsCol:
|
||||
finalCoords.append(letters)
|
||||
return(finalCoords)
|
||||
|
||||
def getNewMessage(finalCoords, matrix):
|
||||
newMessage = ""
|
||||
length = len(finalCoords)
|
||||
finalCoordsCopy = finalCoords.copy()
|
||||
for i in range(int(length / 2) + 1):
|
||||
x = finalCoordsCopy.pop(0)
|
||||
y = finalCoordsCopy.pop(0)
|
||||
newMessage += matrix[x][y]
|
||||
if not finalCoordsCopy: break
|
||||
return(newMessage)
|
||||
|
||||
def getOldCoords(coords):
|
||||
oldCoords = ''.join(str(coords))
|
||||
firstHalf = oldCoords[:len(oldCoords)//2]
|
||||
secondHalf = oldCoords[len(oldCoords)//2:]
|
||||
fH = "".join(c for c in firstHalf if c.isdecimal())
|
||||
sH = "".join(c for c in secondHalf if c.isdecimal())
|
||||
|
||||
firstHalf = list(fH)
|
||||
secondHalf = list(sH)
|
||||
|
||||
stepOneCoords = list()
|
||||
for coord in fH:
|
||||
x = firstHalf.pop(0)
|
||||
y = secondHalf.pop(0)
|
||||
stepOneCoords.append(x)
|
||||
stepOneCoords.append(y)
|
||||
|
||||
stepTwoCoords = ''.join(str(stepOneCoords))
|
||||
firstHalf = stepTwoCoords[:len(stepTwoCoords)//2]
|
||||
secondHalf = stepTwoCoords[len(stepTwoCoords)//2:]
|
||||
|
||||
fH = "".join(c for c in firstHalf if c.isdecimal())
|
||||
sH = "".join(c for c in secondHalf if c.isdecimal())
|
||||
|
||||
firstHalf = list(fH)
|
||||
secondHalf = list(sH)
|
||||
|
||||
fullOldCoords = list()
|
||||
for coord in fH:
|
||||
x = firstHalf.pop(0)
|
||||
y = secondHalf.pop(0)
|
||||
fullOldCoords.append(x)
|
||||
fullOldCoords.append(y)
|
||||
|
||||
return fullOldCoords
|
||||
|
||||
def getOldMessage(fullOldCoords, matrix):
|
||||
oldMessage = ""
|
||||
length = len(fullOldCoords)
|
||||
fullOldCoordsCopy = fullOldCoords.copy()
|
||||
|
||||
for i in range(int(length / 2) + 1):
|
||||
x = int(fullOldCoordsCopy.pop(0))
|
||||
y = int(fullOldCoordsCopy.pop(0))
|
||||
oldMessage += matrix[x][y]
|
||||
if not fullOldCoordsCopy: break
|
||||
return(oldMessage)
|
||||
|
||||
|
||||
class KorBifidCipherEnvironment(BaseCipherEnvironment):
|
||||
def __init__(self, *args, **kwargs):
|
||||
problem_description = ''
|
||||
super().__init__(problem_description, *args, **kwargs)
|
||||
|
||||
@property
|
||||
def cipher_name(self) -> str:
|
||||
return 'Kor_rule13_BifidCipher'
|
||||
|
||||
|
||||
def encode(self, text, **kwargs):
|
||||
secretKey = "UBILANT"
|
||||
print("加密步骤:")
|
||||
# 1. 处理输入文本
|
||||
text = ''.join([c.upper() for c in text if c.isalpha()])
|
||||
text = text.replace('J','I')
|
||||
print(f"1. 去除标点和空格,将J替换为I后的文本: {text}")
|
||||
|
||||
# 2. 生成5x5矩阵
|
||||
matrix = fillMatrix(checkRepeat(secretKey))
|
||||
print("2. 生成的5x5矩阵:")
|
||||
for row in matrix:
|
||||
print(row)
|
||||
|
||||
# 3. 获取坐标
|
||||
coords = getCoords(text, matrix)
|
||||
print(f"3. 获取每个字母的行列坐标: {coords}")
|
||||
|
||||
# 4. 重排坐标并加密
|
||||
ciphered = getNewMessage(coords, matrix)
|
||||
print(f"4. 最终加密结果: {ciphered}")
|
||||
|
||||
return ciphered
|
||||
|
||||
def decode(self, text, **kwargs):
|
||||
secretKey = "UBILANT"
|
||||
print("解密步骤:")
|
||||
# 1. 生成5x5矩阵
|
||||
matrix = fillMatrix(checkRepeat(secretKey))
|
||||
print("1. 生成的5x5矩阵:")
|
||||
for row in matrix:
|
||||
print(row)
|
||||
|
||||
# 2. 获取密文坐标
|
||||
coords = getCoords(text, matrix)
|
||||
print(f"2. 获取密文字母的坐标: {coords}")
|
||||
|
||||
# 3. 还原原始坐标
|
||||
oldCoords = getOldCoords(coords)
|
||||
print(f"3. 还原原始坐标: {oldCoords}")
|
||||
|
||||
# 4. 解密
|
||||
plaintext = getOldMessage(oldCoords, matrix)
|
||||
print(f"4. 最终解密结果: {plaintext}")
|
||||
|
||||
return plaintext
|
||||
|
||||
def get_encode_rule(self, ):
|
||||
return """加密规则:
|
||||
- 输入:
|
||||
- 明文: 大写字母字符串,不含标点和空格
|
||||
- 输出:
|
||||
- 密文: 大写字母字符串
|
||||
- 准备:
|
||||
- 5x5网格(不含字母J,行列坐标在0到4之间):
|
||||
- U B I L A
|
||||
N T C D E
|
||||
F G H K M
|
||||
O P Q R S
|
||||
V W X Y Z
|
||||
- 加密步骤:
|
||||
- 去除明文中的标点、空格和字母J
|
||||
- 对明文中的每个字母,找到其在网格中对应的行列坐标(0-4)。例如A是(0,4)
|
||||
- 将所有行列坐标重排,先读所有行坐标,再读所有列坐标形成新的坐标序列。例如原来是(0,4)(1,2),现在读作0142
|
||||
- 每次从新坐标序列中取出两个数作为新的行列坐标,在网格中找到对应字母形成密文。例如对于0142,密文对应(0,1)是B,(4,2)是X。最终密文是BX"""
|
||||
|
||||
def get_decode_rule(self, ):
|
||||
return """解密规则:
|
||||
- 输入:
|
||||
- 密文: 大写字母字符串,不含标点和空格
|
||||
- 输出:
|
||||
- 明文: 大写字母字符串,不含标点和空格
|
||||
- 准备:
|
||||
- 5x5网格(与加密相同)
|
||||
- 解密步骤(与加密步骤完全相反):
|
||||
- 对密文中的每个字母,找到其在网格中对应的行列坐标(0-4)得到坐标序列
|
||||
- 将坐标序列分成两半,前半部分为所有原始行坐标,后半部分为所有原始列坐标,从原始行坐标读一个,从原始列坐标读一个,根据原始行列坐标在网格中找到对应字母形成明文
|
||||
- 例如[0,1,4,2],前半部分作为行坐标:[0,1],后半部分作为列坐标:[4,2]
|
||||
- 交替读取行坐标和列坐标。得到(0,4),(1,2),分别在网格中找到对应字母为AC"""
|
||||
127
internbootcamp/libs/cipher/KorCollonCipherEnvironment.py
Executable file
127
internbootcamp/libs/cipher/KorCollonCipherEnvironment.py
Executable file
|
|
@ -0,0 +1,127 @@
|
|||
from .BaseCipherEnvironment import BaseCipherEnvironment
|
||||
|
||||
class KorCollonCipherEnvironment(BaseCipherEnvironment):
|
||||
def __init__(self, *args, **kwargs):
|
||||
problem_description = ''
|
||||
super().__init__(problem_description, *args, **kwargs)
|
||||
|
||||
@property
|
||||
def cipher_name(self) -> str:
|
||||
return 'Kor_rule15_CollonCipher'
|
||||
|
||||
def encode(self, text, **kwargs):
|
||||
grid = [['M', 'Z', 'S', 'D', 'P'],
|
||||
['K', 'N', 'F', 'L', 'Q'],
|
||||
['G', 'A', 'O', 'X', 'U'],
|
||||
['W', 'R', 'Y', 'V', 'C'],
|
||||
['B', 'T', 'E', 'H', 'I']]
|
||||
|
||||
print("开始加密过程...")
|
||||
print(f"原始文本: {text}")
|
||||
|
||||
# 预处理文本
|
||||
text = ''.join([char.upper() for char in text if char.isalpha()])
|
||||
text = text.replace('J', '')
|
||||
print(f"预处理后的文本(移除空格标点,转大写,移除J): {text}")
|
||||
|
||||
encrypted_message = []
|
||||
print("\n逐字符加密:")
|
||||
for char in text:
|
||||
found = False
|
||||
for r in range(len(grid)):
|
||||
for c in range(len(grid[0])):
|
||||
if grid[r][c] == char:
|
||||
row_header = grid[r][0]
|
||||
column_footer = grid[len(grid)-1][c]
|
||||
encrypted_pair = row_header + column_footer
|
||||
encrypted_message.append(encrypted_pair)
|
||||
print(f"字符 {char} 位于第{r+1}行第{c+1}列")
|
||||
print(f"-> 行首字符为{row_header}, 列尾字符为{column_footer}")
|
||||
print(f"-> 加密为: {encrypted_pair}")
|
||||
found = True
|
||||
break
|
||||
if found:
|
||||
break
|
||||
|
||||
result = ''.join(encrypted_message)
|
||||
print(f"\n最终加密结果: {result}")
|
||||
return result
|
||||
|
||||
def decode(self, text, **kwargs):
|
||||
grid = [['M', 'Z', 'S', 'D', 'P'],
|
||||
['K', 'N', 'F', 'L', 'Q'],
|
||||
['G', 'A', 'O', 'X', 'U'],
|
||||
['W', 'R', 'Y', 'V', 'C'],
|
||||
['B', 'T', 'E', 'H', 'I']]
|
||||
|
||||
print("开始解密过程...")
|
||||
print(f"加密文本: {text}")
|
||||
|
||||
decrypted_message = []
|
||||
print("\n每次解密两个字符:")
|
||||
for i in range(0, len(text), 2):
|
||||
bigram = text[i:i+2]
|
||||
if bigram == '':
|
||||
break
|
||||
|
||||
row_header = bigram[0]
|
||||
column_footer = bigram[1]
|
||||
print(f"\n处理字符对: {bigram}")
|
||||
print(f"行首字符: {row_header}, 列尾字符: {column_footer}")
|
||||
|
||||
found = False
|
||||
for r in range(len(grid)):
|
||||
if grid[r][0] == row_header:
|
||||
for c in range(len(grid[0])):
|
||||
if grid[len(grid)-1][c] == column_footer:
|
||||
decrypted_char = grid[r][c]
|
||||
decrypted_message.append(decrypted_char)
|
||||
print(f"-> 在第{r+1}行第{c+1}列找到原文字符: {decrypted_char}")
|
||||
found = True
|
||||
break
|
||||
if found:
|
||||
break
|
||||
|
||||
result = ''.join(decrypted_message)
|
||||
print(f"\n最终解密结果: {result}")
|
||||
return result
|
||||
|
||||
def get_encode_rule(self, ):
|
||||
return """加密规则:
|
||||
- 输入:
|
||||
- 明文: 不含标点和空格的大写字母字符串
|
||||
- 输出:
|
||||
- 密文: 不含标点和空格的大写字母字符串
|
||||
- 准备:
|
||||
- 5x5网格(所有行和列号从0开始计数):
|
||||
- M Z S D P
|
||||
K N F L Q
|
||||
G A O X U
|
||||
W R Y V C
|
||||
B T E H I
|
||||
- 位于所有行第一个字母的MKGWB是行首字母
|
||||
- 位于所有列最后一个字母的PQUCL是列尾字母
|
||||
- 加密步骤:
|
||||
- 移除明文中的空格、标点和字母J,并将所有字母转换为大写
|
||||
- 对明文中的每个字母p:
|
||||
- 在网格中找到字母p的位置,然后找到相应的行首和列尾字符
|
||||
- 将行首和列尾字符连接成二元组作为该字母p的加密消息
|
||||
- 例如,如果字母p是H,它在第4行,行首字符是B;它在第3列,列尾字符是H,所以加密消息是BH
|
||||
|
||||
连接所有加密消息作为最终密文输出"""
|
||||
|
||||
def get_decode_rule(self, ):
|
||||
return """解密规则:
|
||||
- 输入:
|
||||
- 密文: 不含标点和空格的大写字母字符串
|
||||
- 输出:
|
||||
- 明文: 不含标点和空格的大写字母字符串
|
||||
- 准备:
|
||||
- 5x5网格(与加密相同)
|
||||
- 解密步骤(与加密步骤完全相反):
|
||||
- 每次从密文中取两个字母c1,c2
|
||||
- 字母c1标识解密字母p在网格中的行位置,找到c1作为行首的行
|
||||
- 字母c2标识解密字母p在网格中的列位置,找到c2在列底的列
|
||||
- 在网格中找到这个行列位置的字母,即为c1,c2的解密消息p
|
||||
- 例如,如果c1,c2=BH,B是行首的行是第4行,H是行底的行是第2列,(4,2)处的字母是H,所以BH解密为H
|
||||
- 两个两个地解密密文中的字母,并将解密消息连接起来作为最终明文输出"""
|
||||
163
internbootcamp/libs/cipher/KorDigrafidCipherEnviroment.py
Executable file
163
internbootcamp/libs/cipher/KorDigrafidCipherEnviroment.py
Executable file
|
|
@ -0,0 +1,163 @@
|
|||
from .BaseCipherEnvironment import BaseCipherEnvironment
|
||||
|
||||
import numpy as np
|
||||
|
||||
grid1 = np.array([
|
||||
["Q", "W", "E", "R", "T", "Y", "U", "I", "O"],
|
||||
["P", "A", "S", "D", "F", "G", "H", "J", "K"],
|
||||
["L", "Z", "X", "C", "V", "B", "N", "M", "#"]
|
||||
])
|
||||
|
||||
grid2 = np.array([
|
||||
["Q", "W", "E"],
|
||||
["R", "T", "Y"],
|
||||
["U", "I", "O"],
|
||||
["P", "A", "S"],
|
||||
["D", "F", "G"],
|
||||
["H", "J", "K"],
|
||||
["L", "Z", "X"],
|
||||
["C", "V", "B"],
|
||||
["N", "M", "#"]
|
||||
])
|
||||
|
||||
grid3 = np.array([
|
||||
[1, 2, 3],
|
||||
[4, 5, 6],
|
||||
[7, 8, 9]
|
||||
])
|
||||
|
||||
def find_position(grid, char):
|
||||
for i in range(grid.shape[0]):
|
||||
for j in range(grid.shape[1]):
|
||||
if grid[i, j] == char:
|
||||
return (i, j)
|
||||
return None
|
||||
|
||||
def encrypt_pair(l1, l2):
|
||||
print(f"处理字符对 {l1}{l2}:")
|
||||
l1_row, l1_col = find_position(grid1, l1)
|
||||
print(f"- 在grid1中找到{l1}的位置: 行={l1_row}, 列={l1_col}")
|
||||
l2_row, l2_col = find_position(grid2, l2)
|
||||
print(f"- 在grid2中找到{l2}的位置: 行={l2_row}, 列={l2_col}")
|
||||
num3 = grid3[l1_row, l2_col]
|
||||
print(f"- 在grid3中找到对应数字: {num3} (使用grid1的行{l1_row}和grid2的列{l2_col})")
|
||||
print(f"- 生成三元组: ({l1_col}, {num3}, {l2_row})")
|
||||
return l1_col, num3, l2_row
|
||||
|
||||
def decrypt_triple(x, y, z):
|
||||
print(f"\n解密三元组 ({x}, {y}, {z}):")
|
||||
l1_col = x
|
||||
l2_row = z
|
||||
l1_row, l2_col = find_position(grid3, y)
|
||||
print(f"- 在grid3中找到{y}的位置: 行={l1_row}, 列={l2_col}")
|
||||
l1 = grid1[l1_row, l1_col]
|
||||
print(f"- 在grid1中找到字符: {l1} (使用行={l1_row}, 列={l1_col})")
|
||||
l2 = grid2[l2_row, l2_col]
|
||||
print(f"- 在grid2中找到字符: {l2} (使用行={l2_row}, 列={l2_col})")
|
||||
print(f"- 解密结果: {l1}{l2}")
|
||||
return l1, l2
|
||||
|
||||
|
||||
class KorDigrafidCipherEnviroment(BaseCipherEnvironment):
|
||||
def __init__(self, *args, **kwargs):
|
||||
problem_description = ''
|
||||
super().__init__(problem_description, *args, **kwargs)
|
||||
|
||||
@property
|
||||
def cipher_name(self) -> str:
|
||||
return 'Kor_rule14_DigrafidCipher'
|
||||
|
||||
def encode(self, text, **kwargs):
|
||||
print("\n开始加密过程:")
|
||||
print(f"原始文本: {text}")
|
||||
# 移除空格和标点,转换为大写
|
||||
message = ''.join(char.upper() for char in text if char.isalpha())
|
||||
print(f"预处理后的文本: {message}")
|
||||
|
||||
# 补充#使长度为6的倍数
|
||||
while len(message) % 6 != 0:
|
||||
message += "#"
|
||||
print(f"补充#后的文本: {message}")
|
||||
|
||||
# 分割成二元组
|
||||
bigrams = [message[i:i+2] for i in range(0, len(message), 2)]
|
||||
print(f"分割成二元组: {bigrams}")
|
||||
|
||||
# 加密每个二元组
|
||||
triples = [encrypt_pair(l1, l2) for l1, l2 in bigrams]
|
||||
encrypted_pairs = ["".join(map(str, triple)) for triple in triples]
|
||||
encrypted_message = "".join(encrypted_pairs)
|
||||
print(f"\n最终加密结果: {encrypted_message}")
|
||||
return encrypted_message
|
||||
|
||||
def decode(self, text, **kwargs):
|
||||
print("\n开始解密过程:")
|
||||
print(f"加密文本: {text}")
|
||||
|
||||
# 分割成三元组
|
||||
original_triples = [text[i:i+3] for i in range(0, len(text), 3)]
|
||||
print(f"分割成三元组: {original_triples}")
|
||||
original_triples = [[int(item) for item in row] for row in original_triples]
|
||||
|
||||
# 解密每个三元组
|
||||
decrypted_pairs = [decrypt_triple(*triple) for triple in original_triples]
|
||||
decrypted_message = "".join(sum(decrypted_pairs, ()))
|
||||
decrypted_message = decrypted_message.replace("#", "")
|
||||
print(f"\n最终解密结果: {decrypted_message}")
|
||||
return decrypted_message
|
||||
|
||||
def get_encode_rule(self, ):
|
||||
return """加密规则:
|
||||
- 输入:
|
||||
- 明文: 大写字母字符串,不含标点和空格
|
||||
- 输出:
|
||||
- 密文: 数字字符串,不含标点和空格
|
||||
- 准备:
|
||||
- 3个网格(所有行列号从0开始计数):
|
||||
- 网格1 (3x9):
|
||||
Q W E R T Y U I O
|
||||
P A S D F G H J K
|
||||
L Z X C V B N M #
|
||||
- 网格2 (9x3):
|
||||
Q W E
|
||||
R T Y
|
||||
U I O
|
||||
P A S
|
||||
D F G
|
||||
H J K
|
||||
L Z X
|
||||
C V B
|
||||
N M #
|
||||
- 网格3 (3x3):
|
||||
1 2 3
|
||||
4 5 6
|
||||
7 8 9
|
||||
- 加密步骤:
|
||||
- 移除所有空格和标点,将文本转换为大写字母
|
||||
- 将明文切分为6个字符一组,如果最后一组不足6个字符,用#填充
|
||||
- 将每组6个字符分成3个二元组
|
||||
- 对每个二元组(L1, L2)执行以下操作:
|
||||
- 确定L1在网格1中的行列号(l1_row, l1_col)
|
||||
- 确定L2在网格2中的行列号(l2_row, l2_col)
|
||||
- 在网格3中用l1_row和l2_col找到对应数字num3
|
||||
- 输出三元组(l1_col, num3, l2_row)
|
||||
- 将所有三元组连接成一个数字串作为加密信息"""
|
||||
|
||||
def get_decode_rule(self, ):
|
||||
return """解密规则:
|
||||
- 输入:
|
||||
- 密文: 数字字符串,不含标点和空格
|
||||
- 输出:
|
||||
- 明文: 大写字母字符串,不含标点和空格
|
||||
- 准备:
|
||||
- 3个网格(与加密相同)
|
||||
- 解密步骤:
|
||||
- 将密文分成三个数字一组
|
||||
- 对每个三元组(x, y, z)执行以下操作:
|
||||
- 在网格3中找到y的行号作为L1_row
|
||||
- 在网格3中找到y的列号作为L2_col
|
||||
- L1_col等于x,L2_row等于z
|
||||
- 根据确定的(L1_row,L1_col)在网格1中找到对应字母p1
|
||||
- 根据确定的(L2_row,L2_col)在网格2中找到对应字母p2
|
||||
- p1p2为该三元组解密后的消息
|
||||
- 将所有解密后的消息连接起来,移除末尾的#(这些字符是为使消息长度为6的倍数而添加的填充字符),形成解密后的明文"""
|
||||
132
internbootcamp/libs/cipher/KorECCCipherEnvironment.py
Executable file
132
internbootcamp/libs/cipher/KorECCCipherEnvironment.py
Executable file
|
|
@ -0,0 +1,132 @@
|
|||
from .BaseCipherEnvironment import BaseCipherEnvironment
|
||||
|
||||
def get_inverse(mu, p):
|
||||
for i in range(1, p):
|
||||
if (i*mu)%p == 1:
|
||||
return i
|
||||
return -1
|
||||
|
||||
def get_gcd(zi, mu):
|
||||
if mu:
|
||||
return get_gcd(mu, zi%mu)
|
||||
else:
|
||||
return zi
|
||||
|
||||
def get_np(x1, y1, x2, y2, a, p):
|
||||
flag = 1
|
||||
if x1 == x2 and y1 == y2:
|
||||
zi = 3 * (x1 ** 2) + a
|
||||
mu = 2 * y1
|
||||
else:
|
||||
zi = y2 - y1
|
||||
mu = x2 - x1
|
||||
if zi* mu < 0:
|
||||
flag = 0
|
||||
zi = abs(zi)
|
||||
mu = abs(mu)
|
||||
gcd_value = get_gcd(zi, mu)
|
||||
zi = zi // gcd_value
|
||||
mu = mu // gcd_value
|
||||
inverse_value = get_inverse(mu, p)
|
||||
k = (zi * inverse_value)
|
||||
if flag == 0:
|
||||
k = -k
|
||||
k = k % p
|
||||
x3 = (k ** 2 - x1 - x2) % p
|
||||
y3 = (k * (x1 - x3) - y1) % p
|
||||
return x3,y3
|
||||
|
||||
def get_rank(x0, y0, a, b, p):
|
||||
x1 = x0
|
||||
y1 = (-1*y0)%p
|
||||
tempX = x0
|
||||
tempY = y0
|
||||
n = 1
|
||||
while True:
|
||||
n += 1
|
||||
p_x,p_y = get_np(tempX, tempY, x0, y0, a, p)
|
||||
if p_x == x1 and p_y == y1:
|
||||
return n+1
|
||||
tempX = p_x
|
||||
tempY = p_y
|
||||
|
||||
|
||||
class KorECCCipherEnvironment(BaseCipherEnvironment):
|
||||
def __init__(self, *args, **kwargs):
|
||||
problem_description = ''
|
||||
super().__init__(problem_description, *args, **kwargs)
|
||||
|
||||
@property
|
||||
def cipher_name(self) -> str:
|
||||
return 'Kor_rule24_ECCCipher'
|
||||
|
||||
def encode(self, text, **kwargs):
|
||||
print("开始加密过程...")
|
||||
# 将输入转换为大写字母,去除标点和空格
|
||||
text = ''.join([char.upper() for char in text if char.isalpha()])
|
||||
print(f"处理后的输入文本: {text}")
|
||||
|
||||
k_q_x = 12
|
||||
print(f"使用预设的k_q_x值: {k_q_x}")
|
||||
|
||||
cipher = []
|
||||
for char in text:
|
||||
print(f"\n处理字符: {char}")
|
||||
ascii_value = ord(char)
|
||||
print(f"对应的ASCII值: {ascii_value}")
|
||||
encrypted_value = ascii_value * k_q_x
|
||||
print(f"加密后的值: {encrypted_value}")
|
||||
cipher.append(str(encrypted_value))
|
||||
|
||||
result = ','.join(cipher)
|
||||
print(f"\n最终加密结果: {result}")
|
||||
return result
|
||||
|
||||
def decode(self, text, **kwargs):
|
||||
print("开始解密过程...")
|
||||
print(f"收到的加密文本: {text}")
|
||||
|
||||
k_q_x = 12
|
||||
print(f"使用预设的k_q_x值: {k_q_x}")
|
||||
|
||||
numbers = text.split(',')
|
||||
plain_text = ""
|
||||
|
||||
for num in numbers:
|
||||
print(f"\n处理数字: {num}")
|
||||
decrypted_value = int(num) // k_q_x
|
||||
print(f"除以k_q_x后的值: {decrypted_value}")
|
||||
char = chr(decrypted_value)
|
||||
print(f"对应的字符: {char}")
|
||||
plain_text += char
|
||||
|
||||
print(f"\n最终解密结果: {plain_text}")
|
||||
return plain_text
|
||||
|
||||
def get_encode_rule(self):
|
||||
return """加密规则:
|
||||
- 输入:
|
||||
- 明文: 不含标点和空格的大写字母字符串
|
||||
- 输出:
|
||||
- 密文: 由逗号分隔的数字序列,例如"y1,y2,..."
|
||||
- 准备:
|
||||
- k_q_x值: 12
|
||||
- 加密步骤:
|
||||
- 对明文中的每个字母p:
|
||||
- 获取字母p对应的ASCII码值x
|
||||
- 计算x * k_q_x作为该字母对应的密文数字y
|
||||
- 最后将所有y值用逗号连接得到最终密文"""
|
||||
|
||||
def get_decode_rule(self):
|
||||
return """解密规则:
|
||||
- 输入:
|
||||
- 密文: 由逗号分隔的数字序列,例如"y1,y2,..."
|
||||
- 输出:
|
||||
- 明文: 不含标点和空格的大写字母字符串
|
||||
- 准备:
|
||||
- k_q_x值: 12
|
||||
- 解密步骤:
|
||||
- 对密文中的每个数字c:
|
||||
- 计算z = c // k_q_x,其中//表示整数除法运算,返回商的整数部分
|
||||
- 根据z对应的ASCII码值找到对应的字母作为明文字母p
|
||||
- 最后将所有p连接得到最终明文"""
|
||||
204
internbootcamp/libs/cipher/KorFourSquareCipherEnvironment.py
Executable file
204
internbootcamp/libs/cipher/KorFourSquareCipherEnvironment.py
Executable file
|
|
@ -0,0 +1,204 @@
|
|||
from .BaseCipherEnvironment import BaseCipherEnvironment
|
||||
|
||||
import re
|
||||
|
||||
def generate_table(key = ''):
|
||||
alphabet = 'ABCDEFGHIJKLMNOPRSTUVWXYZ'
|
||||
table = [[0] * 5 for row in range(5)]
|
||||
|
||||
key = re.sub(r'[\W]', '', key).upper()
|
||||
for row in range(5):
|
||||
for col in range(5):
|
||||
if len(key) > 0:
|
||||
table[row][col] = key[0]
|
||||
alphabet = alphabet.replace(key[0], '')
|
||||
key = key.replace(key[0], '')
|
||||
else:
|
||||
table[row][col] = alphabet[0]
|
||||
alphabet = alphabet[1:]
|
||||
return table
|
||||
|
||||
def position(table, ch):
|
||||
for row in range(5):
|
||||
for col in range(5):
|
||||
if table[row][col] == ch:
|
||||
return (row, col)
|
||||
return (None, None)
|
||||
|
||||
|
||||
class KorFourSquareCipherEnvironment(BaseCipherEnvironment):
|
||||
def __init__(self, *args, **kwargs):
|
||||
problem_description = ''
|
||||
super().__init__(problem_description, *args, **kwargs)
|
||||
|
||||
@property
|
||||
def cipher_name(self) -> str:
|
||||
return 'Kor_rule11_FourSquareCipher'
|
||||
|
||||
|
||||
def encode(self, text, **kwargs):
|
||||
print("开始加密过程...")
|
||||
print(f"原始文本: {text}")
|
||||
|
||||
# 清理文本
|
||||
plaintext = ''.join(char.upper() for char in text if char.isalpha())
|
||||
plaintext = plaintext.replace('Q', '')
|
||||
print(f"清理后的文本(移除非字母字符并转大写,移除Q): {plaintext}")
|
||||
|
||||
# 如果长度为奇数,添加X
|
||||
if len(plaintext) % 2 != 0:
|
||||
plaintext += 'X'
|
||||
print(f"文本长度为奇数,添加X: {plaintext}")
|
||||
|
||||
# 准备密钥表格
|
||||
key = ['ECHO', 'VORTEX']
|
||||
table = [['K', 'L', 'M', 'N', 'O'],
|
||||
['P', 'R', 'S', 'T', 'U'],
|
||||
['V', 'W', 'X', 'Y', 'Z'],
|
||||
['A', 'B', 'C', 'D', 'E'],
|
||||
['F', 'G', 'H', 'I', 'J']]
|
||||
topRight = generate_table(key[0])
|
||||
bottomLeft = generate_table(key[1])
|
||||
|
||||
print("\n开始逐对字母加密:")
|
||||
ciphertext = ''
|
||||
for i in range(0, len(plaintext), 2):
|
||||
pair = plaintext[i:i+2]
|
||||
print(f"\n处理字母对: {pair}")
|
||||
|
||||
# 在原始表格中找到位置
|
||||
pos1 = position(table, pair[0])
|
||||
pos2 = position(table, pair[1])
|
||||
print(f"第一个字母 {pair[0]} 在原始表格中的位置: ({pos1[0]}, {pos1[1]})")
|
||||
print(f"第二个字母 {pair[1]} 在原始表格中的位置: ({pos2[0]}, {pos2[1]})")
|
||||
|
||||
# 在新表格中找到对应字母
|
||||
encrypted_pair = topRight[pos1[0]][pos1[1]] + bottomLeft[pos2[0]][pos2[1]]
|
||||
print(f"加密后的字母对: {encrypted_pair}")
|
||||
ciphertext += encrypted_pair
|
||||
|
||||
print(f"\n最终加密结果: {ciphertext}")
|
||||
return ciphertext
|
||||
|
||||
def decode(self, text, **kwargs):
|
||||
print("开始解密过程...")
|
||||
print(f"加密文本: {text}")
|
||||
|
||||
# 准备密钥表格
|
||||
key = ['ECHO', 'VORTEX']
|
||||
table = [['K', 'L', 'M', 'N', 'O'],
|
||||
['P', 'R', 'S', 'T', 'U'],
|
||||
['V', 'W', 'X', 'Y', 'Z'],
|
||||
['A', 'B', 'C', 'D', 'E'],
|
||||
['F', 'G', 'H', 'I', 'J']]
|
||||
topRight = generate_table(key[0])
|
||||
bottomLeft = generate_table(key[1])
|
||||
|
||||
print("\n开始逐对字母解密:")
|
||||
plaintext = ''
|
||||
for i in range(0, len(text), 2):
|
||||
pair = text[i:i+2]
|
||||
print(f"\n处理加密字母对: {pair}")
|
||||
|
||||
# 在新表格中找到位置
|
||||
pos1 = position(topRight, pair[0])
|
||||
pos2 = position(bottomLeft, pair[1])
|
||||
print(f"第一个字母 {pair[0]} 在ECHO表格中的位置: ({pos1[0]}, {pos1[1]})")
|
||||
print(f"第二个字母 {pair[1]} 在VORTEX表格中的位置: ({pos2[0]}, {pos2[1]})")
|
||||
|
||||
# 在原始表格中找到对应字母
|
||||
decrypted_pair = table[pos1[0]][pos1[1]] + table[pos2[0]][pos2[1]]
|
||||
print(f"解密后的字母对: {decrypted_pair}")
|
||||
plaintext += decrypted_pair
|
||||
|
||||
print(f"\n最终解密结果: {plaintext}")
|
||||
return plaintext
|
||||
|
||||
def get_encode_rule(self, ):
|
||||
return """加密规则:
|
||||
- 输入:
|
||||
- 明文: 大写字母字符串,不含标点和空格
|
||||
- 输出:
|
||||
- 密文: 大写字母字符串
|
||||
- 准备:
|
||||
以下是经过整理后的文字:
|
||||
|
||||
---
|
||||
|
||||
### 5x5 网格布局
|
||||
|
||||
共有四个5x5的字符网格,每个网格代表了不同的排列方式。
|
||||
|
||||
1. **网格1 原始网格**
|
||||
|
||||
这是最初的字符排列,按照特定顺序组织如下:
|
||||
|
||||
```
|
||||
K L M N O
|
||||
P R S T U
|
||||
V W X Y Z
|
||||
A B C D E
|
||||
F G H I J
|
||||
```
|
||||
|
||||
2. **网格2 ECHO 网格**
|
||||
|
||||
该网格根据"ECHO"这个词进行了重新排列:
|
||||
|
||||
```
|
||||
E C H O A
|
||||
B D F G I
|
||||
J K L M N
|
||||
P R S T U
|
||||
V W X Y Z
|
||||
```
|
||||
|
||||
3. **网格3 VORTEX 网格**
|
||||
|
||||
此网格基于"VORTEX"一词进行了独特的字符重组:
|
||||
|
||||
```
|
||||
V O R T E
|
||||
X A B C D
|
||||
F G H I J
|
||||
K L M N P
|
||||
S U W Y Z
|
||||
```
|
||||
|
||||
4. **网格4 重复原始网格**
|
||||
|
||||
最后一个网格与第一个原始网格完全相同,没有进行任何改变:
|
||||
|
||||
```
|
||||
K L M N O
|
||||
P R S T U
|
||||
V W X Y Z
|
||||
A B C D E
|
||||
F G H I J
|
||||
```
|
||||
|
||||
每个网格展示了不同主题词下字符的独特排列。
|
||||
- 加密步骤:
|
||||
- 清理明文,移除空格和非字母字符,移除字母Q,转换为大写
|
||||
- 如果明文长度为奇数,添加字母'X'使其成为偶数
|
||||
- 将处理后的明文分成两个字母一组
|
||||
- 对于每组两个字母p1,p2:
|
||||
- 在网格1和网格4中找到第一个字母和第二个字母的位置
|
||||
- 在网格2和网格3中找到这两个位置对应的字母,用这两个字母作为该组的加密结果
|
||||
- 连接所有加密后的字母组形成最终密文"""
|
||||
|
||||
def get_decode_rule(self, ):
|
||||
return """解密规则:
|
||||
- 输入:
|
||||
- 密文: 大写字母字符串
|
||||
- 输出:
|
||||
- 明文: 大写字母字符串
|
||||
- 准备:
|
||||
- 四个5x5网格(与加密相同)
|
||||
- 解密步骤(与加密步骤相反):
|
||||
- 清理密文,移除空格和非字母字符,转换为大写
|
||||
- 将处理后的密文分成两个字母一组
|
||||
- 对于每组两个字母c1,c2:
|
||||
- 在网格2和网格3中找到第一个字母和第二个字母的位置
|
||||
- 在网格1和网格4中找到这两个位置对应的字母,用这两个字母作为该组的解密结果
|
||||
- 连接所有解密后的字母组形成最终明文"""
|
||||
117
internbootcamp/libs/cipher/KorInverseShiftSubstitutionCipherEnvironment.py
Executable file
117
internbootcamp/libs/cipher/KorInverseShiftSubstitutionCipherEnvironment.py
Executable file
|
|
@ -0,0 +1,117 @@
|
|||
from .BaseCipherEnvironment import BaseCipherEnvironment
|
||||
|
||||
def prepare_alphabet(keyword):
|
||||
alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
|
||||
reversed_alphabet = alphabet[::-1]
|
||||
cleaned_keyword = "".join(dict.fromkeys(keyword))
|
||||
substitution_alphabet = cleaned_keyword + "".join([char for char in alphabet if char not in cleaned_keyword])
|
||||
return alphabet, reversed_alphabet, substitution_alphabet
|
||||
|
||||
|
||||
class KorInverseShiftSubstitutionCipherEnvironment(BaseCipherEnvironment):
|
||||
def __init__(self, *args, **kwargs):
|
||||
problem_description = ''
|
||||
super().__init__(problem_description, *args, **kwargs)
|
||||
|
||||
@property
|
||||
def cipher_name(self) -> str:
|
||||
return "Kor_rule1_InverseShiftSubstitutionCipher"
|
||||
|
||||
|
||||
def encode(self, text, **kwargs):
|
||||
keyword = "RFDDJUUH"
|
||||
n = 4
|
||||
|
||||
# 处理输入文本,只保留字母并转大写
|
||||
text = ''.join([c.upper() for c in text if c.isalpha()])
|
||||
print(f"处理后的输入文本: {text}")
|
||||
|
||||
alphabet, reversed_alphabet, substitution_alphabet = prepare_alphabet(keyword)
|
||||
print(f"标准字母表: {alphabet}")
|
||||
print(f"反转字母表: {reversed_alphabet}")
|
||||
print(f"替换字母表: {substitution_alphabet}")
|
||||
|
||||
ciphertext = []
|
||||
for char in text:
|
||||
print(f"\n加密字符 {char}:")
|
||||
# 步骤1: 反转映射
|
||||
reverse_char = reversed_alphabet[alphabet.index(char)]
|
||||
print(f"1. 在标准字母表中找到位置并用反转字母表对应位置字母替换: {char} -> {reverse_char}")
|
||||
|
||||
# 步骤2: 向前移动4位
|
||||
index = (ord(reverse_char) - ord('A') + n) % 26
|
||||
shifted_char = alphabet[index]
|
||||
print(f"2. 将得到的字母向前移动4位: {reverse_char} -> {shifted_char}")
|
||||
|
||||
# 步骤3: 替换字母表映射
|
||||
encrypted_char = substitution_alphabet[index]
|
||||
print(f"3. 在标准字母表中找到位置并用替换字母表对应位置字母替换: {shifted_char} -> {encrypted_char}")
|
||||
|
||||
ciphertext.append(encrypted_char)
|
||||
|
||||
result = "".join(ciphertext)
|
||||
print(f"\n最终加密结果: {result}")
|
||||
return result
|
||||
|
||||
def decode(self, text, **kwargs):
|
||||
keyword = "RFDDJUUH"
|
||||
n = 4
|
||||
|
||||
alphabet, reversed_alphabet, substitution_alphabet = prepare_alphabet(keyword)
|
||||
print(f"标准字母表: {alphabet}")
|
||||
print(f"反转字母表: {reversed_alphabet}")
|
||||
print(f"替换字母表: {substitution_alphabet}")
|
||||
|
||||
plaintext = []
|
||||
for char in text:
|
||||
print(f"\n解密字符 {char}:")
|
||||
# 步骤1: 在替换字母表中找到对应标准字母表字母
|
||||
index = substitution_alphabet.index(char)
|
||||
standard_char = alphabet[index]
|
||||
print(f"1. 在替换字母表中找到位置并用标准字母表对应位置字母替换: {char} -> {standard_char}")
|
||||
|
||||
# 步骤2: 向后移动4位
|
||||
decrypted_index = (index - n) % 26
|
||||
shifted_char = chr(ord('A') + decrypted_index)
|
||||
print(f"2. 将得到的字母向后移动4位: {standard_char} -> {shifted_char}")
|
||||
|
||||
# 步骤3: 反转映射还原
|
||||
decrypted_char = alphabet[reversed_alphabet.index(shifted_char)]
|
||||
print(f"3. 在反转字母表中找到位置并用标准字母表对应位置字母替换: {shifted_char} -> {decrypted_char}")
|
||||
|
||||
plaintext.append(decrypted_char)
|
||||
|
||||
result = "".join(plaintext)
|
||||
print(f"\n最终解密结果: {result}")
|
||||
return result
|
||||
|
||||
def get_encode_rule(self,):
|
||||
return """加密规则:
|
||||
- 输入:
|
||||
- 明文: 仅包含大写字母的字符串,不含标点和空格
|
||||
- 输出:
|
||||
- 密文: 大写字母字符串
|
||||
- 准备:
|
||||
- 标准字母表: "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
|
||||
- 反转字母表: "ZYXWVUTSRQPONMLKJIHGFEDCBA"
|
||||
- 替换字母表: "RFDJUHABCEGIKLMNOPQSTVWXYZ"
|
||||
- 加密步骤:
|
||||
- 对明文中的每个字母p:
|
||||
- (1) 使用反转字母表进行反向映射。在标准字母表中找到其位置,并用反转字母表中对应位置的字母替换。例如,A映射为Z,B映射为Y。
|
||||
- (2) 将步骤(1)得到的字母在标准字母表顺序中向前移动4位。例如,如果p=A,经过步骤(1)映射为Z,然后Z在标准字母表中向前移动4位得到D。
|
||||
- (3) 将步骤(2)得到的字母,在标准字母表中找到其位置,用替换字母表中对应位置的字母替换,得到最终的密文字母。例如,如果经过步骤(2)得到字母D,则映射为J。"""
|
||||
|
||||
def get_decode_rule(self):
|
||||
return """解密规则:
|
||||
- 输入:
|
||||
- 密文: 大写字母字符串
|
||||
- 输出:
|
||||
- 明文: 大写字母字符串
|
||||
- 准备:
|
||||
- 标准字母表: "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
|
||||
- 反转字母表: "ZYXWVUTSRQPONMLKJIHGFEDCBA"
|
||||
- 替换字母表: "RFDJUHABCEGIKLMNOPQSTVWXYZ"
|
||||
- 解密步骤(与加密步骤完全相反):
|
||||
- (1) 对密文中的每个字母c,在替换字母表中找到其位置,用标准字母表中对应位置的字母替换。
|
||||
- (2) 将步骤(1)得到的字母按标准字母表顺序向后移动4位。
|
||||
- (3) 将步骤(2)得到的字母,在反转字母表中找到其位置,然后用标准字母表中对应位置的字母替换。例如,Z映射为A,Y映射为B。"""
|
||||
158
internbootcamp/libs/cipher/KorJeffersonCipherEnvironment.py
Executable file
158
internbootcamp/libs/cipher/KorJeffersonCipherEnvironment.py
Executable file
|
|
@ -0,0 +1,158 @@
|
|||
from .BaseCipherEnvironment import BaseCipherEnvironment
|
||||
|
||||
class JeffersonCipher:
|
||||
def __init__(self):
|
||||
self.wheel_configuration = [
|
||||
"ABCEIGDJFVUYMHTQKZOLRXSPWN",
|
||||
"ACDEHFIJKTLMOUVYGZNPQXRWSB",
|
||||
"ADKOMJUBGEPHSCZINXFYQRTVWL",
|
||||
"AEDCBIFGJHLKMRUOQVPTNWYXZS",
|
||||
"AFNQUKDOPITJBRHCYSLWEMZVXG",
|
||||
"AGPOCIXLURNDYZHWBJSQFKVMET",
|
||||
"AHXJEZBNIKPVROGSYDULCFMQTW",
|
||||
"AIHPJOBWKCVFZLQERYNSUMGTDX",
|
||||
"AJDSKQOIVTZEFHGYUNLPMBXWCR",
|
||||
"AKELBDFJGHONMTPRQSVZUXYWIC",
|
||||
"ALTMSXVQPNOHUWDIZYCGKRFBEJ",
|
||||
"AMNFLHQGCUJTBYPZKXISRDVEWO",
|
||||
"ANCJILDHBMKGXUZTSWQYVORPFE",
|
||||
"AODWPKJVIUQHZCTXBLEGNYRSMF",
|
||||
"APBVHIYKSGUENTCXOWFQDRLJZM",
|
||||
"AQJNUBTGIMWZRVLXCSHDEOKFPY",
|
||||
"ARMYOFTHEUSZJXDPCWGQIBKLNV",
|
||||
"ASDMCNEQBOZPLGVJRKYTFUIWXH",
|
||||
"ATOJYLFXNGWHVCMIRBSEKUPDZQ",
|
||||
"AUTRZXQLYIOVBPESNHJWMDGFCK",
|
||||
"AVNKHRGOXEYBFSJMUDQCLZWTIP",
|
||||
"AWVSFDLIEBHKNRJQZGMXPUCOTY",
|
||||
"AXKWREVDTUFOYHMLSIQNJCPGBZ",
|
||||
"AYJPXMVKBQWUGLOSTECHNZFRID",
|
||||
"AZDNBUHYFWJLVGRCQMPSOEXTKI"
|
||||
]
|
||||
|
||||
def encrypt(self, message):
|
||||
encrypted_message = []
|
||||
wheel_position = 0
|
||||
|
||||
for char in message:
|
||||
current_wheel = self.wheel_configuration[wheel_position]
|
||||
index = current_wheel.index(char)
|
||||
encrypted_char = current_wheel[(index + 1) % 26]
|
||||
encrypted_message.append(encrypted_char)
|
||||
wheel_position = (wheel_position + 1) % len(self.wheel_configuration)
|
||||
|
||||
return ''.join(encrypted_message)
|
||||
|
||||
def decrypt(self, encrypted_message):
|
||||
decrypted_message = []
|
||||
wheel_position = 0
|
||||
|
||||
for char in encrypted_message:
|
||||
current_wheel = self.wheel_configuration[wheel_position]
|
||||
index = current_wheel.index(char)
|
||||
decrypted_char = current_wheel[(index - 1) % 26]
|
||||
decrypted_message.append(decrypted_char)
|
||||
wheel_position = (wheel_position + 1) % len(self.wheel_configuration)
|
||||
|
||||
return ''.join(decrypted_message)
|
||||
|
||||
|
||||
class KorJeffersonCipherEnvironment(BaseCipherEnvironment):
|
||||
def __init__(self, *args, **kwargs):
|
||||
problem_description = ''
|
||||
super().__init__(problem_description, *args, **kwargs)
|
||||
|
||||
@property
|
||||
def cipher_name(self) -> str:
|
||||
return 'Kor_rule10_JeffersonCipher'
|
||||
|
||||
def encode(self, text, **kwargs):
|
||||
# 将输入转换为大写字母并移除非字母字符
|
||||
text = ''.join([char.upper() for char in text if char.isalpha()])
|
||||
print(f"处理后的输入文本: {text}")
|
||||
|
||||
cipher = JeffersonCipher()
|
||||
print("初始化Jefferson密码轮...")
|
||||
|
||||
print("开始加密过程:")
|
||||
print("- 从第1个密码轮开始")
|
||||
encrypted = cipher.encrypt(text)
|
||||
print(f"- 对每个字符:")
|
||||
for i, (plain, cipher) in enumerate(zip(text, encrypted)):
|
||||
wheel_num = (i % 25) + 1
|
||||
print(f" * 在第{wheel_num}个密码轮上,将字符 {plain} 替换为下一个字符 {cipher}")
|
||||
|
||||
print(f"加密完成,结果: {encrypted}")
|
||||
return encrypted
|
||||
|
||||
def decode(self, text, **kwargs):
|
||||
cipher = JeffersonCipher()
|
||||
print("初始化Jefferson密码轮...")
|
||||
|
||||
print("开始解密过程:")
|
||||
print("- 从第1个密码轮开始")
|
||||
decrypted = cipher.decrypt(text)
|
||||
print(f"- 对每个字符:")
|
||||
for i, (cipher, plain) in enumerate(zip(text, decrypted)):
|
||||
wheel_num = (i % 25) + 1
|
||||
print(f" * 在第{wheel_num}个密码轮上,将字符 {cipher} 替换为前一个字符 {plain}")
|
||||
|
||||
print(f"解密完成,结果: {decrypted}")
|
||||
return decrypted
|
||||
|
||||
def get_encode_rule(self, ):
|
||||
return """加密规则:
|
||||
- 输入:
|
||||
- 明文: 仅包含大写字母的字符串,不含标点和空格
|
||||
- 输出:
|
||||
- 密文: 大写字母字符串
|
||||
- 准备:
|
||||
- 25个密码轮,每个密码轮包含26个字母的不同排列
|
||||
[
|
||||
"ABCEIGDJFVUYMHTQKZOLRXSPWN",
|
||||
"ACDEHFIJKTLMOUVYGZNPQXRWSB",
|
||||
"ADKOMJUBGEPHSCZINXFYQRTVWL",
|
||||
"AEDCBIFGJHLKMRUOQVPTNWYXZS",
|
||||
"AFNQUKDOPITJBRHCYSLWEMZVXG",
|
||||
"AGPOCIXLURNDYZHWBJSQFKVMET",
|
||||
"AHXJEZBNIKPVROGSYDULCFMQTW",
|
||||
"AIHPJOBWKCVFZLQERYNSUMGTDX",
|
||||
"AJDSKQOIVTZEFHGYUNLPMBXWCR",
|
||||
"AKELBDFJGHONMTPRQSVZUXYWIC",
|
||||
"ALTMSXVQPNOHUWDIZYCGKRFBEJ",
|
||||
"AMNFLHQGCUJTBYPZKXISRDVEWO",
|
||||
"ANCJILDHBMKGXUZTSWQYVORPFE",
|
||||
"AODWPKJVIUQHZCTXBLEGNYRSMF",
|
||||
"APBVHIYKSGUENTCXOWFQDRLJZM",
|
||||
"AQJNUBTGIMWZRVLXCSHDEOKFPY",
|
||||
"ARMYOFTHEUSZJXDPCWGQIBKLNV",
|
||||
"ASDMCNEQBOZPLGVJRKYTFUIWXH",
|
||||
"ATOJYLFXNGWHVCMIRBSEKUPDZQ",
|
||||
"AUTRZXQLYIOVBPESNHJWMDGFCK",
|
||||
"AVNKHRGOXEYBFSJMUDQCLZWTIP",
|
||||
"AWVSFDLIEBHKNRJQZGMXPUCOTY",
|
||||
"AXKWREVDTUFOYHMLSIQNJCPGBZ",
|
||||
"AYJPXMVKBQWUGLOSTECHNZFRID",
|
||||
"AZDNBUHYFWJLVGRCQMPSOEXTKI"
|
||||
]
|
||||
- 加密步骤:
|
||||
- 初始选择第1个密码轮
|
||||
- 对明文中的每个字符p:
|
||||
- 在当前密码轮上找到字符p,用其后一个字符替换得到密文字符
|
||||
- 如果当前字符在密码轮末尾,则回到密码轮开头
|
||||
- 移动到下一个密码轮处理下一个字符,当到达最后一个密码轮时,返回第一个密码轮继续加密过程"""
|
||||
|
||||
def get_decode_rule(self, ):
|
||||
return """解密规则:
|
||||
- 输入:
|
||||
- 密文: 大写字母字符串
|
||||
- 输出:
|
||||
- 明文: 大写字母字符串
|
||||
- 准备:
|
||||
- 25个密码轮,与加密相同
|
||||
- 解密步骤(与加密步骤相反):
|
||||
- 初始选择第1个密码轮
|
||||
- 对密文中的每个字符c:
|
||||
- 在当前密码轮上找到字符c,用其前一个字符替换得到明文字符
|
||||
- 如果当前字符在密码轮开头,则回到密码轮末尾
|
||||
- 移动到下一个密码轮处理下一个字符,当到达最后一个密码轮时,返回第一个密码轮继续解密过程"""
|
||||
191
internbootcamp/libs/cipher/KorMorbitCipherEnvironment.py
Executable file
191
internbootcamp/libs/cipher/KorMorbitCipherEnvironment.py
Executable file
|
|
@ -0,0 +1,191 @@
|
|||
from .BaseCipherEnvironment import BaseCipherEnvironment
|
||||
|
||||
class MorseCodeCipher:
|
||||
def __init__(self, key):
|
||||
self.key = key
|
||||
self.index_mapping = self.generate_index_mapping()
|
||||
self.reverse_mapping = {v: k for k, v in self.index_mapping.items()}
|
||||
|
||||
def generate_index_mapping(self):
|
||||
sorted_key = sorted(self.key)
|
||||
index_mapping = {
|
||||
'..': sorted_key.index(self.key[0]) + 1,
|
||||
'.-': sorted_key.index(self.key[1]) + 1,
|
||||
'./': sorted_key.index(self.key[2]) + 1,
|
||||
'-.': sorted_key.index(self.key[3]) + 1,
|
||||
'--': sorted_key.index(self.key[4]) + 1,
|
||||
'-/': sorted_key.index(self.key[5]) + 1,
|
||||
'/.': sorted_key.index(self.key[6]) + 1,
|
||||
'/-': sorted_key.index(self.key[7]) + 1,
|
||||
'//': sorted_key.index(self.key[8]) + 1,
|
||||
}
|
||||
return index_mapping
|
||||
|
||||
def encrypt(self, plaintext):
|
||||
morse_code = plaintext
|
||||
encrypted_numbers = []
|
||||
|
||||
pairs = [morse_code[i:i+2] for i in range(0, len(morse_code), 2)]
|
||||
for pair in pairs:
|
||||
if len(pair) % 2 == 0:
|
||||
index = self.index_mapping[pair]
|
||||
encrypted_numbers.append(str(index))
|
||||
else:
|
||||
encrypted_numbers.append(pair)
|
||||
|
||||
encrypted_message = ''.join(encrypted_numbers)
|
||||
return encrypted_message
|
||||
|
||||
def decrypt(self, encrypted_message):
|
||||
decrypted_numbers = []
|
||||
|
||||
for char in encrypted_message:
|
||||
if char.isdigit():
|
||||
index = int(char)
|
||||
decrypted_numbers.append(self.reverse_mapping[index])
|
||||
else:
|
||||
decrypted_numbers.append(char)
|
||||
|
||||
decrypted_morse = ''.join(decrypted_numbers)
|
||||
return decrypted_morse
|
||||
|
||||
def text_to_morse(self, text):
|
||||
morse_code = {
|
||||
'A': '.-', 'B': '-...', 'C': '-.-.', 'D': '-..',
|
||||
'E': '.', 'F': '..-.', 'G': '--.', 'H': '....',
|
||||
'I': '..', 'J': '.---', 'K': '-.-', 'L': '.-..',
|
||||
'M': '--', 'N': '-.', 'O': '---', 'P': '.--.',
|
||||
'Q': '--.-', 'R': '.-.', 'S': '...', 'T': '-',
|
||||
'U': '..-', 'V': '...-', 'W': '.--', 'X': '-..-',
|
||||
'Y': '-.--', 'Z': '--..',
|
||||
}
|
||||
|
||||
morse_chars = []
|
||||
words = text.split(' ')
|
||||
|
||||
for word in words:
|
||||
chars = []
|
||||
for char in word:
|
||||
if char.upper() in morse_code:
|
||||
chars.append(morse_code[char.upper()])
|
||||
morse_chars.append('/'.join(chars))
|
||||
|
||||
return '//'.join(morse_chars)
|
||||
|
||||
def morse_to_text(self, morse_code):
|
||||
morse_code = morse_code.split('//')
|
||||
morse_to_char = {
|
||||
'.-': 'A', '-...': 'B', '-.-.': 'C', '-..': 'D',
|
||||
'.': 'E', '..-.': 'F', '--.': 'G', '....': 'H',
|
||||
'..': 'I', '.---': 'J', '-.-': 'K', '.-..': 'L',
|
||||
'--': 'M', '-.': 'N', '---': 'O', '.--.': 'P',
|
||||
'--.-': 'Q', '.-.': 'R', '...': 'S', '-': 'T',
|
||||
'..-': 'U', '...-': 'V', '.--': 'W', '-..-': 'X',
|
||||
'-.--': 'Y', '--..': 'Z',
|
||||
}
|
||||
morse_chars = []
|
||||
for word in morse_code:
|
||||
chars = []
|
||||
for char in word.split('/'):
|
||||
chars.append(morse_to_char[char])
|
||||
morse_chars.append(''.join(chars))
|
||||
return ' '.join(morse_chars)
|
||||
|
||||
|
||||
class KorMorbitCipherEnvironment(BaseCipherEnvironment):
|
||||
def __init__(self, *args, **kwargs):
|
||||
problem_description = ''
|
||||
super().__init__(problem_description, *args, **kwargs)
|
||||
|
||||
@property
|
||||
def cipher_name(self) -> str:
|
||||
return 'Kor_rule12_MorbitCipher'
|
||||
|
||||
def encode(self, text, **kwargs):
|
||||
print("加密步骤开始:")
|
||||
# 将输入转换为大写字母,去除标点和空格
|
||||
text = ''.join([char.upper() for char in text if char.isalpha()])
|
||||
print(f"1. 将输入文本标准化为大写字母: {text}")
|
||||
|
||||
# 初始化密码器
|
||||
cipher = MorseCodeCipher("123456789")
|
||||
|
||||
# 转换为摩斯密码
|
||||
morse_code = cipher.text_to_morse(text)
|
||||
print(f"2. 将文本转换为摩斯密码: {morse_code}")
|
||||
|
||||
# 加密
|
||||
encrypted = cipher.encrypt(morse_code)
|
||||
print(f"3. 根据数字索引映射表将摩斯密码对转换为数字: {encrypted}")
|
||||
|
||||
return encrypted
|
||||
|
||||
def decode(self, text, **kwargs):
|
||||
print("解密步骤开始:")
|
||||
print(f"1. 接收到的加密文本: {text}")
|
||||
|
||||
# 初始化密码器
|
||||
cipher = MorseCodeCipher("123456789")
|
||||
|
||||
# 解密为摩斯密码
|
||||
morse_code = cipher.decrypt(text)
|
||||
print(f"2. 将数字转换回摩斯密码: {morse_code}")
|
||||
|
||||
# 转换为明文
|
||||
decrypted = cipher.morse_to_text(morse_code)
|
||||
print(f"3. 将摩斯密码转换为原文: {decrypted}")
|
||||
|
||||
return decrypted
|
||||
|
||||
def get_encode_rule(self, ):
|
||||
encode_rule = """
|
||||
加密规则:
|
||||
- 输入:
|
||||
- 明文: 大写字母字符串,不含标点和空格
|
||||
- 输出:
|
||||
- 密文: 字符串
|
||||
- 准备:
|
||||
- 数字索引映射表
|
||||
- '..' : 5
|
||||
- '.-' : 4
|
||||
- './' : 9
|
||||
- '-.' : 8
|
||||
- '--' : 6
|
||||
- '-/' : 7
|
||||
- '/.' : 3
|
||||
- '/-' : 1
|
||||
- '//' : 2
|
||||
- 摩斯密码表
|
||||
- A: '.-', B: '-...', C: '-.-.', D: '-..',
|
||||
- E: '.', F: '..-.', G: '--.', H: '....',
|
||||
- I: '..', J: '.---', K: '-.-', L: '.-..',
|
||||
- M: '--', N: '-.', O: '---', P: '.--.',
|
||||
- Q: '--.-', R: '.-.', S: '...', T: '-',
|
||||
- U: '..-', V: '...-', W: '.--', X: '-..-',
|
||||
- Y: '-.--', Z: '--..'
|
||||
- 加密步骤:
|
||||
- 根据摩斯密码表将明文中的每个字符转换为摩斯密码,用/分隔每个字符,例如AB对应'.-/-...'
|
||||
- 将摩斯密码分成两个字符一组。如果摩斯密码长度为奇数,最后一个字符不进行映射,直接添加到密文末尾
|
||||
- 根据数字索引映射表将每组字符转换为对应的数字字符串
|
||||
- 加密后的消息用字符串表示
|
||||
"""
|
||||
return encode_rule
|
||||
|
||||
def get_decode_rule(self, ):
|
||||
decode_rule = """
|
||||
解密规则:
|
||||
- 输入:
|
||||
- 密文: 数字字符串
|
||||
- 输出:
|
||||
- 明文: 大写字母字符串
|
||||
- 准备:
|
||||
- 数字索引映射表(与加密相同)
|
||||
- 摩斯密码表(与加密相同)
|
||||
- 解密步骤(与加密步骤相反):
|
||||
- 根据数字索引映射表将密文中的每个数字转换为对应的字符对。如果密文末尾有非数字字符,则不处理。此时获得完整的摩斯密码
|
||||
- 通过/分隔摩斯密码获得每个字符的摩斯密码
|
||||
- 根据摩斯密码表将每个字符的摩斯密码转换为对应的明文字符
|
||||
- 最终明文字符为大写字符串
|
||||
"""
|
||||
return decode_rule
|
||||
|
||||
117
internbootcamp/libs/cipher/KorMultiTapPhoneCodeEnvironment.py
Executable file
117
internbootcamp/libs/cipher/KorMultiTapPhoneCodeEnvironment.py
Executable file
|
|
@ -0,0 +1,117 @@
|
|||
from .BaseCipherEnvironment import BaseCipherEnvironment
|
||||
|
||||
import re
|
||||
|
||||
multitap_encode = {
|
||||
'A': '2^1', 'B': '2^2', 'C': '2^3',
|
||||
'D': '3^1', 'E': '3^2', 'F': '3^3',
|
||||
'G': '4^1', 'H': '4^2', 'I': '4^3',
|
||||
'J': '5^1', 'K': '5^2', 'L': '5^3',
|
||||
'M': '6^1', 'N': '6^2', 'O': '6^3',
|
||||
'P': '7^1', 'Q': '7^2', 'R': '7^3', 'S': '7^4',
|
||||
'T': '8^1', 'U': '8^2', 'V': '8^3',
|
||||
'W': '9^1', 'X': '9^2', 'Y': '9^3', 'Z': '9^4',
|
||||
}
|
||||
|
||||
multitap_decode = {v: k for k, v in multitap_encode.items()}
|
||||
|
||||
|
||||
class KorMultiTapPhoneCodeEnvironment(BaseCipherEnvironment):
|
||||
def __init__(self, problem_description='', *args, **kwargs):
|
||||
super().__init__(problem_description, *args, **kwargs)
|
||||
|
||||
@property
|
||||
def cipher_name(self) -> str:
|
||||
return "Kor_rule3_MultiTapPhoneCode"
|
||||
|
||||
def encode(self, text, **kwargs):
|
||||
print(f"原始文本: {text}")
|
||||
# 转换为大写字母并移除非字母字符
|
||||
text = ''.join(char.upper() for char in text if char.isalpha())
|
||||
print(f"处理后的文本(仅大写字母): {text}")
|
||||
|
||||
print("开始逐字符加密:")
|
||||
encoded_text = ''
|
||||
for char in text:
|
||||
if char in multitap_encode:
|
||||
code = multitap_encode[char]
|
||||
print(f"字符 {char} 对应的多击编码是: {code}")
|
||||
encoded_text += code
|
||||
|
||||
print(f"最终加密结果: {encoded_text}")
|
||||
return encoded_text
|
||||
|
||||
def decode(self, text, **kwargs):
|
||||
print(f"加密文本: {text}")
|
||||
print("开始解密:")
|
||||
|
||||
decoded_text = ''
|
||||
matches = re.findall(r'\d\^\d|\d', text)
|
||||
for match in matches:
|
||||
if match in multitap_decode:
|
||||
char = multitap_decode[match]
|
||||
print(f"多击编码 {match} 对应的字符是: {char}")
|
||||
decoded_text += char
|
||||
|
||||
print(f"解密结果: {decoded_text}")
|
||||
return decoded_text
|
||||
|
||||
def get_encode_rule(self,):
|
||||
encode_rule = """
|
||||
加密规则:
|
||||
- 输入:
|
||||
- 明文: 仅包含大写字母的字符串,不含标点和空格。
|
||||
- 输出:
|
||||
- 密文: 不含标点的字符串。
|
||||
- 准备:
|
||||
- 多击编码表
|
||||
| 字母 | 多击编码 |
|
||||
| A | 2^1 |
|
||||
| B | 2^2 |
|
||||
| C | 2^3 |
|
||||
| D | 3^1 |
|
||||
| E | 3^2 |
|
||||
| F | 3^3 |
|
||||
| G | 4^1 |
|
||||
| H | 4^2 |
|
||||
| I | 4^3 |
|
||||
| J | 5^1 |
|
||||
| K | 5^2 |
|
||||
| L | 5^3 |
|
||||
| M | 6^1 |
|
||||
| N | 6^2 |
|
||||
| O | 6^3 |
|
||||
| P | 7^1 |
|
||||
| Q | 7^2 |
|
||||
| R | 7^3 |
|
||||
| S | 7^4 |
|
||||
| T | 8^1 |
|
||||
| U | 8^2 |
|
||||
| V | 8^3 |
|
||||
| W | 9^1 |
|
||||
| X | 9^2 |
|
||||
| Y | 9^3 |
|
||||
| Z | 9^4 |
|
||||
- 加密步骤:
|
||||
- 对于每个明文字符p:
|
||||
- 如果p是大写字母且存在于多击编码表中:
|
||||
- 用多击编码表中对应的多击编码替换p。
|
||||
"""
|
||||
return encode_rule
|
||||
|
||||
def get_decode_rule(self):
|
||||
decode_rule = """
|
||||
解密规则:
|
||||
- 输入:
|
||||
- 密文: 不含标点的字符串。
|
||||
- 输出:
|
||||
- 明文: 大写字母字符串。
|
||||
- 准备: 多击编码表(与加密相同)
|
||||
- 解密步骤(与加密步骤相反):
|
||||
- 对于每个密文中的多击编码c:
|
||||
- 如果c是多击编码表中的编码:
|
||||
- 用多击编码表中对应的大写字母替换c。
|
||||
"""
|
||||
return decode_rule
|
||||
|
||||
|
||||
148
internbootcamp/libs/cipher/KorPathCipherEnvironment.py
Executable file
148
internbootcamp/libs/cipher/KorPathCipherEnvironment.py
Executable file
|
|
@ -0,0 +1,148 @@
|
|||
from .BaseCipherEnvironment import BaseCipherEnvironment
|
||||
|
||||
class KorPathCipherEnvironment(BaseCipherEnvironment):
|
||||
def __init__(self, *args, **kwargs):
|
||||
problem_description = ''
|
||||
super().__init__(problem_description, *args, **kwargs)
|
||||
|
||||
@property
|
||||
def cipher_name(self) -> str:
|
||||
return 'Kor_rule17_PathCipher'
|
||||
|
||||
def encode(self, text, **kwargs):
|
||||
# 将输入转换为大写字母并去除非字母字符
|
||||
text = ''.join([char.upper() for char in text if char.isalpha()])
|
||||
print(f"1. 输入文本转换为大写并去除非字母字符: {text}")
|
||||
|
||||
# 计算行数和列数
|
||||
cols = 5
|
||||
text_length = len(text)
|
||||
rows = (text_length + cols - 1) // cols
|
||||
print(f"2. 确定网格大小: {rows}行 x {cols}列")
|
||||
|
||||
# 创建空网格
|
||||
grid = [[' ' for _ in range(cols)] for _ in range(rows)]
|
||||
|
||||
# 按照特殊方式填充网格
|
||||
index = 0
|
||||
print("3. 开始填充网格:")
|
||||
for i in range(rows):
|
||||
if i % 2 == 0:
|
||||
print(f" 第{i+1}行从左到右填充:", end=" ")
|
||||
for j in range(cols):
|
||||
if index < len(text):
|
||||
grid[i][j] = text[index]
|
||||
print(text[index], end=" ")
|
||||
index += 1
|
||||
print()
|
||||
else:
|
||||
print(f" 第{i+1}行从右到左填充:", end=" ")
|
||||
for j in range(cols - 1, -1, -1):
|
||||
if index < len(text):
|
||||
grid[i][j] = text[index]
|
||||
print(text[index], end=" ")
|
||||
index += 1
|
||||
print()
|
||||
|
||||
# 按列读取并添加#号
|
||||
cipher_text = []
|
||||
print("4. 按列读取并添加#号:")
|
||||
for j in range(cols):
|
||||
print(f" 第{j+1}列:", end=" ")
|
||||
for i in range(rows):
|
||||
char = grid[i][j]
|
||||
if (i == rows - 1) and char != ' ':
|
||||
cipher_text.append(char)
|
||||
cipher_text.append("#")
|
||||
print(char, end="")
|
||||
break
|
||||
elif char == ' ':
|
||||
cipher_text.append("#")
|
||||
print("#", end="")
|
||||
break
|
||||
else:
|
||||
cipher_text.append(char)
|
||||
print(char, end="")
|
||||
print("#")
|
||||
|
||||
result = ''.join(cipher_text)
|
||||
print(f"5. 最终密文: {result}")
|
||||
return result
|
||||
|
||||
def decode(self, text, **kwargs):
|
||||
print(f"1. 收到密文: {text}")
|
||||
|
||||
# 分割密文
|
||||
cols = 5
|
||||
parts = text.split('#')
|
||||
parts = parts[:-1] # 移除最后一个空元素
|
||||
rows = max(len(part) for part in parts)
|
||||
print(f"2. 将密文分割成{cols}列: {parts}")
|
||||
|
||||
# 创建网格并填充
|
||||
grid = [[' ' for _ in range(cols)] for _ in range(rows)]
|
||||
print("3. 按列填充网格:")
|
||||
for j in range(cols):
|
||||
print(f" 第{j+1}列:", end=" ")
|
||||
for i in range(len(parts[j])):
|
||||
grid[i][j] = parts[j][i]
|
||||
print(parts[j][i], end=" ")
|
||||
print()
|
||||
|
||||
# 按特定顺序读取
|
||||
plain_text = []
|
||||
print("4. 按特定顺序读取:")
|
||||
for i in range(rows):
|
||||
if i % 2 == 0:
|
||||
print(f" 第{i+1}行从左到右读取:", end=" ")
|
||||
for j in range(cols):
|
||||
if grid[i][j] != ' ':
|
||||
plain_text.append(grid[i][j])
|
||||
print(grid[i][j], end=" ")
|
||||
print()
|
||||
else:
|
||||
print(f" 第{i+1}行从右到左读取:", end=" ")
|
||||
for j in range(cols - 1, -1, -1):
|
||||
if grid[i][j] != ' ':
|
||||
plain_text.append(grid[i][j])
|
||||
print(grid[i][j], end=" ")
|
||||
print()
|
||||
|
||||
result = ''.join(plain_text)
|
||||
print(f"5. 最终明文: {result}")
|
||||
return result
|
||||
|
||||
def get_encode_rule(self,):
|
||||
return """加密规则:
|
||||
- 输入:
|
||||
- 明文: 大写字母字符串,不含标点和空格
|
||||
- 输出:
|
||||
- 密文: 不含标点和空格的字符串
|
||||
- 准备:
|
||||
- 每行最大字符数: 5
|
||||
- 加密步骤:
|
||||
- 行数从1开始计数
|
||||
- 明文按特殊方式排列:奇数行从左到右写,偶数行从右到左写,每行最多五个字母
|
||||
- 例如,对于明文"LIDAHELLOWORLD",先从左到右写第一行为LIDAH,然后从右到左写第二行为WOLLE,然后从左到右写第三行为ORLD,写完的全部内容表示如下
|
||||
LIDAH
|
||||
WOLLE
|
||||
ORLD
|
||||
- 然后按列读取,每列从上到下读取,每读完一列加一个"#",读出的内容即为最终密文
|
||||
- 例如,上述写好的内容按列读取为LWO#IOR#DLL#ALD#HE#"""
|
||||
|
||||
def get_decode_rule(self,):
|
||||
return """解密规则:
|
||||
- 输入:
|
||||
- 密文: 不含标点和空格的字符串
|
||||
- 输出:
|
||||
- 明文: 大写字母字符串,不含标点和空格
|
||||
- 准备:
|
||||
- 行数: 5
|
||||
- 解密步骤(与加密步骤完全相反):
|
||||
- 对密文中的每个字符,从上到下写入;如果遇到#,则切换到下一列继续写入,直到整个密文写完
|
||||
- 例如,对于密文LWO#IOR#DLL#ALD#HE#,写出如下
|
||||
LIDAH
|
||||
WOLLE
|
||||
ORLD
|
||||
- 然后按照奇数行从左到右读,偶数行从右到左读的顺序依次读取,最终结果即为解密后的明文
|
||||
- 例如,对于上述写好的内容,第一行从左到右读为LIDAH,第二行从右到左读为ELLOW,第三行从左到右读为ORLD,最终全部内容连接起来,解密明文为LIDAHELLOWORLD"""
|
||||
146
internbootcamp/libs/cipher/KorPhillipsFigureCipherEnvironment.py
Executable file
146
internbootcamp/libs/cipher/KorPhillipsFigureCipherEnvironment.py
Executable file
|
|
@ -0,0 +1,146 @@
|
|||
from .BaseCipherEnvironment import BaseCipherEnvironment
|
||||
|
||||
import numpy as np
|
||||
|
||||
def generate_initial_grid(keyword):
|
||||
cleaned_keyword = keyword.upper().replace('J', 'I')
|
||||
cleaned_keyword = ''.join(sorted(set(cleaned_keyword), key=cleaned_keyword.index))
|
||||
alphabet = 'ABCDEFGHIKLMNOPQRSTUVWXYZ'
|
||||
grid = np.array(list(cleaned_keyword + ''.join(filter(lambda c: c not in cleaned_keyword, alphabet))))
|
||||
grid = grid.reshape(5, 5)
|
||||
return grid
|
||||
|
||||
def generate_subsequent_grids(initial_grid):
|
||||
grids = [initial_grid]
|
||||
for i in range(1, 5):
|
||||
grid = np.roll(initial_grid, i, axis=0)
|
||||
grids.append(grid)
|
||||
for i in range(1, 4):
|
||||
grid = np.roll(grids[4], i, axis=0)
|
||||
grids.append(grid)
|
||||
return grids
|
||||
|
||||
def find_position(grid, letter):
|
||||
indices = np.where(grid == letter)
|
||||
return indices[0][0], indices[1][0]
|
||||
|
||||
|
||||
class KorPhillipsFigureCipherEnvironment(BaseCipherEnvironment):
|
||||
def __init__(self, *args, **kwargs):
|
||||
problem_description = """
|
||||
Kor Phillips Figure Cipher
|
||||
"""
|
||||
super().__init__(problem_description, *args, **kwargs)
|
||||
|
||||
@property
|
||||
def cipher_name(self) -> str:
|
||||
return "Kor_rule7_PhillipsFigureCipher"
|
||||
|
||||
def encode(self, text, **kwargs):
|
||||
keyword = "PHILLIPS"
|
||||
# 处理输入文本,只保留字母并转为大写
|
||||
message = ''.join(char.upper() for char in text if char.isalpha())
|
||||
print(f"处理后的输入文本: {message}")
|
||||
|
||||
initial_grid = generate_initial_grid(keyword)
|
||||
grids = generate_subsequent_grids(initial_grid)
|
||||
encrypted_message = []
|
||||
|
||||
for i in range(0, len(message), 5):
|
||||
block = message[i:i+5]
|
||||
grid_index = (i // 5) % 8
|
||||
grid = grids[grid_index]
|
||||
print(f"\n处理第{i//5}个块: {block}")
|
||||
print(f"使用第{grid_index}号网格")
|
||||
|
||||
encrypted_block = []
|
||||
for letter in block:
|
||||
if letter == 'J':
|
||||
encrypted_block.append(letter)
|
||||
print(f"字母{letter}是J,直接保留")
|
||||
else:
|
||||
row, col = find_position(grid, letter)
|
||||
encrypted_letter = grid[(row + 1) % 5, (col + 1) % 5]
|
||||
print(f"字母{letter}在位置({row},{col}),向右下移动一格得到{encrypted_letter}")
|
||||
encrypted_block.append(encrypted_letter)
|
||||
|
||||
encrypted_message.append(''.join(encrypted_block))
|
||||
print(f"加密后的块: {''.join(encrypted_block)}")
|
||||
|
||||
result = ''.join(encrypted_message)
|
||||
print(f"\n最终加密结果: {result}")
|
||||
return result
|
||||
|
||||
def decode(self, text, **kwargs):
|
||||
keyword = "PHILLIPS"
|
||||
initial_grid = generate_initial_grid(keyword)
|
||||
grids = generate_subsequent_grids(initial_grid)
|
||||
decrypted_message = []
|
||||
|
||||
print(f"需要解密的文本: {text}")
|
||||
|
||||
for i in range(0, len(text), 5):
|
||||
block = text[i:i+5]
|
||||
grid_index = (i // 5) % 8
|
||||
grid = grids[grid_index]
|
||||
print(f"\n处理第{i//5}个块: {block}")
|
||||
print(f"使用第{grid_index}号网格")
|
||||
|
||||
decrypted_block = []
|
||||
for letter in block:
|
||||
if letter == 'J':
|
||||
decrypted_block.append(letter)
|
||||
print(f"字母{letter}是J,直接保留")
|
||||
else:
|
||||
row, col = find_position(grid, letter)
|
||||
decrypted_letter = grid[(row - 1) % 5, (col - 1) % 5]
|
||||
print(f"字母{letter}在位置({row},{col}),向左上移动一格得到{decrypted_letter}")
|
||||
decrypted_block.append(decrypted_letter)
|
||||
|
||||
decrypted_message.append(''.join(decrypted_block))
|
||||
print(f"解密后的块: {''.join(decrypted_block)}")
|
||||
|
||||
result = ''.join(decrypted_message)
|
||||
print(f"\n最终解密结果: {result}")
|
||||
return result
|
||||
|
||||
def get_encode_rule(self, ):
|
||||
return """加密规则:
|
||||
- 输入:
|
||||
- 明文: 不含标点和空格的大写字母字符串
|
||||
- 输出:
|
||||
- 密文: 大写字母字符串
|
||||
- 准备:
|
||||
- 字母表 = 'ABCDEFGHIKLMNOPQRSTUVWXYZ'(不包含字母J)
|
||||
- 8个网格(Grid0-Grid7)
|
||||
- 加密步骤:
|
||||
- 明文按5个字符分组,从0开始编号
|
||||
- 对于5个字符的块:
|
||||
- 使用的网格由grid_index = (i // 5) % 8确定,其中i是块号。整数除法运算符//将左边的数除以右边的数,向下取整结果
|
||||
- 对于当前块中的每个字符:
|
||||
- 如果字符是"J",不加密直接添加到加密块
|
||||
- 否则,在当前网格中找到字符的位置。然后向右下方移动一个网格位置(row+1,col+1)(如果越界则在对应边界的另一侧继续),移动后位置的字母作为加密字母
|
||||
- 将加密字母添加到加密块
|
||||
- 处理完所有块后,连接加密块形成最终加密消息"""
|
||||
|
||||
def get_decode_rule(self, ):
|
||||
return """解密规则:
|
||||
- 输入:
|
||||
- 密文: 大写字母字符串
|
||||
- 输出:
|
||||
- 明文: 大写字母字符串
|
||||
- 准备:
|
||||
- 字母表 = 'ABCDEFGHIKLMNOPQRSTUVWXYZ'(不包含字母J)
|
||||
- 8个网格(与加密相同)
|
||||
- 解密步骤:
|
||||
- 将密文分成5个字符的块:
|
||||
- 例如,如果密文是"KHOORTQHQTHHSAUQ",第0块是"KHOOR",第1块是"TQHQH",以此类推(从0开始编号)
|
||||
- 确定用于当前块的网格:
|
||||
计算grid_index = (i // 5) % 8从网格列表中选择适当的网格。i是块号
|
||||
- 对于块中的每个字符:
|
||||
- 如果字符是"J": 直接将"J"添加到解密块,不进行解密
|
||||
- 否则在网格中找到字符的位置,通过向左上方移动一格获得(如果越界则在对应边界的另一侧继续),移动后位置的字母作为解密字母
|
||||
- 将解密字母添加到解密块
|
||||
- 处理完块中所有字符后,将解密块添加到解密消息列表。形成最终解密消息"""
|
||||
|
||||
|
||||
121
internbootcamp/libs/cipher/KorPigpenMasonicCipherEnvironment.py
Executable file
121
internbootcamp/libs/cipher/KorPigpenMasonicCipherEnvironment.py
Executable file
|
|
@ -0,0 +1,121 @@
|
|||
from .BaseCipherEnvironment import BaseCipherEnvironment
|
||||
|
||||
class KorPigpenMasonicCipherEnvironment(BaseCipherEnvironment):
|
||||
def __init__(self, *args, **kwargs):
|
||||
problem_description = "Pigpen Masonic Cipher from Kor-bench"
|
||||
super().__init__(problem_description, *args, **kwargs)
|
||||
|
||||
@property
|
||||
def cipher_name(self) -> str:
|
||||
return "Kor_rule2_PigpenMasonicCipher"
|
||||
|
||||
def encode(self, text, **kwargs):
|
||||
print("开始加密过程...")
|
||||
print(f"原始输入文本: {text}")
|
||||
|
||||
# 将文本转换为大写并移除非字母字符
|
||||
text = ''.join([char.upper() for char in text if char.isalpha()])
|
||||
print(f"处理后的输入文本: {text}")
|
||||
|
||||
# 初始化加密表
|
||||
encryption_table = {
|
||||
'A': '!', 'B': '@', 'C': '#', 'D': '$',
|
||||
'E': '%', 'F': '^', 'G': '&', 'H': '*',
|
||||
'I': '(', 'J': ')', 'K': '_', 'L': '+',
|
||||
'M': '=', 'N': '~', 'O': '?', 'P': '/',
|
||||
'Q': '0', 'R': ':', 'S': ';', 'T': '<',
|
||||
'U': '>', 'V': '1', 'W': '2', 'X': '3',
|
||||
'Y': '4', 'Z': '5'
|
||||
}
|
||||
|
||||
encrypted_text = ""
|
||||
print("\n逐字符加密过程:")
|
||||
for char in text:
|
||||
if char in encryption_table:
|
||||
encrypted_char = encryption_table[char]
|
||||
print(f"字符 {char} 被加密为 {encrypted_char}")
|
||||
encrypted_text += encrypted_char
|
||||
else:
|
||||
encrypted_text += char
|
||||
|
||||
print(f"\n最终加密结果: {encrypted_text}")
|
||||
return encrypted_text
|
||||
|
||||
def decode(self, text, **kwargs):
|
||||
print("开始解密过程...")
|
||||
print(f"加密文本: {text}")
|
||||
|
||||
# 初始化解密表
|
||||
encryption_table = {
|
||||
'A': '!', 'B': '@', 'C': '#', 'D': '$',
|
||||
'E': '%', 'F': '^', 'G': '&', 'H': '*',
|
||||
'I': '(', 'J': ')', 'K': '_', 'L': '+',
|
||||
'M': '=', 'N': '~', 'O': '?', 'P': '/',
|
||||
'Q': '0', 'R': ':', 'S': ';', 'T': '<',
|
||||
'U': '>', 'V': '1', 'W': '2', 'X': '3',
|
||||
'Y': '4', 'Z': '5'
|
||||
}
|
||||
decryption_table = {v: k for k, v in encryption_table.items()}
|
||||
|
||||
decrypted_text = ""
|
||||
print("\n逐字符解密过程:")
|
||||
for char in text:
|
||||
if char in decryption_table:
|
||||
decrypted_char = decryption_table[char]
|
||||
print(f"符号 {char} 被解密为 {decrypted_char}")
|
||||
decrypted_text += decrypted_char
|
||||
else:
|
||||
decrypted_text += char
|
||||
|
||||
print(f"\n最终解密结果: {decrypted_text}")
|
||||
return decrypted_text
|
||||
|
||||
def get_encode_rule(self, ):
|
||||
encode_rule = """
|
||||
加密规则:
|
||||
|
||||
输入:
|
||||
- 明文: 仅包含大写字母的字符串,不含标点符号和空格。
|
||||
输出:
|
||||
- 密文: 大写字母字符串。
|
||||
准备:
|
||||
- 加密表 = {
|
||||
'A': '!', 'B': '@', 'C': '#', 'D': '$',
|
||||
'E': '%', 'F': '^', 'G': '&', 'H': '*',
|
||||
'I': '(', 'J': ')', 'K': '_', 'L': '+',
|
||||
'M': '=', 'N': '~', 'O': '?', 'P': '/',
|
||||
'Q': '0', 'R': ':', 'S': ';', 'T': '<',
|
||||
'U': '>', 'V': '1', 'W': '2', 'X': '3',
|
||||
'Y': '4', 'Z': '5'
|
||||
}
|
||||
加密步骤:
|
||||
- 对于每个给定的明文字符 p:
|
||||
- 如果 p 是大写字母且存在于加密表中:
|
||||
- 用加密表中对应的符号替换 p。
|
||||
"""
|
||||
return encode_rule
|
||||
|
||||
def get_decode_rule(self, ):
|
||||
decode_rule = """
|
||||
解密规则:
|
||||
|
||||
输入:
|
||||
- 密文: 大写字母字符串。
|
||||
输出:
|
||||
- 明文: 大写字母字符串。
|
||||
准备:
|
||||
- 加密表 = {
|
||||
'A': '!', 'B': '@', 'C': '#', 'D': '$',
|
||||
'E': '%', 'F': '^', 'G': '&', 'H': '*',
|
||||
'I': '(', 'J': ')', 'K': '_', 'L': '+',
|
||||
'M': '=', 'N': '~', 'O': '?', 'P': '/',
|
||||
'Q': '0', 'R': ':', 'S': ';', 'T': '<',
|
||||
'U': '>', 'V': '1', 'W': '2', 'X': '3',
|
||||
'Y': '4', 'Z': '5'
|
||||
}
|
||||
解密步骤 (与加密步骤完全相反):
|
||||
- 对于每个给定的密文字符 c:
|
||||
- 如果 c 是加密表中的符号且存在于加密表中:
|
||||
- 用加密表中对应的大写字母替换 c。
|
||||
"""
|
||||
return decode_rule
|
||||
112
internbootcamp/libs/cipher/KorPolybiusSquareCipherEnvironment.py
Executable file
112
internbootcamp/libs/cipher/KorPolybiusSquareCipherEnvironment.py
Executable file
|
|
@ -0,0 +1,112 @@
|
|||
from .BaseCipherEnvironment import BaseCipherEnvironment
|
||||
|
||||
polybius_square = [
|
||||
['R', 'T', 'X', 'F', 'S'],
|
||||
['W', 'C', 'M', 'V', 'H'],
|
||||
['Z', 'J', 'A', 'P', 'B'],
|
||||
['L', 'Q', 'Y', 'G', 'K'],
|
||||
['N', 'E', 'U', 'D', 'I']
|
||||
]
|
||||
|
||||
def find_position(char):
|
||||
for i in range(len(polybius_square)):
|
||||
for j in range(len(polybius_square[i])):
|
||||
if polybius_square[i][j] == char:
|
||||
return i + 1, j + 1
|
||||
return None
|
||||
|
||||
|
||||
class KorPolybiusSquareCipherEnvironment(BaseCipherEnvironment):
|
||||
def __init__(self, *args, **kwargs):
|
||||
problem_description = "Polybius Square Cipher from KOR-bench"
|
||||
super().__init__(problem_description, *args, **kwargs)
|
||||
|
||||
@property
|
||||
def cipher_name(self) -> str:
|
||||
return "Kor_rule4_PolybiusSquareCipher"
|
||||
|
||||
def encode(self, text, **kwargs):
|
||||
print(f"开始加密文本: {text}")
|
||||
# 转换为大写并只保留字母
|
||||
text = ''.join([c.upper() for c in text if c.isalpha()])
|
||||
print(f"预处理后的文本: {text}")
|
||||
|
||||
encrypted_text = ""
|
||||
print("开始逐字符加密:")
|
||||
for char in text:
|
||||
print(f"处理字符: {char}")
|
||||
if char == 'O':
|
||||
encrypted_text += '66'
|
||||
print(f"字符 {char} 不在Polybius方阵中,替换为: 66")
|
||||
else:
|
||||
row, col = find_position(char)
|
||||
if row and col:
|
||||
encrypted_text += f"{row}{col}"
|
||||
print(f"字符 {char} 在方阵中的位置是: 第{row}行第{col}列,替换为: {row}{col}")
|
||||
|
||||
print(f"最终加密结果: {encrypted_text}")
|
||||
return encrypted_text
|
||||
|
||||
def decode(self, text, **kwargs):
|
||||
print(f"开始解密文本: {text}")
|
||||
decrypted_text = ""
|
||||
i = 0
|
||||
print("开始逐对数字解密:")
|
||||
while i < len(text):
|
||||
if text[i:i+2] == '66':
|
||||
decrypted_text += 'O'
|
||||
print(f"遇到数字对: 66,解密为: O")
|
||||
i += 2
|
||||
elif text[i].isdigit():
|
||||
row = int(text[i])
|
||||
col = int(text[i+1])
|
||||
char = polybius_square[row-1][col-1]
|
||||
decrypted_text += char
|
||||
print(f"遇到数字对: {row}{col},对应方阵位置: 第{row}行第{col}列,解密为: {char}")
|
||||
i += 2
|
||||
|
||||
print(f"最终解密结果: {decrypted_text}")
|
||||
return decrypted_text
|
||||
|
||||
|
||||
def get_decode_rule(self, ):
|
||||
decode_rule = """
|
||||
解密规则:
|
||||
- 输入:
|
||||
- 密文: 字符串
|
||||
- 输出:
|
||||
- 明文: 大写字母字符串
|
||||
- 准备:
|
||||
- Polybius方阵(与加密相同)
|
||||
- 解密步骤(与加密步骤相反):
|
||||
- 对于密文中的每对数字CrCc:
|
||||
- 根据CrCc表示的行列号在Polybius方阵中找到对应字母
|
||||
- 如果CrCc=66,替换为"O"
|
||||
"""
|
||||
return decode_rule
|
||||
|
||||
def get_encode_rule(self, ):
|
||||
encode_rule = """
|
||||
加密规则:
|
||||
- 输入:
|
||||
- 明文: 大写字母字符串,不含标点和空格
|
||||
- 输出:
|
||||
- 密文: 大写字母字符串
|
||||
- 准备:
|
||||
- Polybius方阵:
|
||||
1 2 3 4 5
|
||||
1 R T X F S
|
||||
2 W C M V H
|
||||
3 Z J A P B
|
||||
4 L Q Y G K
|
||||
5 N E U D I
|
||||
|
||||
- 加密步骤:
|
||||
- 对于每个明文字符p:
|
||||
- 如果p是存在于Polybius方阵中的大写字母:
|
||||
- 用字符在方阵中的行号和列号(都从1开始计数)替换该字符
|
||||
- 特别地,字母O不存在于方阵中,用66替换
|
||||
"""
|
||||
return encode_rule
|
||||
|
||||
|
||||
148
internbootcamp/libs/cipher/KorPortaCipherEnvironment.py
Executable file
148
internbootcamp/libs/cipher/KorPortaCipherEnvironment.py
Executable file
|
|
@ -0,0 +1,148 @@
|
|||
from .BaseCipherEnvironment import BaseCipherEnvironment
|
||||
|
||||
class PortaCipher:
|
||||
def __init__(self, key):
|
||||
self.key = key.upper()
|
||||
self.alphabets = [
|
||||
'NOPQRSTUVWXYZABCDEFGHIJKLM',
|
||||
'ZNOPQRSTUVWXYBCDEFGHIJKLMA',
|
||||
'YZNOPQRSTUVWXCDEFGHIJKLMAB',
|
||||
'XYZNOPQRSTUVWDEFGHIJKLMABC',
|
||||
'WXYZNOPQRSTUVEFGHIJKLMABCD',
|
||||
'VWXYZNOPQRSTUFGHIJKLMABCDE',
|
||||
'UVWXYZNOPQRSTGHIJKLMABCDEF',
|
||||
'TUVWXYZNOPQRSHIJKLMABCDEFG',
|
||||
'STUVWXYZNOPQRIJKLMABCDEFGH',
|
||||
'RSTUVWXYZNOPQJKLMABCDEFGHI',
|
||||
'QRSTUVWXYZNOPKLMABCDEFGHIJ',
|
||||
'PQRSTUVWXYZNOLMABCDEFGHIJK',
|
||||
'OPQRSTUVWXYZNMABCDEFGHIJKL'
|
||||
]
|
||||
self.char_to_alphabet_index = {chr(i + ord('A')): i // 2 for i in range(26)}
|
||||
|
||||
def encrypt_char(self, char, key_char):
|
||||
index = self.char_to_alphabet_index[key_char]
|
||||
return self.alphabets[index][ord(char) - ord('A')]
|
||||
|
||||
def decrypt_char(self, char, key_char):
|
||||
index = self.char_to_alphabet_index[key_char]
|
||||
return chr(self.alphabets[index].index(char) + ord('A'))
|
||||
|
||||
def encrypt(self, plaintext):
|
||||
plaintext = plaintext.upper()
|
||||
ciphertext = []
|
||||
for i, char in enumerate(plaintext):
|
||||
if char.isalpha():
|
||||
key_char = self.key[i % len(self.key)]
|
||||
ciphertext.append(self.encrypt_char(char, key_char))
|
||||
else:
|
||||
ciphertext.append(char)
|
||||
return ''.join(ciphertext)
|
||||
|
||||
def decrypt(self, ciphertext):
|
||||
ciphertext = ciphertext.upper()
|
||||
plaintext = []
|
||||
for i, char in enumerate(ciphertext):
|
||||
if char.isalpha():
|
||||
key_char = self.key[i % len(self.key)]
|
||||
plaintext.append(self.decrypt_char(char, key_char))
|
||||
else:
|
||||
plaintext.append(char)
|
||||
return ''.join(plaintext)
|
||||
|
||||
|
||||
class KorPortaCipherEnvironment(BaseCipherEnvironment):
|
||||
def __init__(self, *args, **kwargs):
|
||||
problem_description = 'Portacipher from kor'
|
||||
super().__init__(problem_description, *args, **kwargs)
|
||||
|
||||
@property
|
||||
def cipher_name(self) -> str:
|
||||
return 'Kor_rule8_PortaCipher'
|
||||
|
||||
def encode(self, text, key):
|
||||
print(f"开始加密文本: {text}")
|
||||
print(f"使用密钥: {key}")
|
||||
|
||||
# 预处理文本,只保留字母并转为大写
|
||||
processed_text = ''.join([char.upper() for char in text if char.isalpha()])
|
||||
print(f"预处理后的文本: {processed_text}")
|
||||
|
||||
porta = PortaCipher(key)
|
||||
encoded_text = porta.encrypt(processed_text)
|
||||
|
||||
print("加密步骤:")
|
||||
for i, (p, c) in enumerate(zip(processed_text, encoded_text)):
|
||||
key_char = key[i % len(key)].upper()
|
||||
print(f" 第{i+1}个字符 {p} 使用密钥字符 {key_char}:")
|
||||
print(f" - 查找密钥字符 {key_char} 对应的替换表")
|
||||
print(f" - 将明文字符 {p} 替换为密文字符 {c}")
|
||||
|
||||
print(f"最终加密结果: {encoded_text}")
|
||||
return encoded_text
|
||||
|
||||
def decode(self, text, key):
|
||||
print(f"开始解密文本: {text}")
|
||||
print(f"使用密钥: {key}")
|
||||
|
||||
porta = PortaCipher(key)
|
||||
decoded_text = porta.decrypt(text)
|
||||
|
||||
print("解密步骤:")
|
||||
for i, (c, p) in enumerate(zip(text, decoded_text)):
|
||||
key_char = key[i % len(key)].upper()
|
||||
print(f" 第{i+1}个字符 {c} 使用密钥字符 {key_char}:")
|
||||
print(f" - 查找密钥字符 {key_char} 对应的替换表")
|
||||
print(f" - 将密文字符 {c} 还原为明文字符 {p}")
|
||||
|
||||
print(f"最终解密结果: {decoded_text}")
|
||||
return decoded_text
|
||||
|
||||
def get_encode_rule(self, ):
|
||||
return """加密规则:
|
||||
输入:
|
||||
- 明文: 大写字母字符串,不含标点和空格
|
||||
- 密钥: 用于选择替换表的字符串
|
||||
输出:
|
||||
- 密文: 大写字母字符串
|
||||
准备工作:
|
||||
- 密码替换表:
|
||||
使用以下13个密码替换表,每个表对应两个字母:
|
||||
AB: NOPQRSTUVWXYZABCDEFGHIJKLM
|
||||
CD: ZNOPQRSTUVWXYBCDEFGHIJKLMA
|
||||
EF: YZNOPQRSTUVWXCDEFGHIJKLMAB
|
||||
GH: XYZNOPQRSTUVWDEFGHIJKLMABC
|
||||
IJ: WXYZNOPQRSTUVEFGHIJKLMABCD
|
||||
KL: VWXYZNOPQRSTUFGHIJKLMABCDE
|
||||
MN: UVWXYZNOPQRSTGHIJKLMABCDEF
|
||||
OP: TUVWXYZNOPQRSHIJKLMABCDEFG
|
||||
QR: STUVWXYZNOPQRIJKLMABCDEFGH
|
||||
ST: RSTUVWXYZNOPQJKLMABCDEFGHI
|
||||
UV: QRSTUVWXYZNOPKLMABCDEFGHIJ
|
||||
WX: PQRSTUVWXYZNOLMABCDEFGHIJK
|
||||
YZ: OPQRSTUVWXYZNMABCDEFGHIJKL
|
||||
- 标准字母表:
|
||||
ABCDEFGHIJKLMNOPQRSTUVWXYZ
|
||||
加密步骤:
|
||||
- 将密钥中的每个字母与明文中的每个字母配对。如果密钥比明文短,重复使用密钥
|
||||
- 对于每个明文字符p:
|
||||
- 根据与之配对的密钥字母找到对应的密码替换表
|
||||
- 在标准字母表中找到p的位置,用密码替换表中相同位置的字母替换它"""
|
||||
|
||||
def get_decode_rule(self, ):
|
||||
return """解密规则:
|
||||
输入:
|
||||
- 密文: 大写字母字符串
|
||||
- 密钥: 用于选择替换表的字符串
|
||||
输出:
|
||||
- 明文: 大写字母字符串
|
||||
准备工作:
|
||||
- 密码替换表: (与加密相同)
|
||||
- 标准字母表: (与加密相同)
|
||||
解密步骤:
|
||||
- 将密钥中的每个字母与密文中的每个字母配对。如果密钥比密文短,重复使用密钥
|
||||
- 对于每个密文字符c:
|
||||
- 根据与之配对的密钥字母找到对应的密码替换表
|
||||
- 在密码替换表中找到c的位置,用标准字母表中相同位置的字母还原它"""
|
||||
|
||||
|
||||
97
internbootcamp/libs/cipher/KorRSACipherEnvironment.py
Executable file
97
internbootcamp/libs/cipher/KorRSACipherEnvironment.py
Executable file
|
|
@ -0,0 +1,97 @@
|
|||
from .BaseCipherEnvironment import BaseCipherEnvironment
|
||||
|
||||
class KorRSACipherEnvironment(BaseCipherEnvironment):
|
||||
def __init__(self, *args, **kwargs):
|
||||
problem_description = "RSA Cipher from kor-bench"
|
||||
super().__init__(problem_description, *args, **kwargs)
|
||||
|
||||
@property
|
||||
def cipher_name(self) -> str:
|
||||
return "Kor_rule23_RSACipher"
|
||||
|
||||
def encode(self, text, **kwargs):
|
||||
print("开始加密过程...")
|
||||
# 将输入转换为大写字母,去除标点和空格
|
||||
text = ''.join([char.upper() for char in text if char.isalpha()])
|
||||
print(f"处理后的输入文本: {text}")
|
||||
|
||||
# 设置加密参数
|
||||
e = 263
|
||||
n = 299
|
||||
print(f"使用参数: e={e}, n={n}")
|
||||
|
||||
ciphertext = []
|
||||
print("\n逐字符加密:")
|
||||
for char in text:
|
||||
x = ord(char)
|
||||
print(f"字符 {char} 的ASCII码为 {x}")
|
||||
y = pow(x, e, n)
|
||||
print(f"计算 {x}^{e} mod {n} = {y}")
|
||||
ciphertext.append(str(y))
|
||||
|
||||
encode_text = ','.join(ciphertext)
|
||||
print(f"\n最终加密结果: {encode_text}")
|
||||
return encode_text
|
||||
|
||||
def decode(self, text, **kwargs):
|
||||
print("开始解密过程...")
|
||||
print(f"收到的加密文本: {text}")
|
||||
|
||||
# 设置解密参数
|
||||
e = 263
|
||||
n = 299
|
||||
print(f"使用参数: e={e}, n={n}")
|
||||
|
||||
# 分割密文
|
||||
numbers = text.split(',')
|
||||
print(f"分割后的数字序列: {numbers}")
|
||||
|
||||
plaintext = []
|
||||
print("\n逐数字解密:")
|
||||
for num in numbers:
|
||||
c = int(num)
|
||||
z = pow(c, e, n)
|
||||
print(f"计算 {c}^{e} mod {n} = {z}")
|
||||
char = chr(z)
|
||||
print(f"对应的字符为: {char}")
|
||||
plaintext.append(char)
|
||||
|
||||
decode_text = ''.join(plaintext)
|
||||
print(f"\n最终解密结果: {decode_text}")
|
||||
return decode_text
|
||||
|
||||
def get_encode_rule(self, ):
|
||||
encode_rule = """
|
||||
加密规则:
|
||||
- 输入:
|
||||
- 明文: 仅包含大写字母的字符串,不含标点和空格
|
||||
- 输出:
|
||||
- 密文: 由逗号分隔的数字序列,例如"y1,y2,..."
|
||||
- 准备:
|
||||
- e: 263
|
||||
- n: 299
|
||||
- 加密步骤:
|
||||
- 对明文中的每个字母p:
|
||||
- 获取字母p对应的ASCII码的十进制数x
|
||||
- 计算x^e mod n作为该字母的密文数字y,这里^表示乘法运算
|
||||
- 最后,将所有y用逗号连接形成最终密文
|
||||
"""
|
||||
return encode_rule
|
||||
|
||||
def get_decode_rule(self, ):
|
||||
decode_rule = """
|
||||
解密规则:
|
||||
- 输入:
|
||||
- 密文: 由逗号分隔的数字序列,例如"y1,y2,..."
|
||||
- 输出:
|
||||
- 明文: 仅包含大写字母的字符串,不含标点和空格
|
||||
- 准备:
|
||||
- e: 263
|
||||
- n: 299
|
||||
- 解密步骤:
|
||||
- 对密文中的每个数字c:
|
||||
- 计算z = c^e mod n,这里^表示乘法运算
|
||||
- 根据z的十进制值,使用ASCII码找到对应的字母作为明文字母p
|
||||
- 最后,将所有p连接得到最终明文
|
||||
"""
|
||||
return decode_rule
|
||||
173
internbootcamp/libs/cipher/KorRedefenceFigureCipherEnvironment.py
Executable file
173
internbootcamp/libs/cipher/KorRedefenceFigureCipherEnvironment.py
Executable file
|
|
@ -0,0 +1,173 @@
|
|||
from .BaseCipherEnvironment import BaseCipherEnvironment
|
||||
|
||||
class KorRedefenceFigureCipherEnvironment(BaseCipherEnvironment):
|
||||
def __init__(self, *args, **kwargs):
|
||||
problem_description = "Redefence Figure Cipher from kor"
|
||||
super().__init__(problem_description, *args, **kwargs)
|
||||
|
||||
@property
|
||||
def cipher_name(self) -> str:
|
||||
return "Kor_rule16_RedefenceFigureCipher"
|
||||
|
||||
def encode(self, text, **kwargs):
|
||||
print("加密步骤开始:")
|
||||
# 将输入转换为大写字母,去除空格和标点
|
||||
text = ''.join([char.upper() for char in text if char.isalpha()])
|
||||
print(f"1. 处理输入文本为大写字母: {text}")
|
||||
|
||||
key = "ABCDE"
|
||||
textlen = len(text)
|
||||
rows = len(key)
|
||||
print(f"2. 准备{rows}行矩阵用于填充")
|
||||
|
||||
matrix = [['' for _ in range(textlen)] for _ in range(rows)]
|
||||
dict = {}
|
||||
direction = True
|
||||
finish = False
|
||||
|
||||
index = 0
|
||||
cindex = 0
|
||||
matrix[0][index] = text[cindex]
|
||||
print(f"3. 在第一行第一个位置填入第一个字母: {text[cindex]}")
|
||||
cindex += 1
|
||||
|
||||
print("4. 开始交替向下和向上填充字母:")
|
||||
while(cindex < len(text)):
|
||||
if direction:
|
||||
print(" 向下填充:")
|
||||
for i in range(1, rows):
|
||||
if i == 1 and cindex != 1:
|
||||
matrix[i-1][index] = '#'
|
||||
print(f" 在第{i}行填入#")
|
||||
if cindex == len(text) - 1:
|
||||
matrix[i][index] = text[cindex]
|
||||
print(f" 在第{i+1}行填入最后一个字母: {text[cindex]}")
|
||||
finish = True
|
||||
break
|
||||
elif i == rows-1:
|
||||
matrix[i][index] = text[cindex]
|
||||
print(f" 在第{i+1}行填入: {text[cindex]}")
|
||||
cindex += 1
|
||||
index += 1
|
||||
direction = False
|
||||
else:
|
||||
matrix[i][index] = text[cindex]
|
||||
print(f" 在第{i+1}行填入: {text[cindex]}")
|
||||
cindex += 1
|
||||
else:
|
||||
print(" 向上填充:")
|
||||
for k in range(rows-2, -1, -1):
|
||||
if k == rows-2:
|
||||
matrix[k+1][index] = '#'
|
||||
print(f" 在第{k+2}行填入#")
|
||||
if cindex == len(text)-1:
|
||||
matrix[k][index] = text[cindex]
|
||||
print(f" 在第{k+1}行填入最后一个字母: {text[cindex]}")
|
||||
finish = True
|
||||
break
|
||||
elif k == 0:
|
||||
matrix[k][index] = text[cindex]
|
||||
print(f" 在第{k+1}行填入: {text[cindex]}")
|
||||
cindex += 1
|
||||
index += 1
|
||||
direction = True
|
||||
else:
|
||||
matrix[k][index] = text[cindex]
|
||||
print(f" 在第{k+1}行填入: {text[cindex]}")
|
||||
cindex += 1
|
||||
if finish:
|
||||
break
|
||||
|
||||
print("\n5. 最终矩阵:")
|
||||
for row in matrix:
|
||||
print(' ' + ' '.join([c if c != '' else '_' for c in row]))
|
||||
|
||||
print("\n6. 按行读取并添加*号分隔符")
|
||||
index = 0
|
||||
for char in key:
|
||||
dict[char] = matrix[index]
|
||||
index += 1
|
||||
myKeys = list(dict.keys())
|
||||
myKeys.sort()
|
||||
sorted_dict = {i: dict[i] for i in myKeys}
|
||||
result = ""
|
||||
for v in sorted_dict.values():
|
||||
for i in range(len(v)):
|
||||
if i != len(v)-1:
|
||||
result += v[i]
|
||||
elif i == len(v)-1:
|
||||
result += "*"
|
||||
continue
|
||||
print(f"最终密文: {result}")
|
||||
return result
|
||||
|
||||
def decode(self, text, **kwargs):
|
||||
print("解密步骤开始:")
|
||||
print(f"1. 接收到的密文: {text}")
|
||||
|
||||
key = "ABCDE"
|
||||
textlen = len(text)
|
||||
rows = len(key)
|
||||
rail = [['' for _ in range(textlen)] for _ in range(rows)]
|
||||
|
||||
print("2. 根据*号分割密文")
|
||||
segments = text.split('*')
|
||||
print(f" 分割得到{len(segments)}个部分")
|
||||
|
||||
print("3. 将分割后的内容填入矩阵:")
|
||||
for i, segment in enumerate(segments):
|
||||
print(f" 第{i+1}行: {segment}")
|
||||
for j, char in enumerate(segment):
|
||||
rail[i][j] = char
|
||||
|
||||
print("\n4. 交替读取矩阵内容:")
|
||||
decrypted_message = []
|
||||
for i in range(textlen):
|
||||
if i % 2 == 0:
|
||||
print(f" 向下读取第{i+1}列")
|
||||
for row in range(rows):
|
||||
decrypted_message.append(rail[row][i])
|
||||
else:
|
||||
print(f" 向上读取第{i+1}列")
|
||||
for row in range(rows - 1, -1, -1):
|
||||
decrypted_message.append(rail[row][i])
|
||||
|
||||
print("5. 移除#号获得最终明文")
|
||||
decrypted_text = ''.join(char for char in decrypted_message if char != '#')
|
||||
print(f"解密结果: {decrypted_text}")
|
||||
return decrypted_text
|
||||
|
||||
def get_encode_rule(self, ):
|
||||
encode_rule = """
|
||||
加密规则:
|
||||
- 输入:
|
||||
- 明文: 不含标点和空格的大写字母字符串
|
||||
- 输出:
|
||||
- 密文: 不含标点和空格的字符串
|
||||
- 准备:
|
||||
- 行数: 5
|
||||
- 加密步骤:
|
||||
- 在第一行第一个位置填入第一个明文字母
|
||||
- 两种填充方式:
|
||||
- 向下填充: 在第一行填入"#"(除去第一列,因为第一个位置已经填入明文字母),然后从第二行到最后一行(第五行)向下填充明文
|
||||
- 向上填充: 从最后一行(第五行)到第二行向上填充明文,然后在第一行填入"#"
|
||||
- 对于明文中的每个字母(除了已经填在第一个位置的第一个字母),先进行向下填充,填满一列,然后转向上填充,再转向下填充,如此交替进行,直到所有字母都被填入
|
||||
- 填写完成后,逐行读取,读取每行内容后都添加一个*号,标记行的结束;然后读取第二行内容,依此类推,读取所有行,形成最终密文
|
||||
"""
|
||||
return encode_rule
|
||||
|
||||
def get_decode_rule(self, ):
|
||||
decode_rule = """
|
||||
解密规则:
|
||||
- 输入:
|
||||
- 密文: 不含标点和空格的字符串
|
||||
- 输出:
|
||||
- 明文: 不含标点和空格的大写字母字符串
|
||||
- 准备:
|
||||
- 行数: 5
|
||||
- 解密步骤:
|
||||
- 根据密文中的*(不包括*号),可以分成五组,依次填入五行。得到恢复的五行数据
|
||||
- 然后按照先向下读再向上读交替的方式读取所有列。得到未清理的消息
|
||||
- 从未清理的消息中删除#,得到最终明文
|
||||
"""
|
||||
return decode_rule
|
||||
164
internbootcamp/libs/cipher/KorRotatingGridCipherEnvironment.py
Executable file
164
internbootcamp/libs/cipher/KorRotatingGridCipherEnvironment.py
Executable file
|
|
@ -0,0 +1,164 @@
|
|||
from .BaseCipherEnvironment import BaseCipherEnvironment
|
||||
|
||||
import numpy as np
|
||||
|
||||
def create_grid(template, message_segment):
|
||||
size = template.shape[0]
|
||||
grid = np.full((size, size), '', dtype=str)
|
||||
idx = 0
|
||||
for _ in range(4):
|
||||
for i in range(size):
|
||||
for j in range(size):
|
||||
if (template[i, j]==0) and idx < len(message_segment):
|
||||
grid[i, j] = message_segment[idx]
|
||||
idx += 1
|
||||
template = np.rot90(template)
|
||||
return grid
|
||||
|
||||
|
||||
class KorRotatingGridCipherEnvironment(BaseCipherEnvironment):
|
||||
def __init__(self, *args, **kwargs):
|
||||
problem_description = "Rotating Grid Cipher from kor"
|
||||
super().__init__(problem_description, *args, **kwargs)
|
||||
|
||||
@property
|
||||
def cipher_name(self) -> str:
|
||||
return "Kor_rule18_RotatingGridCipher"
|
||||
|
||||
def encode(self, text, **kwargs):
|
||||
return text
|
||||
|
||||
def encode(self, text, **kwargs):
|
||||
# 处理输入文本,只保留字母并转为大写
|
||||
text = ''.join([char.upper() for char in text if char.isalpha()])
|
||||
print(f"处理后的输入文本: {text}")
|
||||
|
||||
template = np.array([
|
||||
[1, 1, 1, 1],
|
||||
[1, 1, 0, 0],
|
||||
[1, 1, 1, 0],
|
||||
[0, 1, 1, 1]
|
||||
], dtype=bool)
|
||||
|
||||
print("使用的模板:")
|
||||
print("▮ ▮ ▮ ▮")
|
||||
print("▮ ▮ ▯ ▯")
|
||||
print("▮ ▮ ▮ ▯")
|
||||
print("▯ ▮ ▮ ▮")
|
||||
|
||||
size = template.shape[0]
|
||||
segment_length = size * size
|
||||
ciphertext = ''
|
||||
|
||||
print("\n开始加密过程:")
|
||||
for i in range(0, len(text), segment_length):
|
||||
print(f"\n处理第{i//segment_length + 1}个块:")
|
||||
segment = text[i:i + segment_length]
|
||||
print(f"当前块的文本: {segment}")
|
||||
|
||||
if len(segment) < segment_length:
|
||||
print(f"文本长度不足{segment_length},用#补充")
|
||||
segment += '#' * (segment_length - len(segment))
|
||||
print(f"补充后的文本: {segment}")
|
||||
|
||||
filled_grid = create_grid(template, segment)
|
||||
print("\n填充后的网格:")
|
||||
print(filled_grid)
|
||||
|
||||
block_cipher = ''.join(filled_grid.flatten())
|
||||
print(f"当前块的密文: {block_cipher}")
|
||||
ciphertext += block_cipher
|
||||
|
||||
print(f"\n最终密文: {ciphertext}")
|
||||
return ciphertext
|
||||
|
||||
def decode(self, text, **kwargs):
|
||||
template = np.array([
|
||||
[1, 1, 1, 1],
|
||||
[1, 1, 0, 0],
|
||||
[1, 1, 1, 0],
|
||||
[0, 1, 1, 1]
|
||||
], dtype=bool)
|
||||
|
||||
print("使用的模板:")
|
||||
print("▮ ▮ ▮ ▮")
|
||||
print("▮ ▮ ▯ ▯")
|
||||
print("▮ ▮ ▮ ▯")
|
||||
print("▯ ▮ ▮ ▮")
|
||||
|
||||
size = template.shape[0]
|
||||
segment_length = size * size
|
||||
message = ''
|
||||
|
||||
print("\n开始解密过程:")
|
||||
for i in range(0, len(text), segment_length):
|
||||
print(f"\n处理第{i//segment_length + 1}个块:")
|
||||
current_segment = text[i:i + segment_length]
|
||||
print(f"当前块的密文: {current_segment}")
|
||||
|
||||
filled_grid = np.array(list(current_segment)).reshape((size, size))
|
||||
print("\n重构的网格:")
|
||||
print(filled_grid)
|
||||
|
||||
segment = []
|
||||
temp_template = template.copy()
|
||||
for rotation in range(4):
|
||||
print(f"\n第{rotation + 1}次旋转后读取:")
|
||||
for i in range(size):
|
||||
for j in range(size):
|
||||
if temp_template[i, j]==0:
|
||||
segment.append(filled_grid[i, j])
|
||||
print(f"从位置({i},{j})读取字符: {filled_grid[i, j]}")
|
||||
temp_template = np.rot90(temp_template)
|
||||
|
||||
block_message = ''.join(segment)
|
||||
print(f"当前块解密结果: {block_message}")
|
||||
message += block_message
|
||||
|
||||
message = message.rstrip('#')
|
||||
print(f"\n最终明文: {message}")
|
||||
return message
|
||||
|
||||
def get_encode_rule(self, ):
|
||||
return """加密规则:
|
||||
- 输入:
|
||||
- 明文: 不含标点和空格的大写字母字符串
|
||||
- 输出:
|
||||
- 密文: 不含标点和空格的大写字母字符串
|
||||
- 准备:
|
||||
- 网格和模板:
|
||||
- 准备一个空白网格和一个带孔的模板(栅栏)
|
||||
- 使用的模板是:
|
||||
▮ ▮ ▮ ▮
|
||||
▮ ▮ ▯ ▯
|
||||
▮ ▮ ▮ ▯
|
||||
▯ ▮ ▮ ▮
|
||||
其中白色的是孔,将模板放在空白网格上,只通过白色孔洞,在网格的对应位置填入字符。
|
||||
- 加密步骤:
|
||||
- 将明文逐个分成16个字母的块(如果明文少于16个长度则为一个块)
|
||||
- 对每个块执行以下加密操作:
|
||||
- 将带孔的模板放在空白网格上
|
||||
- 通过模板中的孔按顺序填入明文字母
|
||||
- 模板总共有四个孔,所以填完四个字母后,需要将模板逆时针旋转90度
|
||||
- 重复填充可见孔中的明文下一个字母并旋转模板,直到整个网格完全填满。这将执行4次填充+旋转,最终模板会转回原始模板。如果消息不足以填满整个网格,用填充字符(如'#')补充
|
||||
- 网格填满后,按行读取网格内容作为该块的加密消息
|
||||
- 进入下一个块时,清空网格内容并重做整个填充和旋转操作
|
||||
最后,将所有块的加密消息连接在一起作为最终密文。"""
|
||||
|
||||
def get_decode_rule(self, ):
|
||||
return """解密规则:
|
||||
- 输入:
|
||||
- 密文: 不含标点和空格的大写字母字符串
|
||||
- 输出:
|
||||
- 明文: 不含标点和空格的大写字母字符串
|
||||
- 准备:
|
||||
- 网格和模板(与加密相同)
|
||||
- 解密步骤(与加密步骤完全相反):
|
||||
- 将密文逐个分成16个字母的块
|
||||
- 对每个块执行以下操作:
|
||||
- 将16个字母按行写入填满网格
|
||||
- 将带孔的模板放在填满的网格上
|
||||
- 读取通过孔可见的字母获得部分明文消息
|
||||
- 由于只有四个孔,此时需要将模板逆时针旋转90度读取下一组字母
|
||||
- 重复读取步骤四次以获得这块解密消息
|
||||
- 连接所有块的解密消息得到最终明文。"""
|
||||
172
internbootcamp/libs/cipher/KorSBOXCipherEnvironment.py
Executable file
172
internbootcamp/libs/cipher/KorSBOXCipherEnvironment.py
Executable file
|
|
@ -0,0 +1,172 @@
|
|||
from .BaseCipherEnvironment import BaseCipherEnvironment
|
||||
|
||||
S_BOX = {
|
||||
0x00: 0x0F, 0x01: 0x0A, 0x02: 0x07, 0x03: 0x05,
|
||||
0x04: 0x09, 0x05: 0x03, 0x06: 0x0D, 0x07: 0x00,
|
||||
0x08: 0x0E, 0x09: 0x08, 0x0A: 0x04, 0x0B: 0x06,
|
||||
0x0C: 0x01, 0x0D: 0x02, 0x0E: 0x0B, 0x0F: 0x0C
|
||||
}
|
||||
|
||||
INV_S_BOX = {
|
||||
0x0F: 0x00, 0x0A: 0x01, 0x07: 0x02, 0x05: 0x03,
|
||||
0x09: 0x04, 0x03: 0x05, 0x0D: 0x06, 0x00: 0x07,
|
||||
0x0E: 0x08, 0x08: 0x09, 0x04: 0x0A, 0x06: 0x0B,
|
||||
0x01: 0x0C, 0x02: 0x0D, 0x0B: 0x0E, 0x0C: 0x0F
|
||||
}
|
||||
|
||||
KEY = b'1234567890ABCDEF'
|
||||
|
||||
def xor_bytes(a, b):
|
||||
return bytes(x ^ y for x, y in zip(a, b))
|
||||
|
||||
|
||||
def substitute(bytes_data, box):
|
||||
result = bytearray()
|
||||
for byte in bytes_data:
|
||||
high_nibble = (byte >> 4) & 0x0F
|
||||
low_nibble = byte & 0x0F
|
||||
substituted_high = box[high_nibble]
|
||||
substituted_low = box[low_nibble]
|
||||
combined_byte = (substituted_high << 4) | substituted_low
|
||||
result.append(combined_byte)
|
||||
return bytes(result)
|
||||
|
||||
def simple_permute(bytes_data):
|
||||
return bytes(((b << 1) & 0xFF) | ((b >> 7) & 0x01) for b in bytes_data)
|
||||
|
||||
def inverse_permute(bytes_data):
|
||||
return bytes(((b >> 1) & 0xFF) | ((b << 7) & 0x80) for b in bytes_data)
|
||||
|
||||
|
||||
class KorSBOXCipherEnvironment(BaseCipherEnvironment):
|
||||
def __init__(self, *args, **kwargs):
|
||||
problem_description = "SBOX Cipher from kor-bench"
|
||||
super().__init__(problem_description, *args, **kwargs)
|
||||
|
||||
@property
|
||||
def cipher_name(self) -> str:
|
||||
return "Kor_rule22_SBOXCipher"
|
||||
|
||||
def encode(self, text, **kwargs):
|
||||
print("开始加密过程...")
|
||||
# 将输入转换为大写字母和空格
|
||||
text = ''.join(char.upper() for char in text if char.isalnum() or char.isspace())
|
||||
print(f"1. 规范化输入文本: {text}")
|
||||
|
||||
# 使用给定的加密代码进行加密
|
||||
print("2. 开始分块处理...")
|
||||
blocks = [text[i:i+8] for i in range(0, len(text), 8)]
|
||||
encrypted_blocks = []
|
||||
|
||||
for i, block in enumerate(blocks):
|
||||
print(f"\n处理第{i+1}个块: {block}")
|
||||
block = block.ljust(8, '\x00')
|
||||
print(f" - 填充后的块: {block}")
|
||||
|
||||
state = xor_bytes(block.encode('ascii'), KEY)
|
||||
print(f" - 与密钥XOR后: {state.hex().upper()}")
|
||||
|
||||
state = substitute(state, S_BOX)
|
||||
print(f" - S盒替换后: {state.hex().upper()}")
|
||||
|
||||
state = simple_permute(state)
|
||||
print(f" - 左移置换后: {state.hex().upper()}")
|
||||
|
||||
state = xor_bytes(state, KEY)
|
||||
print(f" - 最终与密钥XOR后: {state.hex().upper()}")
|
||||
|
||||
encrypted_blocks.append(''.join(f'{b:02X}' for b in state))
|
||||
|
||||
result = ''.join(encrypted_blocks)
|
||||
print(f"\n最终加密结果: {result}")
|
||||
return result
|
||||
|
||||
def decode(self, text, **kwargs):
|
||||
print("开始解密过程...")
|
||||
print(f"1. 接收到的密文: {text}")
|
||||
|
||||
print("2. 开始分块处理...")
|
||||
blocks = [text[i:i+16] for i in range(0, len(text), 16)]
|
||||
decrypted_blocks = []
|
||||
|
||||
for i, block in enumerate(blocks):
|
||||
print(f"\n处理第{i+1}个块: {block}")
|
||||
|
||||
state = bytes.fromhex(block)
|
||||
print(f" - 转换为字节: {state.hex().upper()}")
|
||||
|
||||
state = xor_bytes(state, KEY)
|
||||
print(f" - 与密钥XOR后: {state.hex().upper()}")
|
||||
|
||||
state = inverse_permute(state)
|
||||
print(f" - 右移置换后: {state.hex().upper()}")
|
||||
|
||||
state = substitute(state, INV_S_BOX)
|
||||
print(f" - 逆S盒替换后: {state.hex().upper()}")
|
||||
|
||||
state = xor_bytes(state, KEY)
|
||||
print(f" - 最终与密钥XOR后: {state.hex().upper()}")
|
||||
|
||||
decrypted_blocks.append(state.decode('ascii').rstrip('\x00'))
|
||||
|
||||
result = ''.join(decrypted_blocks)
|
||||
print(f"\n最终解密结果: {result}")
|
||||
return result
|
||||
|
||||
def get_encode_rule(self, ):
|
||||
return """加密规则:
|
||||
- 输入:
|
||||
- 明文: 大写字母和空格组成的字符串
|
||||
- 输出:
|
||||
- 密文: 表示加密数据的十六进制字符串(其中A-E需要大写)
|
||||
- 准备:
|
||||
- 固定密钥
|
||||
- KEY = b'1234567890ABCDEF'
|
||||
- S盒
|
||||
- S_BOX = {
|
||||
0x00: 0x0F, 0x01: 0x0A, 0x02: 0x07, 0x03: 0x05,
|
||||
0x04: 0x09, 0x05: 0x03, 0x06: 0x0D, 0x07: 0x00,
|
||||
0x08: 0x0E, 0x09: 0x08, 0x0A: 0x04, 0x0B: 0x06,
|
||||
0x0C: 0x01, 0x0D: 0x02, 0x0E: 0x0B, 0x0F: 0x0C
|
||||
}
|
||||
- 加密步骤:
|
||||
1. 填充: 如果明文长度不是8字节的倍数,用\\x00(空字符)填充使其长度成为8字节的倍数
|
||||
2. 分块: 将填充后的明文分成8字节的块
|
||||
3. 块加密:
|
||||
- 转换为字节: 使用ASCII编码将每个块转换为字节
|
||||
- 与密钥XOR: 字节块与固定密钥进行XOR运算
|
||||
- 替换: 使用S盒替换每个字节的高4位和低4位并拼接
|
||||
- 置换: 通过将每个字节左移1位进行简单置换
|
||||
- 与密钥XOR: 置换后的字节块再次与固定密钥进行XOR运算
|
||||
4. 十六进制编码: 将加密后的字节块转换为十六进制字符串
|
||||
5. 拼接: 将所有加密块的十六进制字符串拼接形成最终密文"""
|
||||
|
||||
def get_decode_rule(self, ):
|
||||
return """解密规则:
|
||||
- 输入:
|
||||
- 密文: 表示加密数据的十六进制字符串(其中A-E需要大写)
|
||||
- 输出:
|
||||
- 明文: 大写字母和空格组成的字符串
|
||||
- 准备:
|
||||
- 固定密钥
|
||||
- KEY = b'1234567890ABCDEF'
|
||||
- 逆S盒
|
||||
- INV_S_BOX = {
|
||||
0x0F: 0x00, 0x0A: 0x01, 0x07: 0x02, 0x05: 0x03,
|
||||
0x09: 0x04, 0x03: 0x05, 0x0D: 0x06, 0x00: 0x07,
|
||||
0x0E: 0x08, 0x08: 0x09, 0x04: 0x0A, 0x06: 0x0B,
|
||||
0x01: 0x0C, 0x02: 0x0D, 0x0B: 0x0E, 0x0C: 0x0F
|
||||
}
|
||||
- 解密步骤:
|
||||
1. 分块: 将密文分成16字符(8字节)的块
|
||||
2. 块解密:
|
||||
- 转换为字节: 将每个块从十六进制字符串转换为字节
|
||||
- 与密钥XOR: 字节块与固定密钥进行XOR运算
|
||||
- 逆置换: 通过将每个字节右移1位进行逆置换
|
||||
- 替换: 使用逆S盒替换块中字节的高4位和低4位并拼接
|
||||
- 与密钥XOR: 字节块再次与固定密钥进行XOR运算
|
||||
3. 转换为文本: 使用ASCII解码将解密后的字节块转换回文本
|
||||
4. 移除填充: 从解密后的明文末尾移除填充字符(\\x00)
|
||||
5. 拼接: 将所有解密块拼接形成最终明文"""
|
||||
|
||||
|
||||
98
internbootcamp/libs/cipher/KorSHACipherEnvironment.py
Executable file
98
internbootcamp/libs/cipher/KorSHACipherEnvironment.py
Executable file
|
|
@ -0,0 +1,98 @@
|
|||
from .BaseCipherEnvironment import BaseCipherEnvironment
|
||||
|
||||
import hashlib
|
||||
|
||||
def generate_key():
|
||||
secret = "SECRET_KEY"
|
||||
sha256 = hashlib.sha256()
|
||||
sha256.update(secret.encode('utf-8'))
|
||||
return sha256.digest()
|
||||
|
||||
|
||||
class KorSHACipherEnvironment(BaseCipherEnvironment):
|
||||
def __init__(self, *args, **kwargs):
|
||||
problem_description = "SHA Cipher from kor-bench"
|
||||
super().__init__(problem_description, *args, **kwargs)
|
||||
|
||||
@property
|
||||
def cipher_name(self) -> str:
|
||||
return "Kor_rule25_SHACipher"
|
||||
|
||||
def encode(self, text, **kwargs):
|
||||
print("开始加密过程...")
|
||||
print(f"原始输入文本: {text}")
|
||||
|
||||
# 处理输入文本,只保留字母并转换为大写
|
||||
text = ''.join([char.upper() for char in text if char.isalpha()])
|
||||
print(f"处理后的输入文本: {text}")
|
||||
|
||||
# 生成密钥
|
||||
key = generate_key()
|
||||
print(f"生成的SHA-256密钥: {key.hex()}")
|
||||
|
||||
# 将文本转换为字节序列
|
||||
plaintext_bytes = text.encode('utf-8')
|
||||
print(f"文本转换为字节序列: {plaintext_bytes}")
|
||||
|
||||
# 使用XOR运算加密
|
||||
print("开始XOR加密...")
|
||||
ciphertext_bytes = bytes([b ^ key[i % len(key)] for i, b in enumerate(plaintext_bytes)])
|
||||
print(f"加密后的字节序列: {ciphertext_bytes}")
|
||||
|
||||
# 转换为十六进制字符串
|
||||
result = ciphertext_bytes.hex()
|
||||
print(f"最终加密结果(十六进制): {result}")
|
||||
|
||||
return result
|
||||
|
||||
def decode(self,text, **kwargs):
|
||||
print("开始解密过程...")
|
||||
print(f"加密的十六进制文本: {text}")
|
||||
|
||||
# 生成密钥
|
||||
key = generate_key()
|
||||
print(f"生成的SHA-256密钥: {key.hex()}")
|
||||
|
||||
# 将十六进制转换为字节序列
|
||||
ciphertext_bytes = bytes.fromhex(text)
|
||||
print(f"十六进制转换为字节序列: {ciphertext_bytes}")
|
||||
|
||||
# 使用XOR运算解密
|
||||
print("开始XOR解密...")
|
||||
plaintext_bytes = bytes([b ^ key[i % len(key)] for i, b in enumerate(ciphertext_bytes)])
|
||||
print(f"解密后的字节序列: {plaintext_bytes}")
|
||||
|
||||
# 转换为文本
|
||||
result = plaintext_bytes.decode('utf-8')
|
||||
print(f"最终解密结果: {result}")
|
||||
|
||||
return result
|
||||
|
||||
def get_encode_rule(self,):
|
||||
return """加密规则:
|
||||
- 输入:
|
||||
- 明文: 仅包含大写字母的字符串,不含标点符号和空格
|
||||
- 输出:
|
||||
- 密文: 十六进制字符串(包含小写字母a-e)
|
||||
- 准备:
|
||||
- 密钥(SHA哈希值)
|
||||
- 对"SECRET_KEY"执行SHA-256运算,得到'73ef2a4edd7a7fbf07fd5f6faf99674dc0c25a025fd74c221f4c35849e5c0fb3'
|
||||
- 加密步骤:
|
||||
- 将明文字符串转换为字节序列(ASCII编码)
|
||||
- 使用密钥对每个字节进行异或(XOR)运算加密。重复使用密钥使其长度与明文字节数相同
|
||||
- 将加密后的字节序列转换为十六进制字符串作为密文输出"""
|
||||
|
||||
def get_decode_rule(self,):
|
||||
return """解密规则:
|
||||
- 输入:
|
||||
- 密文: 十六进制字符串(包含小写字母a-e)
|
||||
- 输出:
|
||||
- 明文: 仅包含大写字母的字符串,不含标点符号和空格
|
||||
- 准备:
|
||||
- 密钥(与加密相同,是通过SHA-256获得的哈希值)
|
||||
- 解密步骤:
|
||||
- 将密文字符串转换为字节序列
|
||||
- 使用密钥对每个字节进行异或(XOR)运算解密(解密过程与加密过程相同)
|
||||
- 将解密后的字节序列转换为明文字符串"""
|
||||
|
||||
|
||||
223
internbootcamp/libs/cipher/KorSolitaireCipherEnvironment.py
Executable file
223
internbootcamp/libs/cipher/KorSolitaireCipherEnvironment.py
Executable file
|
|
@ -0,0 +1,223 @@
|
|||
from .BaseCipherEnvironment import BaseCipherEnvironment
|
||||
|
||||
|
||||
import random
|
||||
from typing import Callable, List
|
||||
import functools
|
||||
|
||||
LETTERS = ['J', 'D', 'W', 'O', 'T', 'R', 'A', 'C', 'X', 'Q', 'M', 'F', 'Y',
|
||||
'E', 'Z', 'G', 'U', 'K', 'P', 'V', 'B', 'S', 'H', 'N', 'L', 'I']
|
||||
|
||||
LETTER_TO_NUM_MAP = {}
|
||||
for i, letter in enumerate(LETTERS):
|
||||
LETTER_TO_NUM_MAP[letter] = i
|
||||
|
||||
input_key = [9, 25, 44, 38, 40, 22, 11, 36, 13, 39, 18, 42, 10, 53, 26, 12, 1, 16, 3, 43, 37, 17, 30, 4, 28, 48, 27, 41, 32, 15, 47, 29, 20, 51, 6, 7, 52, 34, 35, 5, 50, 9, 54, 46, 23, 31, 24, 14, 8, 33, 2, 49, 45, 21]
|
||||
|
||||
|
||||
def move_joker_a(cards: List[int]) -> list:
|
||||
return move_joker(len(cards) - 1, cards)
|
||||
|
||||
def move_joker_b(cards: List[int]) -> list:
|
||||
return move_joker(len(cards), cards)
|
||||
|
||||
def move_joker(joker: int, cards: List[int]) -> List[int]:
|
||||
def wraparound(n: int) -> int:
|
||||
if n >= len(cards):
|
||||
return n % len(cards) + 1
|
||||
return n
|
||||
|
||||
cards = list(cards)
|
||||
jump = 2 if joker is len(cards) else 1
|
||||
index = cards.index(joker)
|
||||
cards.insert(wraparound(index + jump), cards.pop(index))
|
||||
return cards
|
||||
|
||||
def triple_cut_by_jokers(cards: List[int]) -> list:
|
||||
joker_a = len(cards) - 1
|
||||
joker_b = len(cards)
|
||||
return triple_cut((cards.index(joker_a), cards.index(joker_b)), cards)
|
||||
|
||||
def triple_cut(cut_indices: tuple, cards: list) -> List[int]:
|
||||
lower, higher = sorted(cut_indices)
|
||||
return cards[higher + 1:] + cards[lower:higher + 1] + cards[:lower]
|
||||
|
||||
def count_cut(cards: List[int]) -> List[int]:
|
||||
last = len(cards) - 1
|
||||
value = cards[last]
|
||||
if is_joker(value, cards):
|
||||
return list(cards)
|
||||
return cards[value:last] + cards[:value] + [cards[last]]
|
||||
|
||||
def get_keystream_value(cards: List[int]) -> int:
|
||||
index = cards[0] if not is_joker(cards[0], cards) else len(cards) - 1
|
||||
return cards[index]
|
||||
|
||||
def is_joker(value: int, cards: List[int]) -> bool:
|
||||
return value > len(cards) - 2
|
||||
|
||||
|
||||
class KorSolitaireCipherEnvironment(BaseCipherEnvironment):
|
||||
def __init__(self, *args, **kwargs):
|
||||
problem_description = "Solitaire Cipher from kor-bench"
|
||||
super().__init__(problem_description, *args, **kwargs)
|
||||
|
||||
@property
|
||||
def cipher_name(self) -> str:
|
||||
return "Kor_rule6_SolitaireCipher"
|
||||
|
||||
def encode(self, text, **kwargs):
|
||||
# 将输入转换为大写字母,去除标点和空格
|
||||
text = ''.join([c.upper() for c in text if c.isalpha()])
|
||||
print(f"处理后的输入文本: {text}")
|
||||
|
||||
print("开始加密过程:")
|
||||
cards = list(input_key)
|
||||
output = []
|
||||
|
||||
for i, char in enumerate(text):
|
||||
print(f"\n处理第{i+1}个字符 '{char}':")
|
||||
# 获取字母位置值
|
||||
x = LETTER_TO_NUM_MAP[char]
|
||||
print(f"字符'{char}'在字母表中的位置是: {x}")
|
||||
|
||||
# 生成密钥流值
|
||||
print("生成密钥流值:")
|
||||
print("1. 移动A王牌下移一位")
|
||||
cards = move_joker_a(cards)
|
||||
print("2. 移动B王牌下移两位")
|
||||
cards = move_joker_b(cards)
|
||||
print("3. 以王牌为界进行三切")
|
||||
cards = triple_cut_by_jokers(cards)
|
||||
print("4. 根据底牌进行计数切牌")
|
||||
cards = count_cut(cards)
|
||||
|
||||
y = get_keystream_value(cards)
|
||||
while is_joker(y, cards):
|
||||
print("获得的是王牌值,重新生成密钥流值")
|
||||
cards = move_joker_a(cards)
|
||||
cards = move_joker_b(cards)
|
||||
cards = triple_cut_by_jokers(cards)
|
||||
cards = count_cut(cards)
|
||||
y = get_keystream_value(cards)
|
||||
|
||||
print(f"生成的密钥流值是: {y}")
|
||||
|
||||
# 计算加密位置
|
||||
z = (x + y) % 26
|
||||
print(f"加密计算: ({x} + {y}) % 26 = {z}")
|
||||
|
||||
# 获取加密字母
|
||||
cipher_char = LETTERS[z]
|
||||
print(f"加密后的字符是: {cipher_char}")
|
||||
output.append(cipher_char)
|
||||
|
||||
result = ''.join(output)
|
||||
print(f"\n最终加密结果: {result}")
|
||||
return result
|
||||
|
||||
def decode(self, text, **kwargs):
|
||||
print(f"开始解密密文: {text}")
|
||||
|
||||
cards = list(input_key)
|
||||
output = []
|
||||
|
||||
for i, char in enumerate(text):
|
||||
print(f"\n处理第{i+1}个字符 '{char}':")
|
||||
# 获取密文字母位置
|
||||
z = LETTER_TO_NUM_MAP[char]
|
||||
print(f"密文字符'{char}'在字母表中的位置是: {z}")
|
||||
|
||||
# 生成密钥流值
|
||||
print("生成密钥流值:")
|
||||
print("1. 移动A王牌下移一位")
|
||||
cards = move_joker_a(cards)
|
||||
print("2. 移动B王牌下移两位")
|
||||
cards = move_joker_b(cards)
|
||||
print("3. 以王牌为界进行三切")
|
||||
cards = triple_cut_by_jokers(cards)
|
||||
print("4. 根据底牌进行计数切牌")
|
||||
cards = count_cut(cards)
|
||||
|
||||
y = get_keystream_value(cards)
|
||||
while is_joker(y, cards):
|
||||
print("获得的是王牌值,重新生成密钥流值")
|
||||
cards = move_joker_a(cards)
|
||||
cards = move_joker_b(cards)
|
||||
cards = triple_cut_by_jokers(cards)
|
||||
cards = count_cut(cards)
|
||||
y = get_keystream_value(cards)
|
||||
|
||||
print(f"生成的密钥流值是: {y}")
|
||||
|
||||
# 计算原文位置
|
||||
x = (z - y) % 26
|
||||
print(f"解密计算: ({z} - {y}) % 26 = {x}")
|
||||
|
||||
# 获取原文字母
|
||||
plain_char = LETTERS[x]
|
||||
print(f"解密后的字符是: {plain_char}")
|
||||
output.append(plain_char)
|
||||
|
||||
result = ''.join(output)
|
||||
print(f"\n最终解密结果: {result}")
|
||||
return result
|
||||
|
||||
def get_encode_rule(self, ):
|
||||
return """加密规则:
|
||||
- 输入:
|
||||
- 明文: 大写字母字符串,不含标点和空格
|
||||
- 输出:
|
||||
- 密文: 大写字母字符串
|
||||
- 准备:
|
||||
- LETTERS = ['J', 'D', 'W', 'O', 'T', 'R', 'A', 'C', 'X', 'Q', 'M', 'F', 'Y', 'E', 'Z', 'G', 'U', 'K', 'P', 'V', 'B', 'S', 'H', 'N', 'L', 'I']
|
||||
- 将每个字母与其在LETTERS中的位置关联(从0开始):
|
||||
J->0, D->1, W->2, O->3, T->4, R->5, A->6, C->7, X->8, Q->9, M->10, F->11, Y->12, E->13, Z->14, G->15, U->16, K->17, P->18, V->19, B->20, S->21, H->22, N->23, L->24, I->25
|
||||
- 初始卡牌序列:
|
||||
- 54张卡牌的列表,包括52张花色牌和2张可区分的王牌(A王牌和B王牌)。花色牌按四种花色顺序编号1-52,王牌值为53和54。
|
||||
- [9, 25, 44, 38, 40, 22, 11, 36, 13, 39, 18, 42, 10, 53, 26, 12, 1, 16, 3, 43, 37, 17, 30, 4, 28, 48, 27, 41, 32, 15, 47, 29, 20, 51, 6, 7, 52, 34, 35, 5, 50, 9, 54, 46, 23, 31, 24, 14, 8, 33, 2, 49, 45, 21]
|
||||
- 密钥流算法:
|
||||
该算法通过移动卡牌生成密钥流值。算法是确定性的,意味着密钥流值仅取决于卡牌的初始顺序。卡牌组被视为循环数组,允许需要移到底部的卡牌绕到顶部。
|
||||
|
||||
执行以下步骤生成密钥流的一个字符:
|
||||
1. 找到A王牌并下移一位。如果是最后一张牌,则成为第二张牌。不能成为第一张牌。
|
||||
2. 找到B王牌并下移两位。如果是倒数第二张牌,则绕到第二位。如果是最后一张牌,则成为第三张牌。不能成为第一张牌。
|
||||
3. 进行"三切":用王牌作为边界将牌组分成三部分,然后交换顶部和底部。王牌本身及其之间的牌保持不变。
|
||||
4. 进行"计数切":检查牌组底牌。如果是王牌(53/54),其值固定为53。从牌组顶部取出该数量的牌,插入到最后一张牌的上方。
|
||||
5. 查看顶牌的值。同样,任何王牌计为53。计算该牌下方的位置数,使用该位置的牌值作为下一个密钥流值。如果计算出的牌是王牌,忽略它并重复密钥流算法。
|
||||
6. 返回生成的密钥流值
|
||||
- 加密步骤:
|
||||
- cards=初始卡牌序列
|
||||
- 对每个明文字符p:
|
||||
- 使用字母表将p转换为对应的位置值x(从0开始)
|
||||
- 使用初始卡牌序列为p生成密钥流值y:
|
||||
- y, cards = 密钥流算法(cards)
|
||||
- 该算法修改卡牌顺序,下次执行使用新顺序
|
||||
- 当密钥流值y加到位置值x时,应用模26运算得到z:
|
||||
- z=(y+x) % 26
|
||||
- 使用LETTERS列表返回对应位置z的字母
|
||||
- 将其附加到密文"""
|
||||
|
||||
def get_decode_rule(self, ):
|
||||
return """解密规则:
|
||||
- 输入:
|
||||
- 密文: 大写字母字符串
|
||||
- 输出:
|
||||
- 明文: 大写字母字符串
|
||||
- 准备:
|
||||
- LETTERS = ['J', 'D', 'W', 'O', 'T', 'R', 'A', 'C', 'X', 'Q', 'M', 'F', 'Y', 'E', 'Z', 'G', 'U', 'K', 'P', 'V', 'B', 'S', 'H', 'N', 'L', 'I']
|
||||
- 将每个字母与其在LETTERS中的位置关联(从0开始):
|
||||
J->0, D->1, W->2, O->3, T->4, R->5, A->6, C->7, X->8, Q->9, M->10, F->11, Y->12, E->13, Z->14, G->15, U->16, K->17, P->18, V->19, B->20, S->21, H->22, N->23, L->24, I->25
|
||||
- 初始卡牌序列(与加密相同)
|
||||
- 密钥流算法(与加密相同)
|
||||
- 解密步骤(与加密步骤完全相反):
|
||||
- cards=初始卡牌序列
|
||||
- 对每个密文字符c:
|
||||
- 使用LETTERS将c转换为对应的位置值z(从0开始)
|
||||
- 为c生成密钥流值y:
|
||||
- y, cards = 密钥流算法(cards)
|
||||
- 该算法修改卡牌顺序,下次执行使用新顺序
|
||||
- 从密文字符c计算原始位置值x:
|
||||
- x=(z-y) mod 26
|
||||
- 使用LETTERS列表返回对应位置x的字母
|
||||
- 将其附加到解密明文"""
|
||||
141
internbootcamp/libs/cipher/KorTranspositionCipherEnvironment.py
Executable file
141
internbootcamp/libs/cipher/KorTranspositionCipherEnvironment.py
Executable file
|
|
@ -0,0 +1,141 @@
|
|||
from .BaseCipherEnvironment import BaseCipherEnvironment
|
||||
|
||||
class KorTranspositionCipherEnvironment(BaseCipherEnvironment):
|
||||
def __init__(self, *args, **kwargs):
|
||||
problem_description = "Transposition Cipher from kor-bench"
|
||||
super().__init__(problem_description, *args, **kwargs)
|
||||
|
||||
@property
|
||||
def cipher_name(self) -> str:
|
||||
return "Kor_rule20_TranspositionCipher"
|
||||
|
||||
def encode(self, text, **kwargs):
|
||||
# 将输入转换为大写字母
|
||||
text = ''.join([char.upper() for char in text if char.isalpha()])
|
||||
print(f"处理后的输入文本: {text}")
|
||||
|
||||
# 定义转置序列
|
||||
transposed_sequence = [1, 4, 0, 6, 5, 2, 3]
|
||||
print(f"使用转置序列: {transposed_sequence}")
|
||||
|
||||
# 计算需要的行数
|
||||
rows = (len(text) + 6) // 7
|
||||
print(f"需要 {rows} 行来存放文本")
|
||||
|
||||
# 创建网格并填充
|
||||
grid = []
|
||||
index = 0
|
||||
for i in range(rows):
|
||||
row = []
|
||||
for j in range(7):
|
||||
if index < len(text):
|
||||
row.append(text[index])
|
||||
index += 1
|
||||
else:
|
||||
row.append('$')
|
||||
grid.append(row)
|
||||
print("原始网格:")
|
||||
for row in grid:
|
||||
print(''.join(row))
|
||||
|
||||
# 根据转置序列调整列顺序
|
||||
new_grid = []
|
||||
for i in range(rows):
|
||||
new_row = []
|
||||
for col in transposed_sequence:
|
||||
new_row.append(grid[i][col])
|
||||
new_grid.append(new_row)
|
||||
|
||||
print("转置后的网格:")
|
||||
for row in new_grid:
|
||||
print(''.join(row))
|
||||
|
||||
# 读取结果
|
||||
result = ''
|
||||
for row in new_grid:
|
||||
result += ''.join(row)
|
||||
|
||||
print(f"最终加密结果: {result}")
|
||||
return result
|
||||
|
||||
def decode(self, text, **kwargs):
|
||||
print(f"需要解密的文本: {text}")
|
||||
|
||||
# 定义转置序列
|
||||
transposed_sequence = [1, 4, 0, 6, 5, 2, 3]
|
||||
print(f"使用转置序列: {transposed_sequence}")
|
||||
|
||||
# 计算行数
|
||||
rows = (len(text) + 6) // 7
|
||||
print(f"需要 {rows} 行来存放文本")
|
||||
|
||||
# 创建网格并填充
|
||||
grid = []
|
||||
index = 0
|
||||
for i in range(rows):
|
||||
row = []
|
||||
for j in range(7):
|
||||
row.append(text[index])
|
||||
index += 1
|
||||
grid.append(row)
|
||||
|
||||
print("加密的网格:")
|
||||
for row in grid:
|
||||
print(''.join(row))
|
||||
|
||||
# 还原原始顺序
|
||||
original_positions = [0] * 7
|
||||
for i, pos in enumerate(transposed_sequence):
|
||||
original_positions[pos] = i
|
||||
|
||||
# 重建原始网格
|
||||
original_grid = []
|
||||
for i in range(rows):
|
||||
new_row = []
|
||||
for col in original_positions:
|
||||
new_row.append(grid[i][col])
|
||||
original_grid.append(new_row)
|
||||
|
||||
print("还原后的网格:")
|
||||
for row in original_grid:
|
||||
print(''.join(row))
|
||||
|
||||
# 读取结果并移除填充字符
|
||||
result = ''
|
||||
for row in original_grid:
|
||||
for char in row:
|
||||
if char != '$':
|
||||
result += char
|
||||
|
||||
print(f"解密结果: {result}")
|
||||
return result
|
||||
|
||||
def get_encode_rule(self, ):
|
||||
return """加密规则:
|
||||
- 输入:
|
||||
- 明文: 不含标点和空格的大写字母字符串
|
||||
- 输出:
|
||||
- 密文: 不含标点和空格的字符串
|
||||
- 准备:
|
||||
- 转置序列表:
|
||||
- [1, 4, 0, 6, 5, 2, 3]
|
||||
- 转置序列表用于按顺序逐行写入明文,然后根据转置序列表调整列的顺序,使每行中的字符按给定顺序排列。
|
||||
- 列从0开始计数。
|
||||
- 加密步骤:
|
||||
- [1, 4, 0, 6, 5, 2, 3]转置序列表共7位,表示一行应写入7个字母。
|
||||
- 按顺序逐行写入明文,每行7个。当不足7个时,最后一行用$填充。可以得到一个写入网格。
|
||||
- 根据转置序列表调整列的顺序,即现在列的顺序为[原列1,原列4,原列0,原列6,原列5,原列2,原列3],可以得到调整列顺序后的网格。
|
||||
- 逐行读取网格并连接起来得到最终密文。(注意需要保留$)"""
|
||||
|
||||
def get_decode_rule(self, ):
|
||||
return """解密规则:
|
||||
- 输入:
|
||||
- 密文: 不含标点和空格的字符串
|
||||
- 输出:
|
||||
- 明文: 不含标点和空格的大写字母字符串
|
||||
- 准备:
|
||||
- 转置序列表(与加密相同)
|
||||
- 解密步骤:
|
||||
- 按顺序逐行写入密文,每行7个字母。
|
||||
- 逐行读取,但读取每行时,先读取对应0的第2列的字符,然后读取对应1的第0列的字符,然后读取对应2的第6列的字符,依此类推。
|
||||
- 最终逐行读取信息,去掉末尾的$,即可得到解密后的明文。"""
|
||||
122
internbootcamp/libs/cipher/KorXORCipherEnvironment.py
Executable file
122
internbootcamp/libs/cipher/KorXORCipherEnvironment.py
Executable file
|
|
@ -0,0 +1,122 @@
|
|||
from .BaseCipherEnvironment import BaseCipherEnvironment
|
||||
|
||||
key = '10101010'
|
||||
permutation = (2, 0, 3, 1, 4, 6, 5, 7)
|
||||
inverse_permutation = (1, 3, 0, 2, 4, 6, 5, 7)
|
||||
|
||||
def xor(bits1, bits2):
|
||||
return ''.join(['1' if b1 != b2 else '0' for b1, b2 in zip(bits1, bits2)])
|
||||
|
||||
def permute(bits, perm_table):
|
||||
return ''.join([bits[i] for i in perm_table])
|
||||
|
||||
|
||||
class KorXORCipherEnvironment(BaseCipherEnvironment):
|
||||
def __init__(self, *args, **kwargs):
|
||||
problem_description = "XOR Cipher from kor-bench"
|
||||
super().__init__(problem_description, *args, **kwargs)
|
||||
|
||||
@property
|
||||
def cipher_name(self) -> str:
|
||||
return "Kor_rule21_XORCipher"
|
||||
|
||||
def encode(self, text, **kwargs):
|
||||
# 移除非字母字符并转为大写
|
||||
text = ''.join([char.upper() for char in text if char.isalpha()])
|
||||
print(f"1. 输入文本处理为: {text}")
|
||||
|
||||
encrypted_bits = []
|
||||
for char in text:
|
||||
print(f"\n处理字符: {char}")
|
||||
binary_plaintext = format(ord(char), '08b')
|
||||
print(f"2. 转换为8位二进制: {binary_plaintext}")
|
||||
|
||||
xor_result = xor(binary_plaintext, key * (len(binary_plaintext) // len(key) + 1))[:len(binary_plaintext)]
|
||||
print(f"3. 与密钥进行XOR运算: {xor_result}")
|
||||
|
||||
permuted = permute(xor_result, permutation)
|
||||
print(f"4. 应用置换表: {permuted}")
|
||||
|
||||
encrypted_bits.append(permuted)
|
||||
|
||||
encrypted_binary_string = ''.join(encrypted_bits)
|
||||
print(f"\n最终加密结果: {encrypted_binary_string}")
|
||||
return encrypted_binary_string
|
||||
|
||||
def decode(self, text, **kwargs):
|
||||
print(f"1. 接收到的加密文本: {text}")
|
||||
|
||||
decrypted_chars = []
|
||||
num_chars = len(text) // 8
|
||||
for i in range(num_chars):
|
||||
binary_chunk = text[i*8:(i+1)*8]
|
||||
print(f"\n处理8位二进制块: {binary_chunk}")
|
||||
|
||||
permuted_bits = permute(binary_chunk, inverse_permutation)
|
||||
print(f"2. 应用逆置换: {permuted_bits}")
|
||||
|
||||
xor_result = xor(permuted_bits, key * (len(permuted_bits) // len(key) + 1))[:len(permuted_bits)]
|
||||
print(f"3. 与密钥进行XOR运算: {xor_result}")
|
||||
|
||||
decrypted_char = chr(int(xor_result, 2))
|
||||
print(f"4. 转换为字符: {decrypted_char}")
|
||||
|
||||
decrypted_chars.append(decrypted_char)
|
||||
|
||||
result = ''.join(decrypted_chars)
|
||||
print(f"\n最终解密结果: {result}")
|
||||
return result
|
||||
|
||||
def get_encode_rule(self, ):
|
||||
encode_rule = """
|
||||
加密规则:
|
||||
- 输入:
|
||||
- 明文: 仅包含大写字母(A-Z)的字符串,不含标点和空格
|
||||
- 输出:
|
||||
- 密文: 仅包含0和1的二进制字符串
|
||||
- 准备:
|
||||
- 固定密钥: 8位二进制字符串(例如'10101010')
|
||||
- 置换表:
|
||||
- 置换表: (2, 0, 3, 1, 4, 6, 5, 7)
|
||||
- 逆置换表: (1, 3, 0, 2, 4, 6, 5, 7)
|
||||
- 加密步骤:
|
||||
1. 将每个字符转换为二进制:
|
||||
- 将每个字符转换为ASCII值
|
||||
- 将ASCII值转换为8位二进制字符串
|
||||
2. XOR运算:
|
||||
- 对字符的8位二进制表示与固定密钥进行XOR运算
|
||||
- 如果需要,重复密钥以匹配二进制表示的长度
|
||||
3. 置换:
|
||||
- 对XOR结果应用置换表得到每个字符的最终加密二进制字符串
|
||||
4. 合并二进制字符串:
|
||||
- 将所有字符的二进制字符串连接形成最终密文
|
||||
"""
|
||||
return encode_rule
|
||||
|
||||
def get_decode_rule(self, ):
|
||||
decode_rule = """
|
||||
解密规则:
|
||||
- 输入:
|
||||
- 密文: 仅包含0和1的二进制字符串
|
||||
- 输出:
|
||||
- 明文: 仅包含大写字母(A-Z)的字符串,不含标点和空格
|
||||
- 准备:
|
||||
- 固定密钥: 与加密使用的相同8位二进制字符串(例如'10101010')
|
||||
- 置换表:
|
||||
- 置换表: (2, 0, 3, 1, 4, 6, 5, 7)
|
||||
- 逆置换表: (1, 3, 0, 2, 4, 6, 5, 7)
|
||||
- 解密步骤:
|
||||
1. 将密文分块:
|
||||
- 将二进制密文分成8位一组,每组代表一个加密字符
|
||||
2. 逆置换:
|
||||
- 对每个8位块应用逆置换表以还原加密时的置换
|
||||
3. XOR运算:
|
||||
- 对置换后的二进制块与固定密钥进行XOR运算
|
||||
4. 二进制转字符:
|
||||
- 将得到的二进制字符串转换为十进制值
|
||||
- 将十进制值转换为对应的ASCII字符
|
||||
5. 合并字符:
|
||||
- 将每个二进制块得到的字符连接形成最终明文
|
||||
"""
|
||||
return decode_rule
|
||||
|
||||
88
internbootcamp/libs/cipher/TapCodeEnvironment.py
Executable file
88
internbootcamp/libs/cipher/TapCodeEnvironment.py
Executable file
|
|
@ -0,0 +1,88 @@
|
|||
from .BaseCipherEnvironment import BaseCipherEnvironment
|
||||
|
||||
class TapCodeEnvironment(BaseCipherEnvironment):
|
||||
def __init__(self, *args, **kwargs):
|
||||
problem_description = ''
|
||||
super().__init__(problem_description, *args, **kwargs)
|
||||
|
||||
@property
|
||||
def cipher_name(self) -> str:
|
||||
return "TapCode"
|
||||
|
||||
def encode(self, text):
|
||||
# 定义Tap Code字母表,C和K合并
|
||||
tap_code_table = [['A', 'B', 'C', 'D', 'E'],
|
||||
['F', 'G', 'H', 'I', 'J'],
|
||||
['L', 'M', 'N', 'O', 'P'],
|
||||
['Q', 'R', 'S', 'T', 'U'],
|
||||
['V', 'W', 'X', 'Y', 'Z']]
|
||||
|
||||
# 创建字母表索引的字典,方便快速查找
|
||||
letter_to_position = {}
|
||||
for i in range(len(tap_code_table)):
|
||||
for j in range(len(tap_code_table[i])):
|
||||
letter_to_position[tap_code_table[i][j]] = (i + 1, j + 1)
|
||||
|
||||
# 将待加密的文字全部转换为大写,C和K视为同一个字母
|
||||
text = text.upper().replace('K', 'C')
|
||||
encrypted_message = []
|
||||
step_counter = 1
|
||||
|
||||
# 对输入文本进行逐个字母的加密
|
||||
words = text.split()
|
||||
for word in words:
|
||||
encrypted_word = []
|
||||
for char in word:
|
||||
if char in letter_to_position:
|
||||
row, col = letter_to_position[char]
|
||||
encrypted_word.append('.' * row + ' ' + '.' * col)
|
||||
print(
|
||||
f"步骤 {step_counter}:正在加密字母 '{char}',它位于第 {row} 行第 {col} 列,编码为 '{'.' * row} {'.' * col}'")
|
||||
step_counter += 1
|
||||
encrypted_message.append(' '.join(encrypted_word))
|
||||
print(f"最终步骤:加密完成,加密后的消息是:{' '.join(encrypted_message)}")
|
||||
|
||||
# 使用 / 分隔不同单词的tap code
|
||||
return ' / '.join(encrypted_message)
|
||||
|
||||
|
||||
def decode(self, text):
|
||||
# 定义Tap Code字母表,C和K合并
|
||||
tap_code_table = [['A', 'B', 'C', 'D', 'E'],
|
||||
['F', 'G', 'H', 'I', 'J'],
|
||||
['L', 'M', 'N', 'O', 'P'],
|
||||
['Q', 'R', 'S', 'T', 'U'],
|
||||
['V', 'W', 'X', 'Y', 'Z']]
|
||||
|
||||
# 将tap code拆分为各个单词的编码
|
||||
words = text.split(' / ')
|
||||
decrypted_message = []
|
||||
step_counter = 1
|
||||
|
||||
# 对每个单词的编码进行解码
|
||||
for word in words:
|
||||
if word == '':
|
||||
continue
|
||||
letters = word.split(' ')
|
||||
for pair in letters:
|
||||
row_dots, col_dots = pair.split(' ')
|
||||
row = len(row_dots)
|
||||
col = len(col_dots)
|
||||
decrypted_char = tap_code_table[row - 1][col - 1]
|
||||
decrypted_message.append(decrypted_char)
|
||||
print(f"步骤 {step_counter}:正在解码 '{pair}',它表示第 {row} 行第 {col} 列,对应的字母是 '{decrypted_char}'")
|
||||
step_counter += 1
|
||||
decrypted_message.append(' ')
|
||||
print(f"最终步骤:解码完成,解码后的消息是:{''.join(decrypted_message)}")
|
||||
|
||||
# 将解码后的字母组合成完整字符串
|
||||
return ''.join(decrypted_message).strip()
|
||||
|
||||
|
||||
def get_encode_rule(self):
|
||||
return "Tap Code 是一种简单的密码技术,每个字母由一个点模式表示。模式通过计算行和列中的点数来编码。例如,字母 'A' 由第一行和第一列的一个点表示。"
|
||||
|
||||
|
||||
def get_decode_rule(self):
|
||||
return "要解码 Tap Code,需要计算每一行和每一列中的点数。通过查找表格中的位置,可以确定对应的字母。"
|
||||
|
||||
206
internbootcamp/libs/cipher/TrifidCipherEnvironment.py
Executable file
206
internbootcamp/libs/cipher/TrifidCipherEnvironment.py
Executable file
|
|
@ -0,0 +1,206 @@
|
|||
from .BaseCipherEnvironment import BaseCipherEnvironment
|
||||
|
||||
class TrifidCipherEnvironment(BaseCipherEnvironment):
|
||||
def __init__(self, *args, **kwargs):
|
||||
problem_description = ''
|
||||
super().__init__(problem_description, *args, **kwargs)
|
||||
|
||||
def encode(self, text):
|
||||
"""
|
||||
Trifid Cipher 加密算法实现
|
||||
|
||||
解题方案:
|
||||
1. 定义3x3x3立方体的布局,每个字母对应一个唯一的三维坐标 (层, 列, 行)。
|
||||
2. 过滤掉明文中的非字母字符,并将其转换为大写。
|
||||
3. 将每个字母转换为其对应的三维坐标,并分别存储层、列、行坐标。
|
||||
4. 将所有层坐标、列坐标、行坐标分别合并成一个字符串。
|
||||
5. 按照每三个字符一组的方式重新组合坐标。
|
||||
6. 根据新的坐标组在立方体中找到对应的字母,生成密文。
|
||||
"""
|
||||
|
||||
# 定义3x3x3立方体的布局
|
||||
cube = [
|
||||
['A', 'B', 'C'], # 第1层
|
||||
['D', 'E', 'F'],
|
||||
['G', 'H', 'I'],
|
||||
['J', 'K', 'L'], # 第2层
|
||||
['M', 'N', 'O'],
|
||||
['P', 'Q', 'R'],
|
||||
['S', 'T', 'U'], # 第3层
|
||||
['V', 'W', 'X'],
|
||||
['Y', 'Z', '.']
|
||||
]
|
||||
|
||||
# 打印立方体布局
|
||||
print("立方体布局:")
|
||||
for layer in range(3):
|
||||
print(f"第{layer + 1}层:")
|
||||
for row in range(3):
|
||||
print(' '.join(cube[layer * 3 + row]))
|
||||
print()
|
||||
|
||||
# Step 1: 过滤掉非字母字符并转换为大写
|
||||
filtered_text = ''.join(filter(str.isalpha, text)).upper()
|
||||
print(f"Step 1: 过滤掉非字母字符并转换为大写: {filtered_text}")
|
||||
|
||||
# 用于存储层、列、行坐标
|
||||
layer_coords = []
|
||||
column_coords = []
|
||||
row_coords = []
|
||||
|
||||
# Step 2: 获取每个字符的坐标
|
||||
print("Step 2: 获取每个字符的坐标:")
|
||||
for char in filtered_text:
|
||||
found = False
|
||||
for layer in range(3):
|
||||
for row in range(3):
|
||||
for col in range(3):
|
||||
if cube[layer * 3 + row][col] == char:
|
||||
layer_coords.append(str(layer + 1))
|
||||
column_coords.append(str(col + 1))
|
||||
row_coords.append(str(row + 1))
|
||||
found = True
|
||||
break
|
||||
if found:
|
||||
break
|
||||
if found:
|
||||
break
|
||||
print(f" {char} -> 层: {layer_coords[-1]}, 列: {column_coords[-1]}, 行: {row_coords[-1]}")
|
||||
|
||||
# Step 3: 合并坐标
|
||||
combined_layer_coords = ''.join(layer_coords)
|
||||
combined_column_coords = ''.join(column_coords)
|
||||
combined_row_coords = ''.join(row_coords)
|
||||
print(f"Step 3: 合并坐标:")
|
||||
print(f" 层坐标: {combined_layer_coords}")
|
||||
print(f" 列坐标: {combined_column_coords}")
|
||||
print(f" 行坐标: {combined_row_coords}")
|
||||
|
||||
# Step 4: 重组坐标
|
||||
combined_coords = combined_layer_coords + combined_column_coords + combined_row_coords
|
||||
new_coords = [combined_coords[i:i + 3] for i in range(0, len(combined_coords), 3)]
|
||||
print(f"Step 4: 重组坐标: {new_coords}")
|
||||
|
||||
# Step 5: 根据新坐标获取密文
|
||||
text = ''
|
||||
print("Step 5: 根据新坐标获取密文:")
|
||||
for coord in new_coords:
|
||||
layer = int(coord[0]) - 1
|
||||
col = int(coord[1]) - 1
|
||||
row = int(coord[2]) - 1
|
||||
index = layer * 3 + row
|
||||
letter = cube[index][col]
|
||||
text += letter
|
||||
print(f" {coord} -> {letter}")
|
||||
|
||||
return text
|
||||
|
||||
def get_encode_rule(self):
|
||||
return """加密方案概述:
|
||||
1. 过滤掉非字母字符并转换为大写。
|
||||
2. 将每个字母转换为对应的3D坐标。
|
||||
3. 将3D坐标重新组合,每三个字符一组。
|
||||
4. 根据新的坐标组在3D立方体中找到对应的字母,生成密文。
|
||||
5. 按照加密逻辑,将密文输出。
|
||||
"""
|
||||
|
||||
|
||||
def decode(self, text):
|
||||
# 解题方案说明
|
||||
# print("解题方案概述:")
|
||||
# print("1. 将密文转换为大写。")
|
||||
# print("2. 将密文中的每个字母映射到Trifid立方体中对应的3D坐标。")
|
||||
# print("3. 将所有坐标连接成一个字符串。")
|
||||
# print("4. 将连接后的坐标组织成一个3xN的矩阵。")
|
||||
# print("5. 转置3xN的矩阵。")
|
||||
# print("6. 从转置后的矩阵中重构原始坐标。")
|
||||
# print("7. 将重构的坐标映射回相应的字母。")
|
||||
# print("8. 将字母组合成明文信息。\n")
|
||||
|
||||
# 步骤1: 创建字母到坐标的映射
|
||||
letter_to_coords = {
|
||||
'A': (1, 1, 1), 'B': (1, 2, 1), 'C': (1, 3, 1),
|
||||
'D': (1, 1, 2), 'E': (1, 2, 2), 'F': (1, 3, 2),
|
||||
'G': (1, 1, 3), 'H': (1, 2, 3), 'I': (1, 3, 3),
|
||||
'J': (2, 1, 1), 'K': (2, 2, 1), 'L': (2, 3, 1),
|
||||
'M': (2, 1, 2), 'N': (2, 2, 2), 'O': (2, 3, 2),
|
||||
'P': (2, 1, 3), 'Q': (2, 2, 3), 'R': (2, 3, 3),
|
||||
'S': (3, 1, 1), 'T': (3, 2, 1), 'U': (3, 3, 1),
|
||||
'V': (3, 1, 2), 'W': (3, 2, 2), 'X': (3, 3, 2),
|
||||
'Y': (3, 1, 3), 'Z': (3, 2, 3), '.': (3, 3, 3)
|
||||
}
|
||||
|
||||
# 步骤2: 创建坐标到字母的逆映射
|
||||
coords_to_letter = {v: k for k, v in letter_to_coords.items()}
|
||||
|
||||
# 步骤3: 转换密文为大写
|
||||
text = text.upper()
|
||||
print(f"步骤1: 将密文转换为大写: {text}")
|
||||
|
||||
# 步骤4: 将密文转换为坐标序列
|
||||
coords_sequence = ''.join([
|
||||
''.join(map(str, letter_to_coords[char]))
|
||||
for char in text
|
||||
])
|
||||
print(f"步骤2: 将每个字母转换为坐标: {coords_sequence}")
|
||||
|
||||
# 步骤5: 计算每行的长度
|
||||
n = len(coords_sequence) // 3
|
||||
print(f"步骤3: 计算列数: {n}")
|
||||
|
||||
# 步骤6: 将坐标序列重新组织成3xN的矩阵
|
||||
coords_matrix = [coords_sequence[i:i + n] for i in range(0, len(coords_sequence), n)]
|
||||
print("步骤4: 将坐标组织成3xN的矩阵:")
|
||||
for row in coords_matrix:
|
||||
print(row)
|
||||
|
||||
# 步骤7: 转置坐标矩阵
|
||||
transposed_matrix = [''.join(row) for row in zip(*coords_matrix)]
|
||||
print("步骤5: 转置矩阵:")
|
||||
for row in transposed_matrix:
|
||||
print(row)
|
||||
|
||||
# 定义3x3x3立方体的布局
|
||||
cube = [
|
||||
['A', 'B', 'C'], # 第1层
|
||||
['D', 'E', 'F'],
|
||||
['G', 'H', 'I'],
|
||||
['J', 'K', 'L'], # 第2层
|
||||
['M', 'N', 'O'],
|
||||
['P', 'Q', 'R'],
|
||||
['S', 'T', 'U'], # 第3层
|
||||
['V', 'W', 'X'],
|
||||
['Y', 'Z', '.']
|
||||
]
|
||||
|
||||
# 打印立方体布局
|
||||
print("立方体布局:")
|
||||
for layer in range(3):
|
||||
print(f"第{layer + 1}层:")
|
||||
for row in range(3):
|
||||
print(' '.join(cube[layer * 3 + row]))
|
||||
print()
|
||||
|
||||
# 步骤8: 将转置后的坐标矩阵重新组合成坐标列表
|
||||
combined_coords = [tuple(map(int, [transposed_matrix[i][0], transposed_matrix[i][1], transposed_matrix[i][2]])) for
|
||||
i in range(n)]
|
||||
print(f"步骤6: 组合转置后的坐标: {combined_coords}")
|
||||
|
||||
# 步骤9: 将坐标转换回原文
|
||||
text = ''.join([coords_to_letter[coord] for coord in combined_coords])
|
||||
print(f"步骤7: 将坐标转换回字母: {text}")
|
||||
|
||||
return text
|
||||
|
||||
def get_decode_rule(self):
|
||||
return """解密方案概述:
|
||||
1. 将密文转换为大写字母。
|
||||
2. 将密文转换为对应的3D坐标。
|
||||
3. 将3D坐标重新组合,每三个字符一组。
|
||||
4. 根据新的坐标组在3D立方体中找到对应的字母,生成明文。
|
||||
5. 按照解密逻辑,将明文输出。
|
||||
"""
|
||||
|
||||
@property
|
||||
def cipher_name(self) -> str:
|
||||
return "TrifidCipher"
|
||||
106
internbootcamp/libs/cipher/__init__.py
Executable file
106
internbootcamp/libs/cipher/__init__.py
Executable file
|
|
@ -0,0 +1,106 @@
|
|||
from .BaseEnvironment import *
|
||||
|
||||
from .CeaserCipherEnvironment import *
|
||||
cipher_env_list = [CeaserCipherEnvironment]
|
||||
|
||||
from .TrifidCipherEnvironment import *
|
||||
cipher_env_list.append(TrifidCipherEnvironment)
|
||||
|
||||
from .Asc2Environment import *
|
||||
cipher_env_list.append(Asc2Environment)
|
||||
|
||||
from .AtbashCipherEnvironment import *
|
||||
cipher_env_list.append(AtbashCipherEnvironment)
|
||||
|
||||
from .DoubleCeaserEnvironment import *
|
||||
cipher_env_list.append(DoubleCeaserEnvironment)
|
||||
|
||||
from .FourSquareCipherEnvironment import FourSquareCipherEnvironment
|
||||
cipher_env_list.append(FourSquareCipherEnvironment)
|
||||
|
||||
from .TapCodeEnvironment import TapCodeEnvironment
|
||||
cipher_env_list.append(TapCodeEnvironment)
|
||||
|
||||
|
||||
### kor ###
|
||||
from .KorADFGVXCipherEnvironment import KorADFGVXCipherEnvironment
|
||||
cipher_env_list.append(KorADFGVXCipherEnvironment)
|
||||
|
||||
from .KorAffineCipherEnvironment import KorAffineCipherEnvironment
|
||||
cipher_env_list.append(KorAffineCipherEnvironment)
|
||||
|
||||
from .KorAlbertiCipherEnvironment import KorAlbertiCipherEnvironment
|
||||
cipher_env_list.append(KorAlbertiCipherEnvironment)
|
||||
|
||||
from .KorBifidCipherEnvironment import KorBifidCipherEnvironment
|
||||
cipher_env_list.append(KorBifidCipherEnvironment)
|
||||
|
||||
from .KorCollonCipherEnvironment import KorCollonCipherEnvironment
|
||||
cipher_env_list.append(KorCollonCipherEnvironment)
|
||||
|
||||
from .KorDigrafidCipherEnviroment import KorDigrafidCipherEnviroment
|
||||
cipher_env_list.append(KorDigrafidCipherEnviroment)
|
||||
|
||||
from .KorECCCipherEnvironment import KorECCCipherEnvironment
|
||||
cipher_env_list.append(KorECCCipherEnvironment)
|
||||
|
||||
from .KorFourSquareCipherEnvironment import KorFourSquareCipherEnvironment
|
||||
cipher_env_list.append(KorFourSquareCipherEnvironment)
|
||||
|
||||
from .KorInverseShiftSubstitutionCipherEnvironment import KorInverseShiftSubstitutionCipherEnvironment
|
||||
cipher_env_list.append(KorInverseShiftSubstitutionCipherEnvironment)
|
||||
|
||||
from .KorJeffersonCipherEnvironment import KorJeffersonCipherEnvironment
|
||||
cipher_env_list.append(KorJeffersonCipherEnvironment)
|
||||
|
||||
from .KorMorbitCipherEnvironment import KorMorbitCipherEnvironment
|
||||
cipher_env_list.append(KorMorbitCipherEnvironment)
|
||||
|
||||
from .KorMultiTapPhoneCodeEnvironment import KorMultiTapPhoneCodeEnvironment
|
||||
cipher_env_list.append(KorMultiTapPhoneCodeEnvironment)
|
||||
|
||||
from .KorPathCipherEnvironment import KorPathCipherEnvironment
|
||||
cipher_env_list.append(KorPathCipherEnvironment)
|
||||
|
||||
from .KorPhillipsFigureCipherEnvironment import KorPhillipsFigureCipherEnvironment
|
||||
cipher_env_list.append(KorPhillipsFigureCipherEnvironment)
|
||||
|
||||
from .KorPigpenMasonicCipherEnvironment import KorPigpenMasonicCipherEnvironment
|
||||
cipher_env_list.append(KorPigpenMasonicCipherEnvironment)
|
||||
|
||||
from .KorPolybiusSquareCipherEnvironment import KorPolybiusSquareCipherEnvironment
|
||||
cipher_env_list.append(KorPolybiusSquareCipherEnvironment)
|
||||
|
||||
from .KorPortaCipherEnvironment import KorPortaCipherEnvironment
|
||||
cipher_env_list.append(KorPortaCipherEnvironment)
|
||||
|
||||
from .KorRedefenceFigureCipherEnvironment import KorRedefenceFigureCipherEnvironment
|
||||
cipher_env_list.append(KorRedefenceFigureCipherEnvironment)
|
||||
|
||||
from .KorRotatingGridCipherEnvironment import KorRotatingGridCipherEnvironment
|
||||
cipher_env_list.append(KorRotatingGridCipherEnvironment)
|
||||
|
||||
from .KorSBOXCipherEnvironment import KorSBOXCipherEnvironment
|
||||
cipher_env_list.append(KorSBOXCipherEnvironment)
|
||||
|
||||
from .KorSHACipherEnvironment import KorSHACipherEnvironment
|
||||
cipher_env_list.append(KorSHACipherEnvironment)
|
||||
|
||||
from .KorSolitaireCipherEnvironment import KorSolitaireCipherEnvironment
|
||||
cipher_env_list.append(KorSolitaireCipherEnvironment)
|
||||
|
||||
from .KorTranspositionCipherEnvironment import KorTranspositionCipherEnvironment
|
||||
cipher_env_list.append(KorTranspositionCipherEnvironment)
|
||||
|
||||
from .KorXORCipherEnvironment import KorXORCipherEnvironment
|
||||
cipher_env_list.append(KorXORCipherEnvironment)
|
||||
|
||||
from .KorRSACipherEnvironment import KorRSACipherEnvironment
|
||||
cipher_env_list.append(KorRSACipherEnvironment)
|
||||
|
||||
# 过滤出KorCipher
|
||||
kor_cipher_env_list = []
|
||||
for env in cipher_env_list:
|
||||
if 'Kor' in env.__name__:
|
||||
kor_cipher_env_list.append(env)
|
||||
### kor ###
|
||||
Loading…
Add table
Add a link
Reference in a new issue