python2.7 的 RSA 加密代码
# -*- coding: utf-8 -*-
import rsa
import os
import base64
def rsa_encrypt(message):
file_path = (os.path.dirname(os.path.realpath(__file__)) + "\\publicKey.pem")#获取当前目录的publicKey.pem文件
with open(file_path) as f:
key = f.read()
pubkey = rsa.PublicKey.load_pkcs1_openssl_pem(key)
# 默认加密长度为117
start = 0
crypto = ""
# 分段加密
while True:
end = start + 117
if end > len(message):
end = len(message)
p = rsa.encrypt(message[start:end], pubkey)
crypto += p
start = end
if start == len(message):
break
crypt_content = base64.b64encode(crypto)
return crypt_content
python3 的 RSA 加密代码
# -*- coding: utf-8 -*-
import rsa
import os
import base64
def rsa_encrypt(message):
file_path = (os.path.dirname(os.path.realpath(__file__)) + "\\publicKey.pem")#获取当前目录的publicKey.pem文件
message = bytes(message,encoding="utf-8")
with open(file_path) as f:
key = f.read()
pubkey = rsa.PublicKey.load_pkcs1_openssl_pem(key)
# 默认加密长度为117
start = 0
crypto = b""
# 分段加密
while True:
end = start + 117
if end > len(message):
end = len(message)
p = rsa.encrypt(message[start:end], pubkey)
crypto += p
start = end
if start == len(message):
break
crypt_content = base64.b64encode(crypto)
return crypt_content
MD5 加密代码
# -*- coding: utf-8 -*-
import hashlib
password = '000000'
password = hashlib.md5(password).hexdigest()
注意点
RSA 公私鈅格式有两种,本文使用的是 pkcs8 的格式,如:demo 上的 publicKey.pem 文件
-----BEGIN PUBLIC KEY-----
MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCiIeSCfxWrzFAdhWyAeCcFUY7jkqfMftcnoVBmYFvQGRGrYEHbPXu5HeO71sY0wF1N4hOq3MYlCKgnoux6vJIEy/z44TiZHV12JbqtvZRPz72ssmgEgHr1YilJJMQt7M1GstcDh9TgH7RzbZYTOv0MIalGc+umThMqQV3t4WTuJwIDAQAB
-----END PUBLIC KEY-----
RSA 的 pkcs1 格式
#公钥
-----BEGIN RSA PUBLIC KEY-----
-----END RSA PUBLIC KEY-----
# 私钥
-----BEGIN RSA PRIVATE KEY-----
-----END RSA PRIVATE KEY-----