In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-03-10 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)05/31 Report--
Today, I would like to share with you how to use the pycrypto algorithm in python encryption related knowledge points, detailed content, clear logic, I believe that most people still know too much about this knowledge, so share this article for your reference, I hope you will learn something after reading this article, let's take a look at it.
I. installation
Pycryto can achieve roughly three types of data encryption (one-way encryption, symmetric encryption and asymmetric encryption), generate random numbers, generate key pairs, and digital signatures.
One-way encryption: Crypto.Hash, which includes MD5, SHA1, SHA256, etc.
Symmetric encryption: Crypto.Cipher, such as DES, etc.
Asymmetric encryption: Crypto.Cipher, such as common AES encryption
Random number operation: Crypto.Random, you can also use Python built-in random module and secrets module to generate
Digital signature and verification: you may need to use Crypto.PublicKey,Crypto.Hash,Crypto.Signature
Pip install pycryto II. AES encryption and decryption
You can use AES.new (key, Mode, IV) for encryption settings
Key: length must be 16, 24, or 32 bits
VI: length can only be 16 bits
When decrypting, you must know the key and IV used in encryption, and then decrypt it through the decrypt () method.
From Crypto.Cipher import AES# encryption aes = AES.new ('this is a key 11, AES.MODE_CBC,' this is an iv 222') string = 'autofelix is god'# encrypt () method requires that the encrypted string must also be 16, 24 or 32 bits in length Therefore, it is generally necessary to process the encrypted string result = aes.encrypt (string) # decrypt aes.decrypt (result) 3, SHA encryption from Crypto.Hash import SHA256hash = SHA256.new () hash.update ('Hello, wordstones') # encrypt digest = hash.digest () using the digest () method # encrypt using the hexdigest () method, after which the hexadecimal hexdigest = hash.hexdigest () print (digest, hexdigest) 4, RSA algorithm generates key pairs
RSA is a public key cryptographic algorithm.
The ciphertext of RSA is the result of finding mod N to the E power of the number in the plaintext of the code. That is, do E times multiplication between plaintext and yourself, and then divide the result by N to find the remainder, and the remainder is ciphertext. RSA is a simple encryption algorithm. The combination of E and N is the public key.
For the decryption of RSA, that is, the ciphertext can be decrypted to the D power of the ciphertext, that is, the ciphertext and oneself can be multiplied D times, and then the result can be divided by N to get the remainder. The combination of D and N is the private key.
From Crypto import Randomfrom Crypto.PublicKey import RSA# gets a pseudo-random number generator random_generator = Random.new (). Read# gets a key pair generator instance rsa = RSA.generate (1024, random_generator) # corresponding to the rsa algorithm to generate the private key and save private_pem = rsa.exportKey () with open ('rsa.key') 'w') as f:f.write (private_pem) # generates the public key and saves public_pem = rsa.publickey () .exportKey () with open ('rsa.pub' 'w') as f:f.write (public_pem) # Private key rsa.key results are as follows #-BEGIN RSA PRIVATE KEY-# MIICXQIBAAKBgQDR4Wq9l44lw/thTPyFmSi2hII92EPh90yGXQNL5e7zJPD16j6Q# # tr+tIPNSQaVrnmNwrtqyEC2x4Meyp3tdCWPYUF11r2GgDgxKfUByetNG4XqJeUKk# kJ6D6C706mTf/2zsm8KFoNYCYPX1GhvpiTOikHcNlHLCnOD7jbMAovJg/QIDAQAB# AoGBAIz8V6+0NxC3bg4WoSs9j1PL/5F7zV3lucoogSZi9vjuP89x40Vi/a9XCxye# bHi2lSYEz3P92jQ7QuqIBx6gSCi3p2HLjD5LyQeSSMbPe8KSlf52dBUaPthbBceA# IJSBDrE8MKGpulTQKAJ7K3zQUOP2ZZgcKxq2jcQgS6iTENIBAkEA5r7emvwuL0Ob# Maav4o1Ovb5c6OL7bSm1tuLPSKl05WuNYfE6LkqiwOOn5lPvsqhwyI1dJeywVeQz# E+PvcTUR7QJBAOjZ8PxnP5T14fuhbfko4d24Ev+iiTBdq3pMXWvobEFL1ljV6aYE# 2JAiMjO/Fzd1WgZhWPa3P+diyTs9mART6VECQQC0LeEXdsn9oDYEbFu1dZBB++8C# 75NTJ5m8iJlB7QjZyMUq8Ln0wdUa9+n4ohxvDraa9EADSDJdr4bvBjLH3J/1AkBr# 9QfO7kvDU5DXqoujVnoJ4xsj3IbAnt0vEZLKwfLW/0M84si2SU7i3IfsB+/KraT0# ilPF50ZAkEN+LNt7PjBRAkAHBBPME7IbFqxi5Cc/6R12DOMiJbOLDTS12b1J1cwG# p8WMIERsvwWdJw+4NdqjbJcjzeGrXhDBi//JU902TAwy#-END RSA PRIVATE KEY-# public key rsa.pub knot The results are as follows: #-BEGIN PUBLIC KEY-# # MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDR4Wq9l44lw/thTPyFmSi2hII9# 2EPh90yGXQNL5e7zJPD16j6Qtr+tIPNSQaVrnmNwrtqyEC2x4Meyp3tdCWPYUF11# r2GgDgxKfUByetNG4XqJeUKkkJ6D6C706mTf/2zsm8KFoNYCYPX1GhvpiTOikHcN# lHLCnOD7jbMAovJg/QIDAQAB#-END PUBLIC KEY- 5. Use key to encrypt and decrypt
Usually, when communicating, the sender uses the receiver's public key to encrypt, and the receiver uses the receiver's private key to decrypt it.
Import cgi Base64from Crypto.PublicKey import RSAfrom Crypto.Signature import PKCS1_v1_5from Crypto.Hash import SHA256import hashlib# the string message = 'autofelix is god'# to encrypt the content rsa using the public key with open (' rsa.pub') as f:key = f.read () rsakey = RSA.importKey (key) cipher = Cipher_pkcs1_v1_5.new (rsakey) cipher_text = base64.b64encode (cipher.encrypt (message)) print (cipher_text) # use the private key pair Content is decrypted by rsa with open ('rsa.key') as f:key = f.read () rsakey = RSA.importKey (key) cipher = Cipher_pkcs1_v1_5.new (rsakey) text = cipher.decrypt (base64.b64decode (encrypt_text)) Random_generator) print (text) VI. Countersign and verify import datetime, randomimport requestsimport hashlibimport json, base64from Crypto.PublicKey import RSAfrom Crypto.Signature import PKCS1_v1_5from Crypto.Hash import SHA256from Crypto.Cipher import AES# countersignature def sign (signflag,keypath,baseRequest): # http request bodyprint (baseRequest) # countersign flag if not signflag:return baseRequestelse:# fetch business data in the request body businessdata = json.dumps (baseRequest ["data"]) # read the private key (.key format) Can be generated using openssl or java.keytools) with open (keypath,'r') as rsaKeyFile:rsaKey = rsaKeyFile.read () .replace ("\ n",') print (rsaKey) rsaKeyBytes = base64.b64decode (rsaKey) print (rsaKeyBytes) # SHA256 Summary RSA encryption Prikey = RSA.importKey (rsaKeyBytes) signer = PKCS1_v1_5.new (priKey) hash_obj = SHA256.new (business_data.encode ('utf-8')) signature = base64.b64encode (signer.sign (hash_obj)) print (signature) # add the signature to the request body and return baseRequest [' sign'] = signature.decode () print (baseRequest) return baseRequest# signature verification def validata (signflag,cerpath) Res): if not signflag:return reselse:# fetch business data and signature data = res ['data'] sign = res [' sign'] # where cer has been converted to pem format Use the openssl tool # openssl x509-inform der-pubkey-noout-in xxxxx.cer > xxxxx.pemcert = open (cerpath). Read (). Replace ("- BEGIN PUBLIC KEY-\ n", "). Replace ("-END PUBLIC KEY-\ n ","). Replace ("\ n" ") print (cert) # check logic with signature pubBytes = base64.b64decode (cert) pubKey = RSA.importKey (pubBytes) signer = SHA256.new (json.dumps (data) .encode (" utf-8 ") verifier = PKCS1_v1_5.new (pubKey) return verifier.verify (signer,base64.b64decode (sign)) above is all the content of the article" how to encrypt using pycrypto algorithm in python " Thank you for reading! I believe you will gain a lot after reading this article. The editor will update different knowledge for you every day. If you want to learn more knowledge, please pay attention to the industry information channel.
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.