python encryption way summary

Basic literacy

Symmetric encryption

Symmetric key encryption, also known as private key encryption. And recipient information that is transmitted by a key to encrypt data and the Secret. The biggest advantage is fast encryption and decryption speed for large amounts of data encryption, symmetric encryption key distribution and management shortcomings are, in other words how to send keys to decrypt your message needs the hands of the problem. In the process of sending the key, the key there is a great risk of being intercepted by hackers. In reality the practice is symmetric encryption key for asymmetric encryption then passed to need him.

Asymmetric encryption

Asymmetric encryption systems, also known as public key encryption. Asymmetric encryption provides a very safe way for data encryption and decryption. She uses a pair of keys, a public key and a private key. There can be only one party custody of private security, it can not be compromised, and the public key can be distributed to anyone who asked for her. This asymmetric encryption using a key to encrypt, decrypt it takes a while another key. For example, you go to the bank that you request a public key to the bank, the bank will send you a public key, you use the public key to encrypt a message, only the private key holders - banks can decrypt your messages. And differs from symmetric encryption, the bank need not be sent over the private network. Therefore, security is greatly improved. The most commonly used asymmetric encryption algorithm is the RSA algorithm. A public key and a flexible, but encryption and decryption speeds much slower than symmetric key encryption. A public key and a flexible, but encryption and decryption speed is much slower than a pile of encryption.

1) Alice needs to do a deal at the bank's website, her browser first generates a random number as the symmetric key.
(2) Alice's browser requests a public key to the bank's website.
(3) the bank will send the public key to Alice.
(4) Alice's browser using the bank's own public key symmetric key encryption.
(5) Alice's browser will send the encrypted symmetric key to the bank.
(6) Bank obtained using the private key to decrypt the symmetric key Alice browser.
(7) Alice and the bank can use a symmetric key to encrypt and decrypt the content of the communication.

Summary
(1) symmetric encryption using encryption and decryption keys are the same, so fast, but because of the need to key network transmission, so security is not high.
(2) asymmetric cryptography uses a pair of keys, public and private keys, so that safe, but slow encryption and decryption.
(3) The solution is a symmetric encryption key using an asymmetric encryption public key to encrypt, and then sent, the recipient uses a private key to decrypt the symmetric encryption keys obtained, then the two sides can communicate using symmetric encryption .

python encrypted Precautions

We are talking about encryption, it is binary coded format is encrypted, which corresponds to Python, it is our Bytes.

So when we perform cryptographic operations in Python, to ensure that our operations are Bytes, otherwise it will error.

Bytes string and mutual conversion can encode () and decode () method.

Base64

Base64 is a character represented by 64 arbitrary binary data.

Base64 encoding can be called the cornerstone of cryptography. Can be arbitrary binary data will be Base64 encoded. All data can be encoded as a text file and only 65 characters can be represented. (65 characters: A ~ Z a ~ z 0 ~ 9 + / =) = ~ coded data encoded data before 4/3, about 1/3 will be larger.

principle

1.将所有字符转化为ASCII码。
2.将ASCII码转化为8位二进制 。
3.将二进制3个归成一组(不足3个在后边补0)24位,再拆分成4组,每组6位。
4.统一在6位二进制前补两个0凑足8位。
5.将补0后的二进制转为十进制。
6.从Base64编码表获取十进制对应的Base64编码。

Explanation

  1. Conversion when the three byte of data into the buffer has a 24bit, the first to occupy the high byte.
  2. Insufficient data 3byte words, in the buffer remaining bit with zeros. Then, in each case taking 6 'bit, in accordance with the selected look-up table to select the value corresponding to the character as the encoded output.
  3. Continues until all of the input data conversion is complete.
  4. If the last remaining two data inputs, the result of adding an encoded "=."
  5. If the last remaining one input data, the encoded result plus 2 "=."
  6. If you do not rest any data, we do not add anything, so we can ensure the correctness of data reduction.

Base64 encryption and decryption

Note:
1. A base64 encoding either contain ASCII characters or binary data
2.base64 symmetric encryption

'''
遇到问题没人解答?小编创建了一个Python学习交流QQ群:579817333 
寻找有志同道合的小伙伴,互帮互助,群里还有不错的视频学习教程和PDF电子书!
'''
import base64

