Python to implement a certificate-free encryption and decryption instance _python

Source: Internet
Author: User
Tags base64

The example of this article is about Python encryption and decryption method without certificate, share for everyone reference. The implementation methods are as follows:

No certificate encryption is the two sides do not need to maintain the certificate, encryption and decryption only need to agree on a key can be, no certificate and decryption way to apply more widely, Python official also has the relevant examples, address is: https://pypi.python.org/pypi/ Pycrypto, the main use is from Crypto.cipher import AES This module, the code is as follows:

Copy Code code as follows:
'''
/**
* AES Encrypted string
*
* @param string data-encrypted string
* @param string Key key (only 16, 24, 32 bits)
* @param string IV 16-bit length vector
* @param BOOL Encoding format (true:base64/false: hexadecimal)
* The result of @return string encryption
*/
'''
def ENCRYPT_MODE_CBC (data, key, IV = ' www.jb51.net!! ', base64 = True):
Lenth = Len (data)
num = lenth% 16
data = Data.ljust (Lenth + 16-num)
obj = Aes.new (key, AES. MODE_CBC, IV)
result = Obj.encrypt (data)
Return Result.encode (' base64 ') if Base64 is True else Result.encode (' hex ')
Encrypt = ENCRYPT_MODE_CBC (' Hello Geekso ', ' www.jb51.net!! ')
Print Encrypt
'''
/**
* AES Decryption string
*
* @param string encrypted the string to be decrypted
* @param string Key key
* @param string IV 16-bit length vector
* @param bool Encoding (true:base64/false: hexadecimal)
* Result of @return string decryption or bool
*/
'''
def DECRYPT_MODE_CBC (encrypted, key, IV = ' www.jb51.net!! ', base64 = True):
encrypted = Encrypted.decode (' base64 ') if Base64 is True else Encrypted.decode (' hex ')
If encrypted is not ':
obj = Aes.new (key, AES. MODE_CBC, IV)
return Obj.decrypt (encrypted)
Else
Return False

Print DECRYPT_MODE_CBC (encrypt, ' www.jb51.net!! ')
Exit ()

I hope this article will help you with your Python programming.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.