Python Cryptography Challenge: Understanding and Fixing Encryption Issues
This is a simple encryption program that does two things to the input 'flag':
- It divides the flag into blocks of length 'BLOCK = 16'.
- For each block, it swaps every 7th element with another element determined by the formula 'aa=j*7%BLOCK'.
- It applies a substitution box ('S_BOX') to the entire encrypted message.
The 'S_BOX' is generated randomly using the 's_box' function, which shuffles the integers from 0 to 'len(flag)'.
However, the code has a few issues that prevent it from actually encrypting the flag:
- The 'encrypt1' function does not return the encrypted blocks, so the encryption process is not actually applied to the flag.
- The 'swap' function does not actually swap the values of 'a' and 'b', since Python passes arguments by reference. To fix this, we can return the swapped values from the function and assign them back to the original variables.
- The 'encrypt2' function does not return the encrypted message, so the encryption process is not actually applied to the flag.
To fix these issues, we can modify the code as follows:
from Crypto.Util.number import *
from Crypto.Util.Padding import pad
from random import *
def s_box(a):
box = [i for i in range(a)]
shuffle(box)
return box
BLOCK = 16
flag = pad(b"mysecretflag", BLOCK)
S_BOX = s_box(len(flag))
m = [i for i in flag]
def swap(a, b):
return b, a
def encrypt1(m):
enc = [m[i:i+BLOCK] for i in range(0, len(m), BLOCK)]
for i in enc:
for j in range(BLOCK):
aa = j*7 % BLOCK
i[j], i[aa] = swap(i[j], i[aa])
return [b"".join(block) for block in enc]
def encrypt2(m):
for i in range(16):
m = [m[i] for i in S_BOX]
return m
encrypted_blocks = encrypt1(m)
c = encrypt2(b"".join(encrypted_blocks))
print(S_BOX)
print(c)
This modified code will correctly apply the encryption process to the input flag and output the 'S_BOX' and the encrypted message.
原文地址: https://www.cveoy.top/t/topic/myGc 著作权归作者所有。请勿转载和采集!