s = 'hello, world'
s = "你好"
# 加密
bs = base64.b64encode(s.encode("utf8"))
print(bs)

# 解密
decode = base64.b64decode(bs)
print(decode)
print(decode.decode("utf8"))

MD5

message-digest algorithm 5 (Information - digest algorithm). Often say "MD5 encryption", is the message digest algorithm.

md5, in fact, an algorithm. You may be a string, or a file, or compressed, after performing MD5, can generate a fixed length of string 128bit. This string is substantially unique.

Explanation

  • Compressibility: arbitrary data length, the calculated length of the MD5 value is fixed.
  • Easily calculated: MD5 value is calculated from the original data easily.
  • Anti Modifiability: any changes to the original data, even if only a byte modifications, MD5 values ​​obtained are very different.
  • Strong anti-collision: the known original data and its MD5 value, want to find data (ie, falsified data) is very difficult with the same MD5 values.
  • Irreversibility: Everyone has different fingerprints, see this person, you can obtain his fingerprints and other information, and the only correspondence, but you look a fingerprint, it is impossible to see or read the person's appearance or identity and other information.

MD5 encryption and decryption

As the MD5 python3 module is removed, a module python3 hashlib operation performed md5

'''
遇到问题没人解答?小编创建了一个Python学习交流QQ群:579817333 
寻找有志同道合的小伙伴,互帮互助,群里还有不错的视频学习教程和PDF电子书!
'''
import hashlib

# 待加密信息
str = '这是一个测试'

# 创建md5对象
hl = hashlib.md5()

# 此处必须声明encode
# 若写法为hl.update(str)  报错为: Unicode-objects must be encoded before hashing
hl.update(str.encode(encoding='utf-8'))

print('MD5加密前为 :' + str)
print('MD5加密后为 :' + hl.hexdigest())

Output

MD5加密前为 :这是一个测试
MD5加密后为 :cfca700b9e09cf664f3ae80733274d9f

Md5 length, the default is 128bit, 128 is a binary string of 0 and 1. Such expression is very friendly. It turned into a binary hexadecimal, each represents a 4 bit hexadecimal, so 128/4 = 32 into the hexadecimal notation, the 32 bits.

Why Online there are 16 md5 it?

In fact, the 16-bit length, from the 32-bit value md5. 32 is a front eight md5 removed, after removing the eight obtained.

OF

Introduction PyCrypto

PyCrypto in Python cryptography is the most famous third-party packages, offers many use encryption algorithms. Unfortunately, its development work in 2012 had stopped.

Fortunately, there is a branch PyCrytodome of the project to replace the PyCrypto.

Installation and Import

You need to install Microsoft Visual c ++ 2015 before installation.

On Linux installation, you can use the following pip command:

pip install pycryptodome

Import:

import Crypto

On a Windows system installation is slightly different:

pip install pycryptodomex

Import:

import Cryptodome

DES Introduction

DES algorithm is a symmetric cryptosystem cryptosystem, and is also known as US Data Encryption Standard.
DES is a block encryption algorithm, a typical 64-bit DES to encrypt the data packet, the encryption and decryption using the same algorithm.
Inlet DES algorithm has three parameters: Key, Data, Mode. Key 7 wherein a total of 56 bytes, the work key is a DES algorithm; Data 8 bytes 64, is to be encrypted or decrypted data; Mode works as DES, there are two: Encryption or decryption.
64-bit key length, the key 56 is in fact involved in the DES operation (8,16,24,32,40,48,56,64 first bit is a parity bit, such that each key is an odd number) , and 56-bit plaintext key group grouped by the method of forming groups ciphertext bits or alternatively exchanged.

Encryption Principle

DES uses a 56-bit key and an additional eight parity bits, to generate 64-bit maximum packet size. This is an iterative block cipher, using the technique called Feistel, wherein the encrypted text block in half. Using the sub-key half cyclic function, and then outputs the other half "exclusive or" operation; then exchanged two halves, this process will continue, but not the last exchange cycle. DES uses 16 cycles, using an exclusive or, replacement, substitution, four basic arithmetic shift operation.

Algorithm steps

1) initial permutation

