AES、RSA密码py脚本

AES密码

# -*- coding: utf-8 -*-
# @Time : 2020-12-23 8:13
# @File : AES密码.py
# @Author : mirror
# @Software: PyCharm

from Crypto.Cipher import AES
from binascii import b2a_hex, a2b_hex
import base64

add = ""
# 如果text不足16位的倍数就用空格补足为16位
def add_to_16(text):
    if len(text.encode('utf-8')) % 16 :
        add = 16 - len(text.encode('utf-8')) % 16
    else:
        add = 0
    text = text + ('\0'*add)
    return text.encode('utf-8')


# 加密函数
def encrypt(text):
    key = '9999999999999999'.encode('utf-8')
    iv = b'qqqqqqqqqqqqqqqq'
    mode = AES.MODE_CBC
    cryptor = AES.new(key, mode, iv)
    text = add_to_16(text)
    cipher_text = cryptor.encrypt(text)
    # 因为AES加密后的字符串不一定是ascii字符集的,输出保存可能存在问题,所以这里需要转为16进制字符串
    return b2a_hex(cipher_text)


# 解密后,去掉补足的空格用rstrip() 去掉
def decrypt(text):
    key = '9999999999999999'.encode('utf-8')
    iv = b'qqqqqqqqqqqqqqqq'
    mode = AES.MODE_CBC
    cryptos = AES.new(key, mode, iv)
    plain_text = cryptos.decrypt(a2b_hex(text))
    return bytes.decode(plain_text).rstrip('\0')


if __name__ == '__main__':
    e = encrypt("hello world")  # 加密
    e = base64.b64encode(e)
    d = base64.b64decode(e)
    d = decrypt(d)  # 解密
    print("加密:", str(e,encoding='utf-8'))
    print("解密:", d)

RSA密码

# -*- coding: utf-8 -*-
# @Time : 2020-12-24 20:20
# @File : RSA密码.py
# @Author : mirror
# @Software: PyCharm

from Crypto.PublicKey import RSA
from Crypto.Cipher import PKCS1_v1_5
import base64
from Crypto import Random

# 伪随机数生成器
random_generator = Random.new().read

# rsa算法生成实例
rsa = RSA.generate(1024,random_generator)

# master的秘钥对的生成
private_pem = rsa.exportKey()
public_pem = rsa.publickey().exportKey()

#生成私钥文件
with open('rsa_private_key.pem','wb') as f :
    f.write(private_pem)
with open('rsa_public_key.pem','wb') as f :
    f.write(public_pem)
print("密钥对生成成功!")



message = 'hello ghost, this is a plian text'
with open('rsa_public_key.pem',"r") as f:
     key = f.read()
     rsakey = RSA.importKey(key)  # 导入读取到的公钥
     cipher = PKCS1_v1_5.new(rsakey) # 生成对象
     cipher_text = cipher.encrypt(message.encode('utf-8'))
     cipher_text = base64.b64encode(cipher_text)
    # 通过生成的对象加密message明文,注意,在python3中加密的数据必须是bytes类型的数据,不能是str类型的数据
     print("密文为:" + str(cipher_text,encoding="utf-8"))

with open('rsa_private_key.pem') as f:
    key = f.read()
    rsakey = RSA.importKey(key)  # 导入读取到的私钥
    cipher = PKCS1_v1_5.new(rsakey)  # 生成对象
    text = base64.b64decode(cipher_text)
    text = cipher.decrypt(text, ' ')
    # 将密文解密成明文,返回的是一个bytes类型数据,需要自己转换成str
    print("明文为:" + str(text,encoding="utf-8"))


pt(text, ' ')
    # 将密文解密成明文,返回的是一个bytes类型数据,需要自己转换成str
    print("明文为:" + str(text,encoding="utf-8"))


  转载请注明: XingHe AES、RSA密码py脚本

  目录