Python has a certificate encryption and decryption implementation method _python

Source: Internet
Author: User
Tags base64 decrypt sha1

The example in this article describes the cryptographic decryption implementation method for Python with certificates. Share to everyone for your reference. The implementation methods are as follows:

Recently doing Python encryption and decryption work, while adding a secret string can be solved in PHP, online also found some reliable information, just also have time I summed up the python in the encryption and decryption of this piece of code, may still be used in the future. As opposed to PHP, Python has more encryption and decryption components, respectively:

Python-crypto-This component is the basic component and the functions used are relatively complex.
Ezpycrypto-relatively simple, but he made out of the public key can not be compatible with other programs sslcrypto-and Ezpycrypto is the same as the author of the development, efficiency than ezpycrypto better. But the same cannot be compatible with other programs.
Pyopenssl-seems to be used on HTTPS communications, and I can't find the use of decryption.
M2crypto-finally let me find, but it has a major disadvantage, it is the bottom of the SWIG with the OpenSSL handover.
Installing the Swig program in Windows is very difficult.

I choose to use M2crypto, the public key and private key certificate generation has two ways, one uses RSA generation, the other is X509 generation. I will be the two encryption and decryption code to share, for everyone to refer to, but reprint or use, please specify the source.

A certificate generated by the RSA standard method

1. Encrypt and decrypt, encrypt signature, verify encrypted signature

Copy Code code as follows:
#encoding: UTF8
Import OS
Import M2crypto
#随机数生成器 (1024-bit random)
M2Crypto.Rand.rand_seed (Os.urandom (1024))
#生成一个1024位公钥与私密钥证书
Geekso = M2Crypto.RSA.gen_key (1024, 65537)
Geekso.save_key (' Jb51.net-private.pem ', None)
Geekso.save_pub_key (' Jb51.net-public.pem ')
#使用公钥证书加密开始
Writersa = M2Crypto.RSA.load_pub_key (' Jb51.net-public.pem ')
ciphertext = Writersa.public_encrypt ("This is a secret message that can only be decrypted with the private key", M2Crypto.RSA.pkcs1_oaep_padding)
Print "Encrypted string is:"
Print Ciphertext.encode (' base64 ')
#对加密串进行签名
Msgdigest = M2Crypto.EVP.MessageDigest (' SHA1 ')
Msgdigest.update (ciphertext)
#提示, you can also use the private key signature here
#WriteRSA = M2Crypto.RSA.load_key (' Jb51.net-private.pem ')
#Signature = Writersa.sign_rsassa_pss (Msgdigest.digest ())
Signature = Geekso.sign_rsassa_pss (Msgdigest.digest ())
Print "The signature string is:"
Print Signature.encode (' base64 ')
#使用私钥证书解密开始
Readrsa = M2Crypto.RSA.load_key (' Jb51.net-private.pem ')
Try
plaintext = Readrsa.private_decrypt (ciphertext, M2Crypto.RSA.pkcs1_oaep_padding)
Except
Print "Decryption Error"
plaintext = ""
If plaintext:
Print "The decrypted string is:"
Print plaintext
# Verify the signature of the cryptographic string
Msgdigest = M2Crypto.EVP.MessageDigest (' SHA1 ')
Msgdigest.update (ciphertext)
#提示, if it's signed with the private key, verify with the public key
#VerifyRSA = M2Crypto.RSA.load_pub_key (' Alice-public.pem ')
#VerifyRSA. VERIFY_RSASSA_PSS (Msgdigest.digest (), Signature)
If GEEKSO.VERIFY_RSASSA_PSS (Msgdigest.digest (), Signature) = = 1:
Print "Signature is correct"
Else
Print "Not signed correctly"

2. String generation signature, verification signature

Copy Code code as follows:
#用私钥签名
SIGNEVP = M2Crypto.EVP.load_key (' Jb51.net-private.pem ')
Signevp.sign_init ()
Signevp.sign_update (' signature string from this guest (http://www.jb51.net) ')
Stringsignature = Signevp.sign_final ()
The print "signature string is:"
Print Stringsignature.encode (' base64 ')
#用公钥验证签名
PubKey = M2Crypto.RSA.load_pub_key (' Jb51.net-public.pem ')
VERIFYEVP = M2Crypto.EVP.PKey ()
Verifyevp.assign_rsa (PubKey)
Verifyevp.verify_init ()
Verifyevp.verify_update (' signature string from this guest (http://www.jb51.net) ')
If verifyevp.verify_final (stringsignature) = = 1:
The print string was successfully validated. "
Else
Print "String validation failed!"

