Encryption algorithm (python implementation)

Encryption Algorithm

1. Symmetric encryption

1.0, Introduction

Symmetric encryption means that data encryption and decryption use the same key. , data encryption

  • Main function: Usually used to ensure the confidentiality of data.

  • Commonly used encryption algorithms:

    • DES: Data Encryption Standard, the key length is 56 bits, and it was cracked around 2003-the key can be cracked violently.
    • 3DES: An improved version of DES.
    • AES: Advanced Encryption Standard, supported key lengths include 128bits, 192bits, 258bits, 384bits, 512bits.

    ※: The longer the key, the longer the encryption and decryption time

1.1,DES

Features: The key is very short and can be easily cracked

Introduction:

The DES algorithm is a symmetric encryption system in the encryption system, also known as the American Data Encryption Standard.

DES is a block encryption algorithm. A typical DES uses 64 bits as a block to encrypt data. The same algorithm is used for encryption and decryption.

There are three entry parameters of the DES algorithm: Key, Data, and Mode. Among them, Key is 8 bytes with a total of 64 bits, which is the working key of the DES algorithm; Data is 8 bytes with 64 bits, which is the data to be encrypted or decrypted**

The key length is 64 bits, and the key is actually 56 bits participating in the DES operation (the 8th, 16th, 24th, 32nd, 40th, 48th, 56th, and 64th bits are check digits, so that each key has an odd number of 1s) , encrypt the 64-bit binary data block, and the grouped plaintext group and the 56-bit key are replaced or exchanged bit by bit to form a ciphertext group. Each encryption performs 16 rounds of encoding on 64-bit input data, and after a series of substitutions and shifts, it is converted into completely different 64-bit output data.

import binascii
from Cryptodome.Cipher import DES


key = b'12345678'	# 密钥(只能是8位)
iv = b'12345678'	# 初始化向量

# 创建了一个DES加密对象
cipher1 = DES.new(key, DES.MODE_CFB, iv)

# 需要加密的数据
data = '大家好,我是啊啊啊'.encode()

# 加密过程
msg = cipher1.encrypt(data)

# 创建了一个解密对象(加密解密不能使用同一把密钥)
cipher2 = DES.new(key, DES.MODE_CFB, iv)

# 解密过程
print(cipher2.decrypt(msg).decode())
复制代码

1.2,3DES

Features: Safer and stronger than DES, by increasing the key length (enhanced computer operating capabilities)

Introduction:

3DES (or Triple DES) is a general term for Triple Data Encryption Algorithm (TDEA, Triple Data Encryption Algorithm) block cipher. It is equivalent to applying the DES encryption algorithm three times to each data block.

Due to the enhancement of computing power of computers, the key length of the original DES cipher becomes easy to be cracked by brute force. 3DES is designed to provide a relatively simple method to avoid similar attacks by increasing the key length of DES, rather than designing a brand new block cipher algorithm.

3DES (Triple DES) is an encryption algorithm for the transition from DES to AES (in 1999, NIST designated 3-DES as a transitional encryption standard), the encryption algorithm, and its specific implementation is as follows: let Ek() and Dk() represent the DES algorithm The encryption and decryption process, K represents the key used by the DES algorithm, M represents the plaintext, and C represents the ciphertext, so:

The 3DES encryption process is: C=Ek3(Dk2(Ek1(M)))

The 3DES decryption process is: M=Dk1(EK2(Dk3(C)))

# 与DES不同的就是他的密钥
key = b'123456781234567812345678'	# 密钥(DES只能是8位,3DES就是24位)
复制代码

1.3,AES

Features: high resistance to brute force cracking, long key length, wide range of current Internet use

Introduction:

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. After a five-year selection process, the Advanced Encryption Standard was published by the National Institute of Standards and Technology (NIST) in FIPS PUB 197 on November 26, 2001, and became an effective standard on May 26, 2002. In 2006, Advanced Encryption Standard became one of the most popular algorithms in symmetric key encryption.

AES can quickly encrypt and decrypt on both software and hardware, is relatively easy to implement, and requires only a small amount of memory. As a new encryption standard, it is currently being deployed and applied to a wider range.

Features and Thoughts

  1. Resists all known attacks.

  2. Fast on multiple platforms, compact coding.

  3. Simple design.

