Python-based data encryption (collecting this one is enough!)

Data encryption based on Python

Remarks: The code examples in this article can be directly copied and used, as long as the corresponding parameters are passed in~~ Convenient and practical!

1. Preparation

Important: First, make sure that the content we want to encrypt is in Bytes format!

The encryption methods we are talking about encrypt the binary encoding format. Therefore, before encrypting, we must first ensure that the content we want to encrypt is in Bytes format, otherwise an error will be reported. So how do we get the Bytes format? The secret is to use encode() and decode() methods; the code is as follows:

str = 'I LOVE China! 我爱你中国!'
str_en = str.encode('utf-8')  # 将内容变为 Bytes格式 ! 这样才可以加密!
print(str_en)    # b'I LOVE China! \xe6\x88\x91\xe7\x88\xb1\xe4\xbd\xa0\xe4\xb8\xad\xe5\x9b\xbd\xef\xbc\x81'

str_de = str_en.decode('utf-8')  # 解密后,将内容变回字符串内容,这样才可读;
print(str_de)    # I LOVE China! 我爱你中国!

Encryption and decryption steps:

  1. Encrypted content.encode('utf-8'), change the encrypted content into Bytes format;
  2. Encrypt
  3. Decrypt
  4. The decrypted content.decode('utf-8'), the decrypted content becomes readable;

2. MD5 encryption

MD5 Message-Digest Algorithm (English: MD5 Message-Digest Algorithm), a widely used cryptographic hash function, can generate a 128-bit (16-byte) hash value to ensure information transmission Complete and consistent.

2.1 Encryption rules

The principle of the MD5 algorithm can be briefly described as follows: MD5 code uses 512-bit groups to process the input information, and each group is divided into 16 32-bit sub-groups. After a series of processing, the output of the algorithm consists of four It is composed of 32-bit packets. The four 32-bit packets are cascaded to generate a 128-bit hash value.

2.2 Application scenarios

  • Password management: The passwords stored in the general database are all encrypted by MD5. There is no decryption method for this kind of encryption. It can only perform forward operation (encryption), not reverse operation (decryption). So when we ask the administrator to check what our password is, the administrator will tell us: I can only reset your password for this reason; although MD5 has loopholes, it is still relatively safe;

  • Electronic signature: When we download various files, in addition to the download address of the software, a long string of characters will be given on the download page. This string of strings is actually the MD5 value of the software. Its function is to use special software (such as Windows MD5 check, etc.) to perform an MD5 check on the downloaded file after downloading the software to ensure the file we obtained It is the same file as the one provided by this site.

2.3 Code example

  1. General MD5 encryption
# 1. md5加密
import hashlib
str = 'I LOVE China! 我爱你中国!'
str_en = str.encode('utf-8')

h = hashlib.md5(str_en)
h_en = h.hexdigest()
print(h_en)   # 1c07f68a93ec867b4b315b90f2098b24
  1. MD5 encryption with parameters
    Although MD5 encryption is relatively safe, it can still be cracked by the library. To increase security, we can pass in another parameter, which is equivalent to performing another encryption to improve security. The method is as follows:
# 增加自己的参数'admin',可以防止撞库破解密码;
str = 'I LOVE China! 我爱你中国!'
str_en = str.encode('utf-8')

h = hashlib.md5(str_en)
h.update('admin'.encode('utf-8'))
h_en = h.hexdigest()
print(h_en)
  1. encrypt documents
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# author:Zhang Kai time:2020/10/22
import hashlib
 
def get_file_md5(f):
    str = hashlib.md5()
    while True:
        data = f.read(10240)
        if not data:
            break
        str.update(data)
    return str.hexdigest()

with open(File_Name, 'rb') as f:
    file_md5 = get_file_md5(f)     # 得到文件对应的加密值,下载结束后,对比此值,即可以判断是否为同一文件;

2.4 sha1 encryption

SHA-1 (English: Secure Hash Algorithm 1, Chinese name: Secure Hash Algorithm 1) is a cryptographic hash function, designed by the National Security Agency, based on MD5, but more secure than MD5, and its use is exactly the same as MD5. as follows:

import hashlib
str = 'I LOVE China! 我爱你中国!'
str_en = str.encode('utf-8')

h = hashlib.sha1(str_en)
h.update('admin'.encode('utf-8'))
h_en = h.hexdigest()
print(h_en)  # ab4d75034500b6f6a8a152df7a1f67349ead6606,比MD5多8位;

3. Base64 encryption