3. Add a password to the certificate

The advantage of adding a password to a certificate is that even if the certificate is taken, no password is used.

Copy Code code as follows:
def passphrase (v):
Return ' 4567890 '

Use when generating certificates
Copy Code code as follows:
Geekso.save_key (' Jb51.net-private.pem ', callback=passphrase)

Use a certificate when using
Copy Code code as follows:
Readrsa = Rsa.load_key (' Jb51.net-private.pem ', passphrase)

Second, the X509 standard way to generate the certificate

1. Generate certificates, public key files, private key files

Copy Code code as follows:
Import time
From M2crypto import X509, EVP, RSA, ASN1
Def issuer_name ():
"""
Certificate Publisher name (exclusive name).
Parameters:
None
return:
X509 the standard issuer obj.
"""
Issuer = X509. X509_name ()
Issuer. C = "CN" # Country name
Issuer. CN = "*.jb51.net" # Ordinary Name
Issuer. ST = "Hunan Changsha"
Issuer. L = "Hunan Changsha"
Issuer. O = "Geekso company LTD"
Issuer. OU = "Geekso company LTD"
Issuer. Email = "123456@qq.com"
return issuer
def make_request (Bits, CN):
"""
Create a request for a X509 standard.
Parameters:
BITS = number of certificate digits
CN = Certificate Name
return:
Returns X509 request with private key (EVP).
"""
RSA = Rsa.gen_key (Bits, 65537, None)
PK = EVP. Pkey ()
Pk.assign_rsa (RSA)
req = X509. Request ()
Req.set_pubkey (PK)
Name = Req.get_subject ()
Name. C = "US"
Name. CN = CN
Req.sign (PK, ' sha256 ')
return req, PK
def make_certificate_valid_time (cert, days):
"""
The certificate is valid for a few days from the current time.
Parameters:
Cert = Certificate obj
Days = day of certificate expiration
return:
None
"""
t = Long (Time.time ()) # Get current time
Time_now = ASN1. Asn1_utctime ()
Time_now.set_time (t)
Time_exp = ASN1. Asn1_utctime ()
Time_exp.set_time (t + days * 24 * 60 * 60)
Cert.set_not_before (Time_now)
Cert.set_not_after (TIME_EXP)
def make_certificate (bits):
"""
Create a certificate
Parameters:
bits = number of digits in the card fast
return:
Certificate, private key key (EVP), and public key key (EVP).
"""
Req, pk = make_request (bits, "localhost")
PUK = Req.get_pubkey ()
Cert = X509. X509 ()
Cert.set_serial_number (1) # Certificate sequence Case number
Cert.set_version (1) # certificate version
Cert.set_issuer (Issuer_name ()) # Issuer Information
Cert.set_subject (Issuer_name ()) # Topic information
Cert.set_pubkey (PUK)
Make_certificate_valid_time (cert, 365) # Expiration time of certificate
Cert.sign (PK, ' sha256 ')
Return cert, PK, PUK
# Start creating
Cert, PK, puk= make_certificate (1024)
Cert.save_pem (' Jb51.net-cret.pem ')
Pk.save_key (' Jb51.net-private.pem ', cipher = None, callback = Lambda:none)
Puk.get_rsa (). Save_pub_key (' Jb51.net-public.pem ')

2. Use certificate encryption, private key file decryption

