God-level programmers bring: the implementation method of encryption and decryption with the Python certificate!

Source: Internet
Author: User
Tags base64 sha1

This paper describes the implementation method of encryption and decryption of Python with certificates. Share to everyone for your reference. The implementation method is as follows:

Recently in Python to do the encryption and decryption work, at the same time add a secret string can be solved in PHP, online also found some reliable information, just have time I summed up the python in the encryption and decryption of this piece of code, in the future may still be used. Compared to PHP, Python has a large number of encryption and decryption components, namely:

I. Certificate generated by RSA Standard mode

1. Encrypt the decryption, encrypt the signature, verify the encrypted signature

The code is 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 "The encrypted string is:"

Print Ciphertext.encode (' base64 ')

#对加密串进行签名

Msgdigest = M2Crypto.EVP.MessageDigest (' SHA1 ')

Msgdigest.update (ciphertext)

#提示, you can also use a private key to sign

#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 signed 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 encrypted string

Msgdigest = M2Crypto.EVP.MessageDigest (' SHA1 ')

Msgdigest.update (ciphertext)

#提示, if you signed it with a private key, verify it 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 "signed correctly"

Else

Print "Signature is incorrect"

2. String to generate signature, verify signature

The code is 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 ()

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:

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.

The code is as follows:

def passphrase (v):

Return ' 4567890 '

When generating the certificate, use the

The code is as follows:

Geekso.save_key (' Jb51.net-private.pem ', callback=passphrase)

When using certificates

The code is as follows:

Readrsa = Rsa.load_key (' Jb51.net-private.pem ', passphrase)

II. certificate generated by X509 standard 1. Generate certificate, public key file, private key file

The code is as follows:

Import time

From M2crypto import X509, EVP, RSA, ASN1

Def issuer_name ():

"""

The name of the certificate issuer (the distinguished name).

Parameters:

None

Return:

The issuer of the X509 standard, obj.

"""

Issuer = X509. X509_name ()

Issuer. C = "CN" # Country name

Issuer. CN = "*.jb51.net" # Common name

Issuer. ST = "Hunan Changsha"

Issuer. L = "Hunan Changsha"

Issuer. O = "GEEKSO Company Ltd."

Issuer. OU = "GEEKSO Company Ltd."

Issuer. email = "[Email protected]"

return issuer

def make_request (Bits, CN):

"""

Creates a request for a X509 standard.

Parameters:

BITS = number of certificate bits

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

Day = number of days the certificate expires

Return:

None

"""

t = Long (Time.time ()) # Gets the 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 with a fast pass

Return:

Certificate, private 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 Order example number

Cert.set_version (1) # Version of the certificate

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 the 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

The code is as follows:

def geekso_encrypt_with_certificate (Message, Cert_loc):

"""

The CERT certificate is encrypted and can be decrypted with the private key file.

Parameters:

Message = string to encrypt

Cert_loc = cert Certificate path

Return:

Encrypt 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 ' Encrypt string ', encrypted

def geekso_decrypt_with_private_key (Message, Pk_loc):

"""

Cryptographic string 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 ' decryption string ', Geekso_decrypt_with_private_key (encrypted, ' JB51.NET-PRIVATE.PEM ')

3. Encryption with private key, certificate decryption

The code is as follows:

def geekso_encrypt_with_private_key (Message,pk_loc):

"""

Private key encryption

Parameters:

Message = encrypted string

Pk_loc = Private Key Path

Return:

Encrypt 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 = the string to decrypt

Cert_loc = cert Certificate path

Return:

The 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. Signing with a private key, certificate authentication

The code is 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 binary processing)

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 validation Signature

Parameters:

Message = The string that was originally signed

Signature = string after signature

Cert_loc = Certificate Path file

Base64 = True (bease64 processing) False (16 binary processing)

Return:

Success or failure 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 ')

Hopefully this article will help you with Python programming.

Welcome to join my thousand People Exchange learning questions: 125240963

God-level programmers bring: the implementation method of encryption and decryption with the Python certificate!

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.