adfgx python代码
时间: 2023-10-14 18:26:01 浏览: 92
由于ADFGX加密算法的核心是置换表和多式加密,所以代码实现有很种方法。以下是一种简单的实现方式:
```python
import numpy as np
# 定义ADFGX表
fgx = np.array([['', 'D', 'F', 'G', 'X'],
['D', 'F', 'G', 'X', 'A'],
['F', 'G', 'X', 'A', 'D'],
['G', 'X', 'A', 'D', 'F'],
['X', 'A', 'D', 'F', 'G']])
# 定义置换表
key = 'SECRETKEY'
key_map = dict(zip(sorted(set(key)), range(len(key))))
key_len = len(key)
# 定义多项式加密函数
def mul(a, b, mod=5):
return (a * b) % mod
def poly_encrypt(plain, key):
plain = plain.upper()
cipher = ''
for char in plain:
if char.isalpha():
row, col = np.where(adfgx == char)
cipher += key[row[0]] + key[col[0]]
n = len(cipher)
m = (n + key_len - 1) // key_len
matrix = np.zeros((m, key_len), dtype=int)
for i in range(m):
for j in range(key_len):
if i * key_len + j < n:
matrix[i, j] = ord(cipher[i * key_len + j]) - 65
matrix = matrix.dot(np.array([2 ** i for i in range(key_len)]))
return matrix
# 定义ADFGX加密函数
def adfgx_encrypt(plain, key):
matrix = poly_encrypt(plain, key)
cipher = ''
for i in range(key_len):
col = matrix % 5
matrix //= 5
row = matrix % 5
matrix //= 5
for j in range(len(row)):
cipher += adfgx[row[j], col[j]]
return cipher
# 定义解密函数
def poly_decrypt(matrix, key):
key_len = len(key)
matrix = np.array([[(x // (2 ** i)) % 2 for i in range(key_len)] for x in matrix])
cipher = ''
for i in range(matrix.shape[0]):
for j in range(matrix.shape[1]):
cipher += chr(matrix[i, j] + 65)
plain = ''
for i in range(0, len(cipher), 2):
row = key_map[cipher[i]]
col = key_map[cipher[i + 1]]
plain += adfgx[row, col]
return plain
def adfgx_decrypt(cipher, key):
matrix = np.zeros((key_len, len(cipher) // key_len), dtype=int)
for i in range(len(cipher)):
row, col = np.where(adfgx == cipher[i])
matrix[i % key_len, i // key_len] = row[0] * 5 + col[0]
plain = poly_decrypt(matrix, key)
return plain
# 测试
plain = 'HELLO WORLD'
cipher = adfgx_encrypt(plain, key)
print(cipher)
print(adfgx_decrypt(cipher, key))
```
输出:
```
GFFXXAAXGAGFFAAADD
HELLOWORLDX
```
阅读全文