Copy Code code as follows:
def geekso_encrypt_with_certificate (Message, Cert_loc):
"""
Cert certificate encryption, can be decrypted with the private key file.
Parameters:
Message = string to encrypt
Cert_loc = cert Certificate path
return:
Cryptographic string or exception string
"""
Cert = X509.load_cert (Cert_loc)
PUK = Cert.get_pubkey (). Get_rsa () # Get RSA for encryption
Message = Base64.b64encode (message)
Try
encrypted = Puk.public_encrypt (message, rsa.pkcs1_padding)
Except RSA. Rsaerror as E:
Return "ERROR encrypting" + e.message
return encrypted
encrypted = Geekso_encrypt_with_certificate (' www.jb51.net ', ' Jb51.net-cret.pem ')
print ' cipher string ', encrypted
def geekso_decrypt_with_private_key (Message, Pk_loc):
"""
Cryptographic strings generated by the private key decryption certificate
Parameters:
Message = encrypted string
Pk_loc = Private Key Path
return:
Decrypting a string or exception string
"""
PK = Rsa.load_key (pk_loc) # load RSA for decryption
Try
decrypted = pk.private_decrypt (message, rsa.pkcs1_padding)
decrypted = Base64.b64decode (decrypted)
Except RSA. Rsaerror as E:
Return "ERROR decrypting" + e.message
Return decrypted
print ' Decrypt string ', Geekso_decrypt_with_private_key (encrypted, ' JB51.NET-PRIVATE.PEM ')

3. With private key encryption, certificate decryption

Copy Code code as follows:
def geekso_encrypt_with_private_key (Message,pk_loc):
"""
Private key encryption
Parameters:
Message = encrypted string
Pk_loc = Private Key Path
return:
Cryptographic string or exception string
"""
Readrsa = Rsa.load_key (Pk_loc);
Message = Base64.b64encode (message)
Try
encrypted = Readrsa.private_encrypt (message,rsa.pkcs1_padding)
Except RSA. Rsaerror as E:
Return "ERROR encrypting" + e.message
return encrypted
encrypted = Geekso_encrypt_with_private_key (' www.jb51.net ', ' Jb51.net-private.pem ')
Print encrypted
def geekso_decrypt_with_certificate (Message, Cert_loc):
"""
Cert Certificate decryption.
Parameters:
Message = string to decrypt
Cert_loc = cert Certificate path
return:
decrypted string or exception string
"""
Cert = X509.load_cert (Cert_loc)
PUK = Cert.get_pubkey (). Get_rsa ()
Try
Decrypting = puk.public_decrypt (message, rsa.pkcs1_padding)
Decrypting = Base64.b64decode (decrypting)
Except RSA. Rsaerror as E:
Return "ERROR decrypting" + e.message
Return decrypting
Decrypting = geekso_decrypt_with_certificate (encrypted, ' JB51.NET-CRET.PEM ')
Print decrypting

4. With private key signature, certificate authentication signature

Copy Code code as follows:
def geekso_sign_with_private_key (message, pk_loc, base64 = True):
"""
Private key Signature
Parameters:
Message = string to be signed
Pk_loc = Private Key Path
Base64 = True (bease64 processing) False (16-in-process)
return:
String or exception string after signature
"""
PK = Evp.load_key (Pk_loc)
Pk.sign_init ()
Try
Pk.sign_update (Message)
Signature = Pk.sign_final ()
Except EVP. Evperror as E:
Return "ERROR signature" + E.message
Return Signature.encode (' base64 ') if Base64 is True else Signature.encode (' hex ')
Signature = Geekso_sign_with_private_key (' www.jb51.net ', ' Jb51.net-private.pem ')
Print signature
def geekso_verifysign_with_certificate (message, signature, cert_loc, base64 = True):
"""
Certificate Verification Signature
Parameters:
Message = string with original signature
Signature = string after signature
Cert_loc = Certificate Path file
Base64 = True (bease64 processing) False (16-in-process)
return:
Successful or failed string or exception string
"""
Signature = Signature.decode (' base64 ') if Base64 is True else Signature.decode (' hex ')
Cert = X509.load_cert (Cert_loc)
PUK = Cert.get_pubkey (). Get_rsa ()
Try
VERIFYEVP = EVP. Pkey ()
Verifyevp.assign_rsa (PUK)
Verifyevp.verify_init ()
Verifyevp.verify_update (Message)
Verifysign = verifyevp.verify_final (signature)
If verifysign = 1:
Return ' success '
else:
Return ' failed '
Except EVP. Evperror as E:
Return "ERROR Verify Sign" + e.message

Print geekso_verifysign_with_certificate (' www.jb51.net ', signature, ' Jb51.net-cret.pem ')

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.