[Python3] RSA encryption and decryption and signature / signing experience to achieve - using pycrytodome

 Crypto package description:

pycrypto, pycrytodome and crypto is a thing, crypto python name above is pycrypto it is a third-party library, but have stopped updating, it is not recommended to install the library;

windows under python3.6 version of the above installation is too much trouble (I am Python3.7, trying to install is not successful, try to install if needed, refer to click here), in the case of installation to no avail, you can install pycryptodome, it is the pycrypto extended version, and pycrypto usage is exactly the same;

pip install pycryptodome

After installation is complete, the Python various packages are stored under the reference path, the crypto folder can be changed Crypto.

About RSA algorithm:

RSA encryption algorithm is an asymmetric encryption algorithm ,

Secret key encrypted by a public key and a private key of two parts secret key pair,

The public key used to encrypt the message, the private key is used to decrypt the message ,

The public key is the private key is the user's own retention,

Because the public key is public, so anyone who obtained a public key, you can use the public key to encrypt send fake content, for safety reasons, before sending the message that we can use RSA to sign.

Signature using the private key to sign , using the public key to verify signed by the signature we can ensure the uniqueness of user identities, thereby improving safety.

 

from Crypto.PublicKey Import the RSA
 Import Crypto.Signature.PKCS1_v1_5 sign_PKCS1_v1_5 AS   # for signing / - stamped 
from Crypto.Cipher Import PKCS1_v1_5   # for encryption 
from Crypto Import the Random
 from Crypto Import the Hash 

# manually generate a key pair (the project Usually the key is generated by the development) of, when generating the key pair can be generated by a specified length, is usually recommended 1024bit, 
# 1024bit rsa the public key can only 117byte encrypted data, the data stream is more than the number required encrypting the data segment, 
# currently 1024bit key length has been proven safe enough, to make use of the key length 2048bit, 2048bit key length up to the length of the encrypted data 245byte 
calculated length formula: key length / 8--11 = the maximum amount of encryption (in bytes) 
to generate a pair of keys 2048bit following: 
XRSA.generate = (2048 )
 # Y = RSA.generate (2048, Random.new (). Read) # may be used to assist in generating a pseudo-random number 

S_KEY = x.export_key () # private 
g_key = x.publickey ( ) .export_key () # public 
# Print ( "private key:", S_KEY) 
# Print ( "public key:", g_key) 
 
# write to the file 
# with Open ( "c.pem", "wb") the X-AS : 
#      x.write (S_KEY) 
# with Open ( "d.pem", "WB") AS X: 
#      x.write (g_key) 
 
# import from the file key - public key generated by the private key (public key is not becomes - for the case of a private key known only) - 2 
# with Open ( 'c.pem', 'RB') AS X: 
#      S_KEY RSA.importKey = (X.read())
#. # = New_g_key s_key.publickey () export_key () 
# # Print (new_g_key) 
# 
# CERT = s_key.export_key ( "DER") to generate the certificate # - and it is the unique private key corresponding to 
# Print (CERT) 
 
# implemented RSA asymmetric encryption 
my_private_key = S_KEY   # private 
my_public_key = g_key   # public key

① the use of public - private key information is "encrypted" + "decryption"

'' ' 
Effect: the information is public key cryptography, private key to decrypt. 
Scenario: 
    A copy of the data you want to encrypt transmitted to B, worry about others using symmetric encryption algorithms easily crack (only one key, once the leak, the leak of data), so the use of asymmetric encryption. 
    The receiving party can generate its own secret key pair, namely a public and private key each, and then the public key to others, their own private reserved. 
    
    A data encryption using the public key and then sends the encrypted ciphertext to B, B then decrypts using his private key, so that even if the A's public key and the ciphertext are to give the third party, 
    the third party must know the secret key and the encryption algorithm to decrypt the ciphertext, greatly reducing the risk of data exposure. 
'' ' 
 
DEF encrypt_with_rsa (Plain_Text): 
 
    # first public-key cryptography 
    cipher_pub_obj = PKCS1_v1_5.new (RSA.importKey (my_public_key)) 
    _secret_byte_obj = cipher_pub_obj.encrypt (plain_text.encode ()) 
 
    return _secret_byte_obj 
 
DEF decrypt_with_rsa (_secret_byte_obj): 
 
    # After Private decryption key 
    cipher_pri_obj = PKCS1_v1_5.new(RSA.importKey(my_private_key))
    _byte_obj = cipher_pri_obj.decrypt(_secret_byte_obj, Random.new().read)
    plain_text = _byte_obj.decode()
 
    return plain_text
 
def executer_without_signature():
 
    #加解密验证
    text = "I love CA!"
    assert text == decrypt_with_rsa(encrypt_with_rsa(text))
    print("rsa test success!")

② using the private key - public key information "signature" + "sign test"

'' ' 
Effect: on the decrypted file integrity, authenticity verification (but more complicated insurance practice, rarely used) 
scenario: 
    A file sent to a B after private information to be encrypted, it is feared due to various B causes receive and decrypt the file is not complete, true original file (can be tampered with or missing part), 
    so a sign of the original file before sending the [signature and ciphertext] sent together to make B B Upon receipt of the file to do something with [+ decrypting signed inspection], 
    are after through - only to prove the original documents received by the authenticity, integrity. 
    
'' ' 
DEF to_sign_with_private_key (Plain_Text): 
 
    # private key signature 
    signer_pri_obj = sign_PKCS1_v1_5.new (RSA.importKey (my_private_key)) 
    rand_hash = Hash.SHA256.new () 
    rand_hash.update (plain_text.encode ()) 
    Signature = signer_pri_obj.sign (rand_hash) 
 
    return Signature 
 
DEF to_verify_with_public_key (Signature, Plain_Text): 
 
    # public inspection sign
    verifier = sign_PKCS1_v1_5.new(RSA.importKey(my_public_key))
    _rand_hash = Hash.SHA256.new()
    _rand_hash.update(plain_text.encode())
    verify = verifier.verify(_rand_hash, signature)
 
    return verify #true / false
 
def executer_with_signature():
 
    #签名/验签
    text = "I love CA!"
    assert to_verify_with_public_key(to_sign_with_private_key(text), text)
    print("rsa Signature verified!")
 
if __name__ == '__main__' : 
 
    Executer_without_signature () # encrypt only the signature is not 
 
    executer_with_signature ()   # only signatures do not encrypt 
 
    # combination of the two eating better 
' ' 
if it is encrypted while also signing, this time a little bit complicated. 
1, each sender and receiver need to hold a pair of male private key, which is four keys. 
2, plus the recipient's public and private key for decrypting confidential information 
3, the sender's private key used for signing public confidential information / check-mortem 
4, the sender and the recipient must advance their [public] to inform the other party. 
'' '

Guess you like

Origin www.cnblogs.com/suguangti/p/12100215.html