Montecarlo模拟AES扩散

发布于 2025-01-29 05:50:43 字数 1178 浏览 3 评论 0原文

我需要对AE进行蒙特卡洛模拟来观察扩散的效果(如果我更改了一位明文,那么密文中的一半位应该会改变)...我认为我认为我在这里做了正确的一切,但是在AES(AES = AES.New(key,aes.mode_ecb)的定义中,说语法错误)。我在哪里犯了一个错误?在此先感谢您的帮助c:

import numpy as np
import random
from Cryptodome.Cipher import AES



def flip_bit(text, ibit):
    flipped_text = bytearray(text) 
    flipped_text[ibit//8] ^= 1 << (ibit%8) 
    return bytes(flipped_text)

def text_distance(textA, textB):
    AxorB = bytes(a ^ b for (a, b) in zip(textA, textB))
    distance = sum([bin(byte).count('1') for byte in AxorB])
    return distance

def mcs_diffusion(key_length):
    
    assert key_length in AES.key_size
    
 
    key = bytes(random.randint( key_length)
    aes = AES.new(key, AES.MODE_ECB)             
   

    x = bytes(random.randint(AES.block_size))
    x1 = flip_bit(x, random.randint(8*AES.block_size))

    y = aes.encrypt(x)
    y1 = aes.encrypt(x1)
    distance = text_distance(y, y1)
    
    return distance


N = 10000 
key_length = 16

results = np.zeros(N)
for i in range(N):
    results[i] = mcs_diffusion(key_length)
    
print('average: {}'.format(np.mean(results)))
print('min, max: {}, {}'.format(min(results), max(results)))

I need to implement a MonteCarlo simulation to an AES to observe the effect of diffusion (if I change a single bit of the plaintext, then half of the bits in the ciphertext should change)... I think I did everything correct here but it says syntax error in the definition of the aes ( aes = AES.new(key, AES.MODE_ECB) ). Where did I make a mistake? Thanks in advance for your help c:

import numpy as np
import random
from Cryptodome.Cipher import AES



def flip_bit(text, ibit):
    flipped_text = bytearray(text) 
    flipped_text[ibit//8] ^= 1 << (ibit%8) 
    return bytes(flipped_text)

def text_distance(textA, textB):
    AxorB = bytes(a ^ b for (a, b) in zip(textA, textB))
    distance = sum([bin(byte).count('1') for byte in AxorB])
    return distance

def mcs_diffusion(key_length):
    
    assert key_length in AES.key_size
    
 
    key = bytes(random.randint( key_length)
    aes = AES.new(key, AES.MODE_ECB)             
   

    x = bytes(random.randint(AES.block_size))
    x1 = flip_bit(x, random.randint(8*AES.block_size))

    y = aes.encrypt(x)
    y1 = aes.encrypt(x1)
    distance = text_distance(y, y1)
    
    return distance


N = 10000 
key_length = 16

results = np.zeros(N)
for i in range(N):
    results[i] = mcs_diffusion(key_length)
    
print('average: {}'.format(np.mean(results)))
print('min, max: {}, {}'.format(min(results), max(results)))

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文