Its function is the 64-bit input data block re bitwise combination, and the output is divided into L0, R0 two parts, each part of each length 32 bits, which permutation rule for the first 58 to the first input transducer, the first 50 to change the first two ...... and so on, the last one is the original 7th. L0, R0 is the output of the two parts after the transposition, the L0 is 32-bit output from the left, the right 32-bit R0 are, for example: an input transducer is provided before D1D2D3 ...... D64, after a result of the initial permutation is: L0 = D58D50 ...... D8; R0 = D57D49 ...... D7.
Its replacement rule as follows:
58,50,42,34,26,18,10,2,60,52,44,36,28,20,12,4,
62,54,46,38,30,22 , 14,6,64,56,48,40,32,24,16,8,
57,49,41,33,25,17,9,1,59,51,43,35,27,19,11 3,
61,53,45,37,29,21,13,5,63,55,47,39,31,23,15,7,

2) the inverse permutation

After 16 times iteration, to give L16, R16, this as an input, an inverse permutation, inverse permutation is just the inverse of the initial permutation, thus to obtain the ciphertext output.
This algorithm is a symmetric encryption algorithm is the representative system is widely used in a computer network system.

DES encryption and decryption

'''
遇到问题没人解答?小编创建了一个Python学习交流QQ群:579817333 
寻找有志同道合的小伙伴,互帮互助,群里还有不错的视频学习教程和PDF电子书!
'''
# 导入DES模块
from Cryptodome.Cipher import DES
import binascii

# 这是密钥
key = b'abcdefgh'
# 需要去生成一个DES对象
des = DES.new(key, DES.MODE_ECB)
# 需要加密的数据
text = 'python spider!'
text = text + (8 - (len(text) % 8)) * '='

# 加密的过程
encrypto_text = des.encrypt(text.encode())
encrypto_text = binascii.b2a_hex(encrypto_text)
print(encrypto_text)

3DES

3DES (or referred to as Triple DES) is a generic term Triple Data Encryption Algorithm (TDEA, Triple Data Encryption Algorithm) block cipher. It corresponds to the triple DES encryption algorithm is applied to each data block.

Due to enhanced computing power, the original DES password key length becomes vulnerable to brute force. 3DES that is designed to provide a relatively simple method, i.e., to prevent similar attacks by increasing the DES key length, rather than designing a new block cipher algorithm.

3DES (ie, Triple DES) encryption algorithm DES transition to AES (In 1999, NIST will 3DES encryption standard as specified transition), the encryption algorithm, the specific implementation as follows: Let Ek () and Dk () on behalf of the DES algorithm the encryption and decryption processes, K DES algorithm using the key representatives, M for plaintext, C for the ciphertext, so that:

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

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

AES

Advanced Encryption Standard (English: Advanced Encryption Standard, abbreviation: AES), also known as Rijndael cipher In cryptography, a block encryption standard adopted by the US federal government. This standard is used to replace the original DES, it has been widely analyzed and multi- used around the world. After a five-year selection process, the Advanced Encryption Standard on November 26, 2001 issued by the US National Institute of Standards and Technology (NIST) in the FIPS PUB 197, and became effective standards in 2002, May 26. In 2006, the Advanced Encryption Standard has become one of the most popular symmetric key encryption algorithm.

AES encryption and decryption can be in the software and hardware quickly, relatively speaking, easier to implement, and requires very little memory. As a new encryption standard, currently being deployed to a wider range of applications.

Feature

  1. Resistant to all known attacks.
  2. Speed ​​on multiple platforms, compact coding.
  3. Simple designs.

AES encryption and decoding

AES is a block cipher, the block cipher is a set of plaintext into a group, each equal length, each time a set of the encrypted data until a complete encryption of plaintext. In the AES standard specification, only the packet length is 128 bits, i.e., each packet is 16 bytes (8 bits per byte). The length of the key can use 128-bits, 192 bits or 256 bits. The different length of the key, the encrypted recommend different rounds.

128 is commonly used

'''
遇到问题没人解答?小编创建了一个Python学习交流QQ群:579817333 
寻找有志同道合的小伙伴,互帮互助,群里还有不错的视频学习教程和PDF电子书!
'''
from Cryptodome.Cipher import AES
from Cryptodome import Random

from binascii import a2b_hex