Base64 is one of the most common encoding methods used to transmit 8Bit bytecode on the network. Base64 is a method of representing binary data based on 64 printable characters. Base64 encoding is a process from binary to character, which can be used to transfer longer identification information in the HTTP environment. The Base64 encoding is unreadable and needs to be decoded before reading. Because of the above advantages, Base64 is widely used in various fields of computer.

3.1 Encryption rules

  1. Turn 3 bytes into 4 bytes.
  2. Add a newline character every 76 characters.
  3. The final terminator is also processed.

3.2 Application scenarios

  • The dedicated address link downloaded by Thunder uses Base64'encrypted';
  • QQ Cyclone also uses Base64'encryption';

Note: The encryption here is all quoted, because it is not so much encryption, as it is to encode data according to the rules, and encode the originally meaningful content into content that must be decoded to read;

3.3 Code example

#!/usr/bin/env python
# -*- coding: utf-8 -*-
# author:Zhang Kai time:2020/10/22
# 2. BASE64
import base64
str = 'I LOVE China! 我爱你中国!'
str_en = str.encode('utf-8')

b64_en= base64.b64encode(str_en)
print(b64_en)   # b'SSBMT1ZFIENoaW5hISDmiJHniLHkvaDkuK3lm73vvIE='

b64_de = base64.b64decode(b64_en)
print(b64_de)    # b'I LOVE China! \xe6\x88\x91\xe7\x88\xb1\xe4\xbd\xa0\xe4\xb8\xad\xe5\x9b\xbd\xef\xbc\x81'
str_de = b64_de.decode('utf-8')
print(str_de)    # I LOVE China! 我爱你中国!

4. AES

Advanced Encryption Standard (English: Advanced Encryption Standard, abbreviation: AES), also known as Rijndael encryption in cryptography, is a block encryption standard adopted by the US federal government. This standard is used to replace the original DES, has been analyzed by many parties and is widely used all over the world. In 2006, the Advanced Encryption Standard has become one of the most popular algorithms in symmetric key encryption.

4.1 Encryption rules

The AES encrypted data block and key length can be any of 128b, 192b, and 256b. AES encryption has many rounds of repetition and transformation. The general steps are as follows: ①Key Expansion; ②InitialRound; ③Rounds, each repeated round includes subbytes (SubBytes), row shift (ShiftRows), column Operations such as mixing (MixColurmns), round key addition (AddRoundKey); ①Final round (Final Round), there is no column mixing operation (MixColumns) in the final round.

4.2 Application scenarios

The AES algorithm is used to transmit packets that are not suitable for plaintext transmission.

4.3 Code example

#!/usr/bin/env python
# -*- coding: utf-8 -*-
# author:Zhang Kai time:2020/10/22

import base64
from Crypto.Cipher import AES

'''
采用AES对称加密算法
'''
# str不是16的倍数那就补足为16的倍数
def add_to_16(message):
    while len(message) % 16 != 0:
        message = str(message)
        message += '\0'
        # message = str(message)
    return message  # 返回bytes


# 加密方法
def encrypt_oracle(message,key_pri):
    '''
    加密函数,传入明文 & 秘钥,返回密文;
    :param message: 明文
    :param key_pri: 秘钥
    :return:encrypted  密文
    '''
    # 初始化加密器
    aes = AES.new(add_to_16(key_pri), AES.MODE_ECB)
    # 将明文转为 bytes
    message_bytes = message.encode('utf-8')
    # 长度调整
    message_16 = add_to_16(message_bytes)
    #先进行aes加密
    encrypt_aes = aes.encrypt(message_16)
    #用base64转成字符串形式
    encrypt_aes_64 = base64.b64encode(encrypt_aes)
    return encrypt_aes_64


# 解密方法
def decrypt_oralce(message,key_pri):
    '''
    解密函数,传入密文 & 秘钥,返回明文;
    :param message: 密文
    :param key_pri: 秘钥
    :return: encrypted 明文
    '''
    # 初始化加密器
    aes = AES.new(add_to_16(key_pri), AES.MODE_ECB)
    #优先逆向解密base64成bytes
    message_de64 = base64.b64decode(message)
    # 解密 aes
    message_de64_deaes = aes.decrypt(message_de64)
    message_de64_deaes_de = message_de64_deaes.decode('utf-8')
    return message_de64_deaes_de


message = 'Tommorrow is another day!over!'     # 待加密内容
key_pri = '123456'                              # 密码

