rsa encryption and decryption and signing endorsement test

Crypto installer to use encryption pip install Crypto

New two modules rsautils.py, rsatest.py directly on the code,
rsautils.py


! # / usr / bin / env python3 
# Coding = UTF-8
# Author: Zhifengshi
"" "
create_rsa_key () - create an RSA key
my_encrypt_and_decrypt () - test the encryption and decryption functions
rsa_sign () & rsa_signverify () - Signature Verification and Validation Test check function
"" "

Import Base64
from Crypto.Hash Import SHAl
from the RSA Crypto.PublicKey Import
from Crypto.Signature Import pkcs1_15
from Crypto.Cipher Import PKCS1_v1_5 AS Cipher_pkcs1_v1_5
from rsa_test Import to_para, to_decrypt

pubkey = '' 'the BEGIN ----- the PUBLIC KEY ----- RSA
MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCCaqlxNJpDUjMLGlzLglAub6SLZDP8HxfpHzqg
kecuVRpQ4OOlIOHSFGGHSRUyQ5F18vMzMcTWWzGaxV + bVHC8E0q9w1hUeUu954gn01wt6vK3N82o
D/N0R9ZbireOGZB/weaW8cw8jUHjc/j9N4o1pV+vcOYUsU2xt5vXRwFEGQIDAQAB
-----END RSA PUBLIC KEY-----'''

privatekey = '''-----BEGIN RSA PRIVATE KEY-----
MIICdwIBADANBgkqhkiG9w0BAQEFAASCAmEwggJdAgEAAoGBAIJqqXE0mkNSMwsaXMuCUC5vpItk
M/wfF+kfOqCR5y5VGlDg46Ug4dIUYYdJFTJDkXXy8zMxxNZbMZrFX5tUcLwTSr3DWFR5S73niCfT
XC3q8rc3zagP83RH1luKt44ZkH/B5pbxzDyNQeNz+P03ijWlX69w5hSxTbG3m9dHAUQZAgMBAAEC
gYBFUhKcpLw2enO9PBcE6VBbTmZk3S8wnQpllH7iKIt8OioRwWffNtoxgznP4g3NONMRocCZfqPE
2JZGUREfjEObP/jnPQFRd7r/XOwsWT80pbpBdo4csGnenbq5FVR1Ren0i1lyHeIdm+mZR3BuPoMN
QbAha+3ggYBaSvEgfLGRrQJBANWrKQ7YHQRTf1JKDEeIQYT6Xuc1WVPZ9oNQg+G1yYK3vSxHAqEj
7pj7OYXETb7fPBsOYb3Z3OyRAJBnQhwbV+sCQQCcQSGBALdwLL6aGKfMJiEc2VTCY4//K04L8dB1
These three parameters) to get the private key. 4, the private key file is written to disk. 5, using the chain method calls publickey and exportKey method to generate a public key, written to a file on disk. "" "
















key = RSA.generate(1024)
encrypted_key = key.exportKey(passphrase=password, pkcs=8, protection="scryptAndAES128-CBC")
with open("my_private_rsa_key.pem", "wb") as f:
f.write(encrypted_key)
with open("my_rsa_public.pem", "wb") as f:
f.write(key.publickey().exportKey())

def encrypt_and_decrypt_test(message, password="123456"):
# 加载公钥用于加密
key = pubkey
rsakey = RSA.importKey(key)
cipher = Cipher_pkcs1_v1_5.new(rsakey)
cipher_text = base64.b64encode(cipher.encrypt(message))
print('b"123456,abcdesd"对应的密文是:',Cipher_Text) rsakey = RSA.importKey (Key) Key = PrivateKey
# private key is used to decrypt loaded


= Cipher_pkcs1_v1_5.new cipher (rsakey)
text = cipher.decrypt (base64.b64decode (Cipher_Text), password)
Print ( 'the decrypted text is:', text)


DEF rsa_sign (Message, password = "123456"):
# reading private key information for endorsement
private_key = RSA.importKey (Open ( "my_private_rsa_key.pem"). the Read (), passphrase = password)
hash_obj = SHA1.new (the message)
# Print (pkcs1_15.new (private_key) .can_sign ( )) #check wheather Object of pkcs1_15 CAN BE Signed
# Base64 encoded print visualization
Signature = base64.b64encode (pkcs1_15.new (the private_key) .sign (hash_obj))
return Signature


DEF rsa_signverify (message, Signature):
# read the public key information a test to check
public_key = RSA.importKey (open ( "my_rsa_public.pem "). read ())
# Message to do a "hash" treatment, RSA signature so required
hash_obj = SHA1.new (the Message)
the try:
# Because the signature is the base64 encoding, decoding it here first, and then test to check
pkcs1_15.new (public_key) .verify (hash_obj, base64.b64decode (Signature))
Print ( 'IS of The Signature Valid.')
return True
the except (a ValueError, TypeError):
Print ( 'IS of The Signature invalid.')