AES is a block cipher, and the block cipher divides the plaintext into groups, each group has the same length, and encrypts a group of data each time until the entire plaintext is encrypted. In the AES standard specification, the packet length can only be 128 bits, that is, each packet is 16 bytes (8 bits per byte). The length of the key can be 128 bits, 192 bits or 256 bits. The length of the key is different, and the recommended number of encryption rounds is also different.

128 bits are commonly used

from Cryptodome.Cipher import AES
from Cryptodome import Random
from binascii import b2a_hex

# 要加密的明文
data = '测试数据'

# 密钥 key 长度必须是 16(AES-128)、24(AES-192)、或32(AES-256)Bytes 长度.
# 目前AES-128
key = b'this is a 16 key'

# 生成长度等于AES快大小的不可重复的密钥向量
iv = Random.new().read(AES.block_size)

# 加密函数,使用 key 和 iv 创建,使用 MODE_CFB 模式
myencrypt = AES.new(key, AES.MODE_CFB, iv)

# 加密的明文长度必须为16的倍数,如果长度不为16的倍数,则需要补足为16的倍数
# 将iv(密钥向量)加到加密的密文开头,一起传输
encrypttext = iv + myencrypt.encrypt(data.encode())

# 解密函数,要用 key 和 iv(密文前16位) 生成新的AES对象
mydecrypt = AES.new(key, AES.MODE_CFB, encrypttext[:16])

# 使用新生成的 AES 对象,讲加密的密文解密
decrypttext = mydecrypt.decrypt(encrypttext[16:])

print('密钥key为:', key)
print('iv为:', b2a_hex(encrypttext)[:16])
print('加密后的数据为:', b2a_hex(encrypttext)[16:])
print('加密后的数据为:', decrypttext.decode())
复制代码

1.4,PyCrytodemo

PyCrypto is the most famous third-party package for cryptography in Python . Sadly, its development stopped in 2012

Fortunately, there is a fork of this project, PyCrytodome, which replaces PyCrypto .

PyCrypto documentation: pycryptodome.readthedocs.io/en/latest/s…

  1. Install and Import

    • under Linux

      # 安装
      pip install pycryptodome
      
      # 导入
      import Crypto 
      复制代码
    • under Windows

      Microsoft Visual C++ 2015 needs to be installed before installation .

      # 安装有稍稍的不同(pycryptodomex是代表两个版本都下载共存)
      pip install pycryptodomex
      
      # 导入
      import Cryptodome
      复制代码

Second, asymmetric encryption

Refers to the use of different keys for encryption and decryption. Provided by the public key server, the private key is stored on the server, and the password is encrypted

2.0, Introduction

Refers to the use of different keys for encryption and decryption.

One is the public key and the other is the private key. This encrypts the public key in the key, and the private key is used for decryption. And vice versa (data encrypted by the private key can also be decrypted by the public key).

In actual use, the private key is generally kept in the hands of the publisher, which is private and not disclosed to the public. Only the public key is released to the public, and only the holder of the private key can decrypt the data. This encryption method has a high safety factor because it does not need to transmit the decryption key, so there is no risk of the key being intercepted during the transmission process, and it is almost impossible to crack the ciphertext.

However, the efficiency of the algorithm is low, so it is often used for encryption of very important data. It is often used in conjunction with symmetry, and an asymmetric encryption key is used to encrypt a symmetric encryption key.

In fact, the public key encryption algorithm is rarely used for data encryption, it is usually only used for identity authentication , because its key is too long, the encryption speed is too slow - the speed of the public key encryption algorithm is even faster than the speed of the symmetric encryption algorithm 3 orders of magnitude (1000x) slower.

main effect:

Typically used to ensure authentication.

Commonly used public key encryption algorithms are:

  • RSA: can realize digital signature and data encryption
  • DSA: only digital signature can be realized, data encryption cannot be realized

Features:

  1. Different keys are used for encryption and decryption.
  2. In fact, the keys it uses are a pair, one is called the public key and the other is called the private key. This pair of keys is not independent. The public key is extracted from the private key, so the private key is very long, including 968-bit, 1024-bit, 2048-bit, and 4096-bit.
  3. Usually the public key is public and available to everyone; the private key cannot be public and only you have it.
  4. Content encrypted with the public key can only be decrypted with the corresponding private key, and vice versa.