content_en = encrypt_oracle(message,key_pri)    # 加密
print('加密后,密文为:',content_en)            # 加密后,密文为: b'LbzC28Y/ZIgvQ1SszLrlciocu1D8HNDTcLUaUXvCgvo='

content = decrypt_oralce(content_en,key_pri)    # 解密
print('解密后,明文为:',content)               # 解密后,明文为: Tommorrow is another day!over!

5.RSA

RSA was proposed in 1977 by Ron Rivest, Adi Shamir, and Leonard Adleman. At that time, all three of them were working at the Massachusetts Institute of Technology. RSA is made up of the first letters of their last names.

The RSA public key cryptosystem is a cryptosystem that uses different encryption keys and decryption keys. It is computationally infeasible to derive the decryption key from a known encryption key. RSA allows you to choose the size of the public key. A 512-bit key is considered insecure; a 768-bit key does not have to worry about being compromised by anything other than the National Security Administration (NSA); a 1024-bit key is almost safe.

5.1 Encryption principle

The principle of the RSA public key cryptosystem is: According to number theory, it is relatively simple to find two large prime numbers, but it is extremely difficult to factorize their product, so the product can be publicly used as an encryption key.

5.2 Code example

# RSA
import rsa

def rsaEncrypt(message):
    '''
    RSA加密函数
    传入需要加密的内容,进行RSA加密,并返回密文 & 私钥 & 公钥
    :param message: 需要加密的内容,明文
    :return: 密文 & 私钥 & 公钥
    '''
    key_pub,key_pri = rsa.newkeys(1024)
    # print(key_pri)
    # print(key_pub)
    content = message.encode('utf-8')
    crypto = rsa.encrypt(content,key_pub)
    return (crypto,key_pri,key_pub)


def rsaDecrypt(message,key_pri):
    '''
    RSA 解密函数,传入密文 & 私钥,得到明文;
    :param message: 密文
    :param key_pri: 私钥
    :return: 明文
    '''
    content = rsa.decrypt(message,key_pri)
    return content.decode('utf-8')

# 公钥加密,私钥解密

message='I Love China. 我爱你中国!'

print('加密前:',message)  # 加密前: I Love China. 我爱你中国!

crypto,key_pri,key_pub = rsaEncrypt(message)

print('加密后:',crypto)    # 加密后: b';\x1fT\x0b\xa2\xc2t\x18\xf2z\x85p\t>\xdc@%\xd4\xf3>i1\xae\xe9=\x993>\xed!\xc9?F\xcb\xde\xe1\xa5\xf0\xe9\xde\xc3\x16\xf4W\x19;\x83B\x1c\xa7\xc8k\xc9EB\xdd\x94\xad7\xda\x7f{\xec\x9f\x99\xbfd\x87\xf0d\xbc\xfe\xef_\xd9;\x18s{l\xcb\xd5u\xb7/\xf4FX\xda\xd4\xa1\xe6\xce|\xe0[<\xe4\xe2j\xb9N\xc4\x93\x17\xe7J\xeey\xbd\x1a\xd8.\x0b)\xcb\x98\xc4\x96\xb9b\t\xdc\x18]2\xdfy'
print('秘钥为:',key_pri)   # 秘钥为: PrivateKey(115288028345818733754881460912555806638911383959807908842585241310442843853213667112358247839422013848032677508051802527090846065467533765017680180661692630683981532520607475409309404078951405099846021972426884336220213989970308538119345752815652299922371343220268410359092002773721528507791837782603361434249, 65537, 72671372491785063554143583498765474892962268379138876088256082881055042532006497124961953957220544334895981514795123582047544773342223284047871955302686464986848482351432416996957016628407054177594256525025069157980131024957403886435812321512561610952210861350247053560059407031244790602637847816964556926465, 38939822841624334244626968212850549717962185656658548767156085704609096413636024697954233697763690441579951219223510491427663677756196233739375481382535403537584193, 2960671619249966096061431500671042485145295502851556909042124706260452571275538786999969819708964185223862037824834932783401994640273454183045193)
print('公钥为:',key_pub)   # 公钥为: PublicKey(115288028345818733754881460912555806638911383959807908842585241310442843853213667112358247839422013848032677508051802527090846065467533765017680180661692630683981532520607475409309404078951405099846021972426884336220213989970308538119345752815652299922371343220268410359092002773721528507791837782603361434249, 65537)

content = rsaDecrypt(crypto,key_pri)
print('明文为:',content)   # 明文为: I Love China. 我爱你中国!

Guess you like

Origin blog.csdn.net/weixin_47139649/article/details/109221698