# 要加密的明文
data = '南来北往'
# 密钥key必须为 16(AES-128), 24(AES-192), 32(AES-256)
key = b'this is a 16 key'
# 生成长度等于AES 块大小的不可重复的密钥向量
iv = Random.new().read(AES.block_size)
print(iv)
# 使用 key 和iv 初始化AES 对象, 使用MODE_CFB模式
mycipher = AES.new(key, AES.MODE_CFB, iv)
print(mycipher)
# 加密的明文长度必须为16的倍数, 如果长度不为16的倍数, 则需要补足为16的倍数
# 将iv(密钥向量)加到加密的密钥开头, 一起传输
ciptext = iv + mycipher.encrypt(data.encode())
# 解密的话需要用key 和iv 生成的AES对象
print(ciptext)
mydecrypt = AES.new(key, AES.MODE_CFB, ciptext[:16])
# 使用新生成的AES 对象, 将加密的密钥解密
decrytext = mydecrypt.decrypt(ciptext[16:])

print(decrytext.decode())

RSA

RSA encryption algorithm is an asymmetric encryption algorithm. In public-key encryption and electronic commerce RSA is widely used.

The algorithm is based on a very simple arithmetical fact: multiplying two large prime numbers is very easy, but then want to factorization of their product is extremely difficult, so it can be used as a product of public encryption key that is public, arrays while two large prime synthesis private key. The public key is available for the release of any person to use, the private key was all his, for decryption purposes.

Asymmetric encryption

Typical such as RSA and the like, a common method using openssl, keytools other tools to generate a pair of public and private key, data encrypted using the public key can be decrypted using the private key, and vice versa (the private key data may be known decryption key).

In actual use, the private key is generally kept in the hands of the publisher, is private not open to the public, only the public key announced, the method can be achieved only holder of the private key to decrypt the data. This encryption safety factor is very high, because the key to decrypt it will not be passed, so there is no risk of the key in the transfer process was intercepted, and the crack ciphertext is almost impossible.

However, the low efficiency of the algorithm, it is commonly used in the encryption of data is important, and often with the use of symmetric, asymmetric encryption key to encrypt the symmetric encryption key.

RSA encryption and decryption

First we need to install a module rsa:

pip install rsa

Further, because the characteristics of the RSA encryption algorithm, the RSA public and private key are decimal, but often public key value stored in hexadecimal format, so it is necessary to use int (), is converted to decimal 10 format.

'''
遇到问题没人解答?小编创建了一个Python学习交流QQ群:579817333 
寻找有志同道合的小伙伴,互帮互助,群里还有不错的视频学习教程和PDF电子书!
'''
import rsa
import binascii

# 使用网页中获得的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,我们在网站中获得的公钥一般就是这样的两个值。
# n常常为长度为256的十六进制字符串
# e常常为十六进制‘10001’
pubkey_n = '8d7e6949d411ce14d7d233d7160f5b2cc753930caba4d5ad24f923a505253b9c39b09a059732250e56c594d735077cfcb0c3508e9f544f101bdf7e97fe1b0d97f273468264b8b24caaa2a90cd9708a417c51cf8ba35444d37c514a0490441a773ccb121034f29748763c6c4f76eb0303559c57071fd89234d140c8bb965f9725'
pubkey_e = '10001'
# 需要将十六进制转换成十进制
rsa_n = int(pubkey_n, 16)
rsa_e = int(pubkey_e, 16)
# 要加密的明文
message = '南北今天很忙'

print("公钥n值长度:", len(pubkey_n))
print(rsa_encrypt(rsa_n, rsa_e, message))

operation result:

公钥n值长度: 256
480f302eed822c8250256511ddeb017fcb28949cc05739ae66440eecc4ab76e7a7b2f1df398aefdfef2b9bfce6d6152bf6cc1552a0ed8bebee9e094a7ce9a52622487a6412632144787aa81f6ec9b96be95890c4c28a31b3e8d9ea430080d79297c5d75cd11df04df6e71b237511164399d72ccb2f4c34022b1ea7b76189a56e
Published 706 original articles · won praise 737 · Views 1.02 million +

Guess you like

Origin blog.csdn.net/sinat_38682860/article/details/104030117
Recommended