2.1,RSA

The RSA public key encryption algorithm was proposed in 1977 by Ronald Rivest, Adi Shamir and Leonard Adleman. RSA is composed of the initial letters of their three surnames. RSA is currently the most influential public key encryption algorithm. It can resist most of the known cryptographic attacks. The RSA algorithm is based on a very simple number theory fact: it is very easy to multiply two large prime numbers, but if you want to Since its product is extremely difficult to factor , the product can be made public as an encryption key.

First install RASthe module

pip install rsa
复制代码

Moreover, because of the characteristics of the RSA encryption algorithm, the public and private keys of RSA are in decimal, but the value of the public key is often saved in hexadecimal format, so it needs to be converted to decimal format int().

Encrypt the data with the public key in the web page

# -.- encoding = utf-8 -.-
import rsa
import binascii
# rsa 加密,公钥都是由服务器提供的

# 使用网页中获得的n和e值,将明文加密
def rsa_encrypt(rsa_n, rsa_e, message):
    # 用 n 和 e 生成公钥
    key = rsa.PublicKey(rsa_n, rsa_e)
    # 用公钥加密明文
    message = rsa.encrypt(message.encode(), key)
    # 讲密文转换成可读性高的十六进制
    message = binascii.b2a_hex(message)
    # 将加密结果转化回字符串并返回
    return message.decode()


# RSA的公钥有两个值 n 和 e,我们在网站中获得的值一般就是这两个
pubkey_n = '8d7e6949d411ce14d7d233d7160f5b2cc753930caba4d5ad24f923a505253b9c39b09a059732250e56c594d735077cfcb0c3508e9f544f101bdf7e97fe1b0d97f273468264b8b24caaa2a90cd9708a417c51cf8ba35444d37c514a0490441a773ccb121034f29748763c6c4f76eb0303559c57071fd89234d140c8bb965f9725'
pubkey_e = '10001'
# 需要将十六进制转换成十进制
rsa_n = int(pubkey_n, 16)
rsa_e = int(pubkey_e, 16)
# 要加密的明文
message = '测试数据'

if __name__ == '__main__':
    print('公钥n的值的长度:', len(pubkey_n))
    print('加密后的数据:', rsa_encrypt(rsa_n, rsa_e, message))
复制代码

Three, hash

Mainly used to verify the integrity of the data

3.0, Introduction

One-way encryption means that only plaintext data can be encrypted, but not decrypted.

For example: Everyone has different fingerprints. When you see this person, you can get his fingerprint and other information, and there is a unique correspondence. However, if you only look at one fingerprint, it is impossible to see or read the person's appearance or Identity and other information.

Commonly used algorithm implementations:

  • MD5: 128bits
  • SHA: SHA1(160bits), SHA224, SHA256, SHA384

Features:

  1. 不可逆: The original data cannot be restored based on the data fingerprint/signature code.
  2. 容易计算: It is easy to calculate the MD5 value from the original data.
  3. 抗修改性: If any modification is made to the original data, even if only one byte is modified, the resulting MD5 value will be very different.
  4. 定长输出: For data of any length, the length of the calculated MD5 value is fixed.

3.2,MD5,SHA

Since the MD5 module was removed in python3, use hashlibthe module for md5 operations in python3

# -。- encoding = utf-8 -.-
import hashlib

data = '测试数据'

text = hashlib.md5()

text.update(data.encode())

print('MD5加密前的数据:', data)
print('MD5加密后的数据:', text.hexdigest())
print('MD5加密后的长度:', len(text.hexdigest()))
复制代码
MD5加密前的数据: 测试数据
MD5加密后的数据: 145314895749100ae8306079519b3393
MD5加密后的长度: 32
复制代码

MD5 length

The length of md5 is 128bit by default, that is, 128 binary strings of 0 and 1. This expression is very unfriendly. Therefore, the binary is converted into a hexadecimal system, and every 4 bits represent a hexadecimal system, so 128/4 = 32 After being converted into a hexadecimal system, it is 32 bits.

Guess you like

Origin blog.csdn.net/weixin_73136678/article/details/128905162