Security and Cryptography in Python - Block Cipher(1)

Security and Cryptography in Python - Block Cipher(1)

DES

https://en.wikipedia.org/wiki/Data_Encryption_Standard

GOST

https://en.wikipedia.org/wiki/GOST_(block_cipher)

pyDes

https://github.com/twhiteman/pyDes/blob/master/pyDes.py

DES

ECB mode

from pyDes import *

message = "0123456701234567"
key = "DESCRYPT"
iv = bytes([0]*8)
k = des(key, ECB, iv, pad=None, padmode=PAD_PKCS5)

cipher = k.encrypt(message)
print("Length of plain text:", len(message ))
print("Length of cipher text:", len(cipher))
print("Encrypted:", cipher[0:8])
print("Encrypted:", cipher[8:16])
print("Encrypted:", cipher[16:])
message = k.decrypt(cipher)
print("Decrypted:", message)

image-20210208202446089

CBC Mode

from pyDes import *

message = "0123456701234567"
key = "DESCRYPT"
iv = bytes([0]*8)
k = des(key, CBC, iv, pad=None, padmode=PAD_PKCS5)

cipher = k.encrypt(message)
print("Length of plain text:", len(message ))
print("Length of cipher text:", len(cipher))
print("Encrypted:", cipher[0:8])
print("Encrypted:", cipher[8:16])
print("Encrypted:", cipher[16:])
message = k.decrypt(cipher)
print("Decrypted:", message)

image-20210208202612840

DES and modifying the cipher texts - ECB Mode

from pyDes import *

def modify(cipher):
    mod = [0]*len(cipher)
    mod[10] = ord(' ') ^ ord('1')
    mod[11] = ord(' ') ^ ord('0')
    mod[12] = ord('1') ^ ord('0')
    return bytes([mod[i] ^ cipher[i] for i in range(len(cipher))])

message = "Give Bob:    10$"
key = "DESCRYPT"
iv = bytes([0]*8)
k = des(key, ECB, iv, pad=None, padmode=PAD_PKCS5)

# Alice sending the encrypted message
cipher = k.encrypt(message)
print("Length of plain text:", len(message ))
print("Length of cipher text:", len(cipher))
print("Encrypted:", cipher)

# Bob modifying the cipher text
cipher = modify(cipher)

# this is the bank decrypting the message
message = k.decrypt(cipher)
print("Decrypted:", message)

Running Result:

image-20210208204610172

Change the modified block and run it again:

image-20210208204824471

Change the modified block again and run it again:

image-20210208205001340

DES and modifying the cipher texts - CBC Mode

from pyDes import *

def modify(cipher):
    mod = [0]*len(cipher)
    mod[9] = 1
    return bytes([mod[i] ^ cipher[i] for i in range(len(cipher))])

message = "Give Bob:    10$ and send them to him"
key = "DESCRYPT"
iv = bytes([0]*8)
k = des(key, CBC, iv, pad=None, padmode=PAD_PKCS5)

# Alice sending the encrypted message
cipher = k.encrypt(message)
print("Length of plain text:", len(message ))
print("Length of cipher text:", len(cipher))
print("Encrypted:", cipher)

# Bob modifying the cipher text
cipher = modify(cipher)

# this is the bank decrypting the message
message = k.decrypt(cipher)
print("Decrypted:", message)

Running Result:

image-20210208205513589

posted @ 2021-02-08 20:56  晨风_Eric  阅读(90)  评论(0编辑  收藏  举报