from Crypto.PublicKey import RSA
from Crypto.Cipher import PKCS1_v1_5 as Cipher_pkcs1_v1_5
from Crypto.Signature import PKCS1_v1_5 as Signature_pkcs1_v1_5
import base64
def rsa_encrypt(password:str,publickey):
"""校驗RSA加密 使用公鑰進行加密"""
public_key = '-----BEGIN PUBLIC KEY-----\n'+ publickey +'\n-----END PUBLIC KEY-----'
cipher = Cipher_pkcs1_v1_5.new(RSA.importKey(public_key))
cipher_text = base64.b64encode(cipher.encrypt(password.encode())).decode()
return cipher_text
def rsa_decrypt(text):
"""校驗RSA加密 使用私鑰進行解密"""
cipher = Cipher_pkcs1_v1_5.new(RSA.importKey(private_key))
retval = cipher.decrypt(base64.b64decode(text), 'ERROR').decode('utf-8')
return retval
publickey='MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCN1c81ZEC8c2AaYMdoV9yZbOUXL3LFBVyhC/lnYz+26MjrjsAF+07mREIZBhVZqN+8dIs3+s3M6FMuMFXYJH7ckCGKvWpDauzyf7B9jmCu+1QAeP32pdJA+1T3fBe8mvhq/dFN4bMhsSw2O56ydwBREeQGhNkTQaKGJCc231J9OwIDAQAB'
print(rsa_encrypt('123456789',publickey))
另一種方案 秘鑰長度不是x.509
import base64
import rsa
(pubkey, privkey) = rsa.newkeys(1024) # 1024這個數字表示可以加密的字符串長度,可以是512,4096等等,
with open('public.pem' ,'w+') as f:
f.write(pubkey.save_pkcs1().decode())
print("=============================")
with open('private.pem' ,'w+') as f:
f.write(privkey.save_pkcs1().decode())
with open('public.pem' ,'r') as f:
pubkey = rsa.PublicKey.load_pkcs1(f.read().encode())
with open('private.pem' ,'r') as f:
privkey = rsa.PrivateKey.load_pkcs1(f.read().encode())
print('pubkey:',pubkey)
print('privkey:',privkey)
message_data = '123456789'.encode('utf-8')
crypto = rsa.encrypt(message_data, pubkey)
print('pubkey加密後的數據:',crypto)
base64_key = base64.b64encode(crypto)
print('base64後的數據:',base64_key)
# 解密數據
message = rsa.decrypt(crypto, privkey)
print('解密後的數據:',message)
另一種方案
import Crypto.PublicKey.RSA
import Crypto.Random
x = Crypto.PublicKey.RSA.generate(1024)
a = x.exportKey("PEM") # 生成私鑰
b = x.publickey().exportKey() # 生成公鑰
with open("a.pem", "wb") as x:
x.write(a)
with open("b.pem", "wb") as x:
x.write(b)
y = Crypto.PublicKey.RSA.generate(1024, Crypto.Random.new().read)
c = y.exportKey() # 生成私鑰
d = y.publickey().exportKey() # 生成公鑰
with open("c.pem", "wb") as x:
x.write(c)
with open("d.pem", "wb") as x:
x.write(d)