Encryption and decryption Based on rsa in Python2.6, python2.6rsa
Generate the private key of the public key:
#-*-Coding: UTF-8-*-import rsaimport base64 (public_key, private_key) = rsa. newkeys (1024) print (chr (10) + "Public Key:") print (public_key.save_pkcs1 () print (chr (10) + "Public Key:") print (public_key.save_pkcs1 ())
Execution result:
Public key: ----- begin rsa public key ----- migjaog1_0g4ds76httoob2nri65l2s5slie4zeedbp + vrzq71juhigzipmywicaf1_krdiaalvvt + signature + Signature = ----- end rsa public key ----- public key: ----- begin rsa private key ----- keys + keys/keys + LO + keys/keys + chcJlrBh/keys BYJ/keys/R6y/keys/jSv7JuqvBX2oA/MGViCuzdQjyK2YV + keys + 1l4FaOM /PSYQEfR/logs/keys + c7V1n0RN6DVnW4kINJ9z9sWQEcF5/Yd + keys = ----- end rsa private key -----
Use the public key and private key for encryption and decryption:
#-*-Coding: UTF-8-*-import rsaimport base64public_key_str = "----- begin rsa public key ----- MIGJAoGBAJ6m + keys/WgC + lHUCwQ6/keys = ----- end rsa public key -----" private_key_str = "" "----- begin rsa private key ----- BEGIN + BEGIN/decrypt + encrypt/decrypt + QopQ6nmsYCApCihnVCJ8hcvERokm9Wgcadfr/fW9dHwDdCB/encrypt/decrypt + BEGIN = ----- end rsa private key ----- "private_key = rsa. privateKey. load_pkcs1 (private_key_str) public_key = rsa. publicKey. load_pkcs1 (public_key_str) msg = "abc12344" encrypt_msg = base64.encodestring (rsa. encrypt (msg, public_key) decrypt_msg = rsa. decrypt (base64.decodestring (encrypt_msg), private_key) print (chr (10) + "original text:") print (msg) print (chr (10) + "encrypted text: ") print (encrypt_msg) print (chr (10) +" decrypted text: ") print (decrypt_msg)
Execution result:
Original Text: abc12344 encrypted text: cxQ/ciphertext + s3n/iuei = decrypted text: abc12344
PS: the header of the public key generated by some RSA modules is ----- BEGIN public key -----. This RSA header cannot be imported to generate public key normally, standard "----- begin rsa public key -----" is required -----".
Encrypted ciphertext through RSA is usually difficult to use. base64 is used for encoding to facilitate transmission between systems.
BASE64 is an encoding method used to encode binary data into writable characters. BASE64 is a reversible encoding method.
##=================================================== ================== ##
Python: You can take it if you think it's useful. It's useless!