#!/usr/bin/env python
# -*- coding:utf-8 -*-
import base64
from Crypto import Random
from Crypto.Hash import MD5 # or use SHA
from Crypto.Cipher import AES
from Crypto.PublicKey import RSA
from Crypto.Cipher import PKCS1_v1_5
from Crypto.Signature import PKCS1_v1_5 as Sign_PKCS1_v1_5
def create_pems():
rsa = RSA.generate(1024, Random.new().read)
private_pem = rsa.exportKey()
public_pem = rsa.publickey().exportKey()
return public_pem, private_pem
def rsa_encrypt(message):
cipher = PKCS1_v1_5.new(RSA.importKey(public_pem))
return base64.b64encode(cipher.encrypt(message.encode('utf-8'))).decode('utf-8')
def rsa_decrypt(cipher_text):
cipher = PKCS1_v1_5.new(RSA.importKey(private_pem))
return cipher.decrypt(base64.b64decode(cipher_text), Random.new().read).decode('utf-8')
def sign(message):
cipher = Sign_PKCS1_v1_5.new(RSA.importKey(private_pem))
return base64.b64encode(cipher.sign(MD5.new(data=message)))
def verify(message, cipher_text):
cipher = Sign_PKCS1_v1_5.new(RSA.importKey(public_pem))
return cipher.verify(MD5.new(message), base64.b64decode(cipher_text))
def aes_encrypt(password):
cipher = AES.new(key, AES.MODE_CBC, iv)
pad_length = 16 - len(password.encode()) % 16
pad_string = pad_length * chr(pad_length)
return base64.b64encode(cipher.encrypt('%s%s' % (password, pad_string))).decode()
def aes_decrypt(password):
cipher = AES.new(key, AES.MODE_CBC, iv)
password = cipher.decrypt(base64.b64decode(password))
return password.decode().strip('')
public_pem, private_pem = create_pems()
message = "hello client, this is a message"
cipher_text = rsa_encrypt(message)
message = rsa_decrypt(cipher_text)
print(public_pem)
print(private_pem)
print('==========================aes encrypt=========================')
print(cipher_text)
print(message)
cipher_text = sign(message)
message = verify(message, cipher_text)
print('==========================aes sign============================')
print(cipher_text)
print(message)
key, iv = '<cq:"s|fd.t;\'ag\\', 'z!b#t%h&*v_u{n"J'
cipher_text = aes_encrypt('123456789')
print('==========================des encrypt=========================')
print(cipher_text)
print(aes_decrypt(cipher_text))