Python development [module]: M2Crypto RSA encryption and decryption, m2cryptorsa
M2Crypto Module
Quick installation:
# Environment centos7.0: openssl is installed in advance (self-installed by Baidu). windows cannot be installed. For now, [root @ localhost ~] is not considered. # Pip install m2crypto # verification >>> import M2Crypto >>>
Preparations:
# Run the following command on centos to generate the public key and private key [root @ localhost ~] # Openssl genrsa-out key. pem1024 [root @ localhost ~] # Openssl rsa-in key. pem-pubout-out pubkey. pem
-----BEGIN RSA PRIVATE KEY-----MIICXAIBAAKBgQDhhyVxmY/TU/buuIfwlykV1d5Wg5PRu4Qu14LssRhZH9E9pVbXlGeP1Q8iJEErHt4Rk5tsFgavDf+L5QIM8zpmydJqbivUJCY/5b9zSwVSnDhFfGajLY4Bj7Fq0yngRkxwUVaTmJ/u0FiKzy1mpnk0Xmj/pk7AburWj3YHVsYtuwIDAQABAoGATYKhP9XDNKJa79jD/9Az8qk6bQlzuFV2LJMtECQddiQVSdaVbio3HZvgQ5+qNiO5ttjARfmb+nYZKf9fIQxHOX9GJeepzkvltZJO0LheS0+ZsX2ab62cv8ThUndfyp/thuqHHXt7ERYIHS7CzvzPUQ303OEA9a6WLDaTL/MpjEECQQD5G5cJrEAL1rGF0ELSRl0YRRRyywmGmc0Wlx0VHCyqG0/5GgmPJmB+8t7k7CtTgRhzStYSmwExziohylL3vpgTAkEA58SKxKezIGcuFbCB54yuWEtgauYNrBYauQLC7+Z9d6NjFUrcHO001cVJ0cvIK++hvvOrCIUpq/86N8JFUyWYuQJACnH5t1IdrWFnODEvXBnPNYFQBjA1SguQ6e2ULppr1QYoKE3LMNFvImOUrQyqFGpJWCw/JbCSMEBwy9HsAK9hOQJAIV6vDDmJFPVGMWFEku4yfAv+SeXtugVEu7amEpyBHCSuM3af0ppkrRLG2ioZHBpYk4HJ8mQZ5+XLoBOcn6geIQJBAIcFTwZETKFs1h6dov3Bp6EPq8zZBABvy7fhCsQk9uX66lI0pty9E3KUWGTw4AVp3EwGTc7OqLfiZQTgV65eBcA=-----END RSA PRIVATE KEY-----
Key. pem
-----BEGIN PUBLIC KEY-----MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDhhyVxmY/TU/buuIfwlykV1d5Wg5PRu4Qu14LssRhZH9E9pVbXlGeP1Q8iJEErHt4Rk5tsFgavDf+L5QIM8zpmydJqbivUJCY/5b9zSwVSnDhFfGajLY4Bj7Fq0yngRkxwUVaTmJ/u0FiKzy1mpnk0Xmj/pk7AburWj3YHVsYtuwIDAQAB-----END PUBLIC KEY-----
Pubkey. pem
How to Use
1. Private Key Encryption:
Import M2Cryptoimport json # private key encryption def pri_encrypt (msg, file_name): rsa_pri = M2Crypto. RSA. load_key (file_name) # import the key <M2Crypto. RSA. RSA instance at 0x24da8c0> ctxt_pri = rsa_pri.private_encrypt (msg, M2Crypto. RSA. pkcs1_padding) # The encryption filling method is used here, so it must be matched during decryption. Print (ctxt_pri, type (ctxt_pri) ctxt64_pri = ctxt_pri.encode ('base64') # ciphertext is base64 and can only be written to base64 to save the encode into str print ('ciphertext: % s' % ctxt64_pri, type (ctxt64_pri) return ctxt64_priprikey_file = 'Key. pem 'data = {'name': 'jefrey'} message = json. dumps (data) pri_encrypt (message, prikey_file) # print # ("\ x8e \ xc8 \ x98 \ xea \ xd5 % & \ xe3 \ xfa \ xa5 \ xbbu]; zZ \ xf0 \ xc1 \ xdd \ xf3 \ x8f \ xaa \ xdc \ xfa \ xbc \ xacg \ xfd \ x0b3 \ xbba \ x94K \ x91ta \ xda # \ xdf \ xd05 \ xecV \ xb1 \ xff \ xf0 \ xc4 \ x07 \ xbf \ x1c \ xe0 \ xfc \ x84 & \ xfcp \ xf5 \ xab \ xd8 \ xf2 # \ xfc \ xce:] \ xbae] W47 \ xf7 \ xc9 \ x9aXt \ xff \ # xe9 \ xda \ x19 \ x82 \ xecDP \ xb2 \ xcb \ xd3 \ x8d @ \ x81F \ x9f} \ xfb \ x8b \ xb1o> \ x91 \ xf0G \ xc36 \ x19Q \ xf8 \ x7f \ xaf \ xbe \ xa2 \ xee \ xf0V \ x88 \ # xbd [\ x1e3 \ xaf \ xf0 \ xd3 \ xebu \ xa9 ", <type 'str'>) # ('\ xe5 \ xaf \ x86 \ xe6 \ x96 \ x87: jsggmOrVJSbj + kernel + rysZ/kernel/QNexWsf/wxAe/HOD8hCb8 \ ncPVcq9jyI/zO # kernel/kernel + kfBHwzYZUfh/r76i \ kernel = \ n', <type 'str'>)
2. Public Key decryption(File path ):
Import M2Cryptoimport json # private key encryption def pri_encrypt (msg, file_name): rsa_pri = M2Crypto. RSA. load_key (file_name) # import the key ctxt_pri = rsa_pri.private_encrypt (msg, M2Crypto. RSA. pkcs1_padding) # Use the encrypted pkcs1_padding encryption mode. Ctxt64_pri = ctxt_pri.encode ('base64') # The ciphertext is base64 and can only be written to base64 to save the encode as str print ('ciphertext: % s' % ctxt64_pri, type (ctxt64_pri )) return ctxt64_pri # Public Key decryption input file path def pub_decrypt (msg, file_name): rsa_pub = M2Crypto. RSA. load_pub_key (file_name) ctxt_pri = msg. decode ("base64") # convert str to base64 maxlength = 128 #128-bit output = ''while ctxt_pri: input = ctxt_pri [: 128] ctxt_pri = ctxt_pri [128:] out = rsa_pub.public_decrypt (input, M2Crypto. RSA. pkcs1_padding) # decrypt output = output + out print ('plaintext: % s' % output, type (output) print ('json: % s' % Json. loads (output), type (json. loads (output) prikey_file = 'Key. pem 'pubkey _ file = 'pubkey. pem 'data = {'name': 'jefrey'} message = json. dumps (data) primsg = pri_encrypt (message, prikey_file) pub_decrypt (primsg, pubkey_file) # print # ('\ xe6 \ x98 \ x8e \ xe6 \ x96 \ x87: {"name": "Jefrey"} ', <type 'str'>) # ("Json: {u'name': u'jefrey '}", <type 'dict '>)
3. Public Key decryption(String ):
Import M2Cryptoimport json # private key encryption def pri_encrypt (msg, file_name): rsa_pri = M2Crypto. RSA. load_key (file_name) # import the key ctxt_pri = rsa_pri.private_encrypt (msg, M2Crypto. RSA. pkcs1_padding) # Use the encrypted pkcs1_padding encryption mode. Ctxt64_pri = ctxt_pri.encode ('base64') # The ciphertext is base64 and can only be written to base64 to save the encode as str # print ('ciphertext: % s' % ctxt64_pri, type (ctxt64_pri )) return ctxt64_pri # input string def pub_decrypt (msg, pub_key): bio = M2Crypto. BIO. memoryBuffer (pub_key) rsa_pub = M2Crypto. RSA. load_pub_key_bio (bio) ctxt_pri = msg. decode ("base64") # convert str to base64 output = rsa_pub.public_decrypt (ctxt_pri, M2Crypto. RSA. pkcs1_padding) # decrypt print ('plaintext: % s' % output, type (output) print ('json: % s' % Json. loads (output), type (json. loads (output) prikey_file = 'Key. pem 'pubkey _ file = 'pubkey. pem 'data = {'name': 'jefrey'} message = json. dumps (data) primsg = pri_encrypt (message, prikey_file) with open (pubkey_file, 'r + ') as f: pub_key = f. read () pub_decrypt (primsg, pub_key) # print # ('\ xe6 \ x98 \ x8e \ xe6 \ x96 \ x87: {"name": "Jefrey "}', <type 'str'>) # ("Json: {u'name': u'jefrey'}", <type 'dict '>)
Conclusion: The private key is encrypted and the Public Key is decrypted. The opposite is true,Public_encrypt public key encryption,Private_decrypt Private Key decryption;