任意的s盒,用Python3实现
时间: 2024-03-16 19:43:49 浏览: 44
python实现对称加密中3DES算法工程文件
好的,这里提供一个Python 3的程序,可以计算任意S盒的4比特和8比特的差分均匀性。程序使用的是布鲁斯特算法(Bruce Schneier Algorithm)。
```python
import random
# S盒输入输出的比特数
IN_BITS = 4
OUT_BITS = 4
# 每个输入比特可能的取值个数
IN_VALUES = 2**IN_BITS
# 每个输出比特可能的取值个数
OUT_VALUES = 2**OUT_BITS
# 随机生成一个S盒,输入输出比特数为IN_BITS和OUT_BITS
sbox = [[random.randint(0, OUT_VALUES-1) for j in range(IN_VALUES)] for i in range(OUT_VALUES)]
# 计算4比特差分均匀性
def differential_uniformity_4():
max_abs_sum = 0
for a in range(IN_VALUES):
for b in range(IN_VALUES):
in_diff = a ^ b
out_diff = sbox[a] ^ sbox[b]
abs_sum = sum([bin(out_diff).count('1') for out_diff in range(OUT_VALUES) if (out_diff ^ in_diff) == out_diff])
if abs_sum > max_abs_sum:
max_abs_sum = abs_sum
return max_abs_sum - 2**(OUT_BITS-1)
# 计算8比特差分均匀性
def differential_uniformity_8():
max_abs_sum = 0
for a in range(IN_VALUES):
for b in range(IN_VALUES):
for c in range(IN_VALUES):
for d in range(IN_VALUES):
in_diff = (a << 12) + (b << 8) + (c << 4) + d
out_diff = (sbox[a][b] << 12) + (sbox[c][d] << 8) + (sbox[a][d] << 4) + sbox[c][b]
abs_sum = sum([bin(out_diff).count('1') for out_diff in range(OUT_VALUES) if (out_diff ^ in_diff) == out_diff])
if abs_sum > max_abs_sum:
max_abs_sum = abs_sum
return max_abs_sum - 2**(OUT_BITS-1)
# 打印S盒和差分均匀性
print("S盒:")
for row in sbox:
print(row)
print("4比特差分均匀性:", differential_uniformity_4())
print("8比特差分均匀性:", differential_uniformity_8())
```
程序运行后会随机生成一个S盒,计算其4比特和8比特的差分均匀性,并打印结果。你可以多次运行程序,生成不同的S盒,以观察差分均匀性的变化。
阅读全文