Python verification RSA encryption uses public key for encryption
編輯:Python
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):
""" check RSA encryption Use public key for encryption """
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):
""" check RSA encryption Decrypt with private key """
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))
Another option Key length is not x.509
import base64
import rsa
(pubkey, privkey) = rsa.newkeys(1024) # 1024 This number indicates the length of the string that can be encrypted , It can be 512,4096 wait ,
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 Encrypted data :',crypto)
base64_key = base64.b64encode(crypto)
print('base64 Later data :',base64_key)
# Decrypt data
message = rsa.decrypt(crypto, privkey)
print(' Decrypted data :',message)
Another option
import Crypto.PublicKey.RSA
import Crypto.Random
x = Crypto.PublicKey.RSA.generate(1024)
a = x.exportKey("PEM") # Generate private key
b = x.publickey().exportKey() # Generate public key
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() # Generate private key
d = y.publickey().exportKey() # Generate public key
with open("c.pem", "wb") as x:
x.write(c)
with open("d.pem", "wb") as x:
x.write(d)