CFB加密模式的python实现
python代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73
| from typing import Tuple
def encrypt_des_cfb(key, iv, plaintext): key_bits = bytes_to_bits(key) iv_bits = bytes_to_bits(iv)
cipher = DES(key_bits)
ciphertext = cipher.encrypt(iv_bits)
for i in range(len(plaintext)): cipher_byte = ciphertext[i] ^ plaintext[i]
ciphertext = ciphertext[1:] + bytes([cipher_byte])
return ciphertext[len(iv):]
def bytes_to_bits(data): bits = [] for byte in data: bits += [int(bit) for bit in bin(byte)[2:].rjust(8, '0')] return bits
class DES: def __init__(self, key_bits): self.key_bits = key_bits
def encrypt(self, plaintext_bits): key = self.permute_key(self.key_bits) plaintext = self.permute_text(plaintext_bits, DES.IP) left, right = self.split(plaintext) for i in range(16): new_right = self.apply_function(right, key[i]) new_right = self.permute_text(new_right, DES.P) new_right = self.xor(left, new_right) left = right right = new_right ciphertext = self.permute_text(right + left, DES.IP_INV) return self.bits_to_bytes(ciphertext)
def apply_function(self, bits, key_bits): expanded_bits = self.permute_text(bits, DES.E) bits_xor_key = self.xor(expanded_bits, key_bits) bits_groups = [bits_xor_key[i:i+6] for i in range(0, len(bits_xor_key), 6)] result = [] for bits in bits_groups: row = bits[0] * 2 + bits[5] col = bits[1] * 8 + bits[2] * 4 + bits[3] * 2 + bits[4] val = DES.S[bits_groups.index(bits)][row][col] result += [int(bit) for bit in bin(val)[2:].rjust(4, '0')] return self.permute_text(result, DES.P_BOX)
@staticmethod def split(bits): return bits[:32], bits[32:]
@staticmethod def xor(bits1, bits2): return [bit1 ^ bit2 for bit1, bit2 in zip(bits1, bits2)]
@staticmethod def permute_text(bits, permutation): return [bits[i-1] for i in permutation]
|
加密的des类没有实现完全,故无法运行,但是我们可以从中看出来des的cfb加密模式的大概原理
代码解释
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
| def encrypt_des_cfb(key, iv, plaintext): key_bits = bytes_to_bits(key) iv_bits = bytes_to_bits(iv)
cipher = DES(key_bits)
ciphertext = cipher.encrypt(iv_bits)
for i in range(len(plaintext)): cipher_byte = ciphertext[i] ^ plaintext[i]
ciphertext = ciphertext[1:] + bytes([cipher_byte])
return ciphertext[len(iv):]
|
key是密钥,iv是初始化向量,plaintext是明文
- 首先将密钥和初始化向量转换为位数组
- 然后将初始化向量进行des加密生成向量的密文
- 最后循环将向量的密文和明文进行异或生成密文
- 再将生成的密文加到向量密文里面