Python’s standard library has you covered in the hashlib module. It includes the FIPS secure hash algorithms SHA1, SHA224, SHA256, SHA384, and SHA512 as well as RSA’s MD5 algorithm.
1 2 3 4 5 6 7
import hashlib md5 = hashlib.md5() # md5.update('I Love Python') # Unicode-objects must be encoded before hashing md5.update(b'I Love Python') md5.digest() hashlib.sha256(b'I Love Python').hexdigest()
key : it’s 8 bytes
Pad function: pad any string out with spaces until it’s a multiple of 8
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
from Cryptodome.Cipher import DES
key = b'abcdefgh'
defpad(text): text = text.decode() while len(text) % 8 != 0: text+= ' ' return bytes(text,'utf-8')
des = DES.new(key, DES.MODE_ECB) text = b'I Love Python' # encrypted_text = des.encrypt(text) # Data must be aligned to block boundary in ECB mode padded_text = pad(text) # b'I Love Python ' encrypted_text = des.encrypt(padded_text) encrypted_text des.decrypt(encrypted_text)
b'y\x9aM\xac\x17Y\x8f\xfc^\xa5p\x14Lq\xb6\x0e'
b'I Love Python '
If you want to encrypt your data with RSA, then you’ll need to either have access to a public / private RSA key pair or you will need to generate your own.
Ok Let’s we will just generate our own.
1 2 3 4 5 6 7 8 9 10 11 12
from Cryptodome.PublicKey import RSA code = 'nobodyknows' key = RSA.generate(2048) # an RSA key of 2048 bits encrypted_key = key.exportKey(passphrase=code, pkcs=8, protection="scryptAndAES128-CBC") # private key. # which PKCS standard to use and which encryption scheme to use
with open('my_private_rsa_key.bin', 'wb') as f: f.write(encrypted_key) with open('my_rsa_public.pem', 'wb') as f: f.write(key.publickey().exportKey())
1865
450
Encrypting a File
For this example we are going to be using a hybrid encryption method, so we use PKCS1 OAEP, which is Optimal asymmetric encryption padding. This allows us to write a data of an arbitrary length to the file. Then we create our AES cipher, create some data and encrypt the data. This will return the encrypted text and the MAC. Finally we write out the nonce, MAC (or tag) and the encrypted text.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
from Cryptodome.PublicKey import RSA from Cryptodome.Random import get_random_bytes from Cryptodome.Cipher import AES, PKCS1_OAEP
with open('encrypted_data.bin', 'wb') as out_file: recipient_key = RSA.import_key(open('my_rsa_public.pem').read()) session_key = get_random_bytes(16)
cipher_aes = AES.new(session_key, AES.MODE_EAX, nonce) data = cipher_aes.decrypt_and_verify(ciphertext, tag)
print(data)
b'blah blah blah Python blah blah'
Cryptography
The cryptography package aims to be “cryptography for humans” much like the requests library is “HTTP for Humans”.
The Fernet module implements an easy-to-use authentication scheme that uses a symmetric encryption algorithm which guarantees that any message you encrypt with it cannot be manipulated or read without the key you define. The Fernet module also supports key rotation via MultiFernet.
1 2 3 4 5 6 7 8 9
from cryptography.fernet import Fernet cipher_key = Fernet.generate_key() cipher_key cipher = Fernet(cipher_key) text = b'My super secret message' encrypted_text = cipher.encrypt(text) encrypted_text decrypted_text = cipher.decrypt(encrypted_text) decrypted_text
b'IIW_KsInMPbTR60cyxD8nza5RKv_noP_3_bUeoyrqYY='
b'gAAAAABaq148thkx3uK066S-J59eUdIG8UptOUnKAYVvHGpjjszje5WYX64lICXjgHRbalqFs8RU9V_ovABgO4U-9py6qDwHMAp5Qx4SjyIePb-IFZ0I0y8='
b'My super secret message'
Parse Netease Music
We want to download comments from this url,but the data was encrypted with some methods, then we want to find the the cipher out
URL : http://music.163.com/#/song?id=36990266
First Download Core.js and Simulate the requests using fiddler
conn = psycopg2.connect(database="demo", user="lysql", password="123456", host="127.0.0.1", port="5432") try: cursor = conn.cursor() transaction = cursor.execute("""CREATE TABLE MUSIC( ID SERIAL PRIMARY KEY NOT NULL, TIME BIGINT NOT NULL, CONTENT TEXT NOT NULL, LIKEDCOUNT INT NOT NULL, NICKNAME TEXT NOT NULL, USERID BIGINT NOT NULL, AVATARURL TEXT NOT NULL, AVATARPATH TEXT NOT NULL); """) print('Successful') conn.commit() except (Exception, psycopg2.DatabaseError) as error: print(error) finally: print(conn) if conn isnotNone: conn.close()
from Cryptodome.Cipher import AES from Cryptodome import Random from Cryptodome.Util.Padding import pad from hashlib import md5 from base64 import b64encode import requests from requests import RequestException import json import codecs import time import os
defget_json(url): s = requests.Session() data=get_params() try: r = requests.post(url, headers=headers, data=data,allow_redirects=True) if r.status_code == 200: return r.json() else: if response.history: # for his in r.history: # print (his.status_code, his.url) print("Request was redirected to ", r.url) try: rr = requests.post(url, headers=headers, data=data) if rr.status_code == 200: return rr.json() return(rr.status_code) except RequestException: return"Redirected, But Some Still thing Wrong!!!" except RequestException as e: returnNone # json_text = get_json("http://music.163.com/weapi/v1/resource/comments/R_SO_4_36990266?csrf_token=") # json_text
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
defsave_avatar(url,nickname): ifnot os.path.exists("avatars"): os.mkdir("avatars") try: response = requests.get(url) if response.status_code == 200: file_path = '{0}/{1}.{2}'.format("avatars", md5(response.content).hexdigest(), 'jpg') ifnot os.path.exists(file_path): with open(file_path, 'wb') as f: f.write(response.content) else: print('Already Downloaded', file_path) return file_path except requests.ConnectionError: print('Failed to Save Image')