IF the __name__ == '__main__':
Message = B "123456, dnclod "
create_rsa_key ()
encrypt_and_decrypt_test (Message)
dict_body = { 'certificate_no': '2019042955452554', 'AUTH_CODE': '456789'}
encrypt_message = to_para (STR (dict_body))
Print (" Dictionary decrypting dict_body:% s "% to_decrypt(to_para(str(dict_body))))
message1 = b'dsjdhsjds'
signature = rsa_sign(message)
print(rsa_signverify(message, signature))

rsatest.py


import rsa
import base64
from Crypto.PublicKey import RSA
from Crypto.Cipher import PKCS1_v1_5 as Cipher_pkcs1_v1_5

# 需要安装pycrypto rsa
pubkey = '''-----BEGIN RSA PUBLIC KEY-----
MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCCaqlxNJpDUjMLGlzLglAub6SLZDP8HxfpHzqg
kecuVRpQ4OOlIOHSFGGHSRUyQ5F18vMzMcTWWzGaxV+bVHC8E0q9w1hUeUu954gn01wt6vK3N82o
D/N0R9ZbireOGZB/weaW8cw8jUHjc/j9N4o1pV+vcOYUsU2xt5vXRwFEGQIDAQAB
-----END RSA PUBLIC KEY-----'''

privatekey = '''-----BEGIN RSA PRIVATE KEY-----
MIICdwIBADANBgkqhkiG9w0BAQEFAASCAmEwggJdAgEAAoGBAIJqqXE0mkNSMwsaXMuCUC5vpItk
M/wfF+kfOqCR5y5VGlDg46Ug4dIUYYdJFTJDkXXy8zMxxNZbMZrFX5tUcLwTSr3DWFR5S73niCfT
XC3q8rc3zagP83RH1luKt44ZkH/B5pbxzDyNQeNz+P03ijWlX69w5hSxTbG3m9dHAUQZAgMBAAEC
gYBFUhKcpLw2enO9PBcE6VBbTmZk3S8wnQpllH7iKIt8OioRwWffNtoxgznP4g3NONMRocCZfqPE
2JZGUREfjEObP/jnPQFRd7r/XOwsWT80pbpBdo4csGnenbq5FVR1Ren0i1lyHeIdm+mZR3BuPoMN
QbAha+3ggYBaSvEgfLGRrQJBANWrKQ7YHQRTf1JKDEeIQYT6Xuc1WVPZ9oNQg+G1yYK3vSxHAqEj
7pj7OYXETb7fPBsOYb3Z3OyRAJBnQhwbV+sCQQCcQSGBALdwLL6aGKfMJiEc2VTCY4//K04L8dB1
NSlzWYZSLMkfP7X+KKgdcmWQRx6Dwm6hKIIOWjQBi+CikzcLAkEAtszhqp6AbMQWyMsrKEPNcjxV
109QJiny+jN3MTK6vQf/Y5M5D63TIrTEaMoijaslHCy4uJlcplQD/IcrCyrlkwJABXA640uMFupn
w+NBy9gz5NYnnhBrDZ2LPN0wvTOZertN8oQ+h8jm4660kznNESV4iWt2AEPxquA22SruKZpoGwJB
ALrT5IiJs5RJs3/uxjlDyg1A9NABkU9EM4xzvSxWHVSS0orF/sH/218OphjH/D8GTFMfmySqpJVs
ZHd+IzzVa54=
-----END RSA PRIVATE KEY-----'''


# 加密
def to_para(plain):
rsa_key = RSA.importKey(pubkey)
x = rsa.encrypt(plain.encode(), rsa_key)
cipher_text = base64.b64encode(x).decode()
return cipher_text


# 解密
def to_decrypt(plain):
rsa_privkey = RSA.importKey(privatekey)
cipher = Cipher_pkcs1_v1_5.new(rsa_privkey)
x = cipher.decrypt(base64.b64decode(plain), "ERROR")
print(x.decode())
return x.decode()


def ByteToHex(bins):
"""
Convert a byte string to it's hex string representation e.g. for output.
"""
return ''.join(["%02X" % x for x in bins]).strip()


def HexToByte(hexStr):
"""
Convert a string hex byte values into a byte string. The Hex Byte values may
or may not be space separated.
"""
return bytes.fromhex(hexStr)


def hex_to_str(s):
return ''.join([chr(int(b, 16)) for b in [s[i:i + 2] for i in range(0, len(s), 2)]])


if __name__ == '__main__':
v = '182895d57f87530e854d9842ff02edaefc66fa1cca66c8f352111b6c5fbf22a9f057e5b74523cdd03f76424064df2c38ce45a68dd5492246e6b832c1b4edaacd8fb4e6050bed5a1a27ae7894d38b62e8453cd77fdbce3529d831e0278ac9e8ad3b8d6002ca82380b5ac61e7a19f773003136d64902c58f2ad563d04ce701c565'
b = bytes.fromhex(v)
k = base64.b64encode(b)
print(to_decrypt(k))
 

Guess you like

Origin www.cnblogs.com/yichuncom/p/10973036.html