python reptile basis of common encryption algorithms 05-

Python and common encryption

Foreword

Data encryption and decryption usually in order to ensure the security of data during transmission, and have existed since ancient times, the ancient main application in the field of war, the war will be a lot of intelligence information to be passed, these important information will be encrypted, sent corresponding to the human hand.

Modern, in the early stages of network development, data network security is not enough attention. In fact, at that time in order to achieve data can be transmitted through the network of scientists has spent the majority of brain cells, so early in the TCP / IP protocol design, they really do not have much energy to give much thought to the data may exist in the network transmission process security issues. With the maturing of TCP / IP protocols and related technologies, network data transmission technology more and more stable, people are slowly starting to focus on this issue.

1. What is encryption and decryption?

"Encryption" process, that is, the "plaintext" into "cipher text" process; the other hand, "decryption" process, is to "ciphertext" to "plaintext." In both processes, we need a critical thing - called the "key" - to participate in math.

Parameter encryption and decryption functions are required to be byte object in python that is our Bytestarget

Python 3.x in str is a string, use python3 to encrypt and decrypt operation, when the operation to ensure that the data we areBytes

Strings and Bytesanother converter may be used encode()and decode()methods.

 

Note: The two-digit hexadecimal often used to show a binary byte.

Using binasciimodule hexadecimal byte display may be converted into the encryption our more common display:

In [1]: import binascii

In [2]: '测试'.encode()
Out[2]: b'\xe6\xb5\x8b\xe8\xaf\x95'

In [3]: binascii.b2a_hex('测试'.encode())
Out[3]: b'e6b58be8af95'

In [4]: binascii.a2b_hex(b'e6b58be8af95')
Out[4]: b'\xe6\xb5\x8b\xe8\xaf\x95'

In [5]: binascii.a2b_hex(b'e6b58be8af95').decode()
Out[5]: '测试'

 

Use of computer storage units

Bit (bit) the smallest unit of a computer, for storing binary

Byte (Byte) The most common basic unit of a computer, an eight-byte (1Byte = 8 bit)

  • KB (K bytes) 1K = 1024 Byte

  • MB (megabytes) 1M = 1024K

  • GB (gigabyte) 1G = 1204M

  • TB (terabyte) 1T = 1024G

 

Network information security involves many aspects, of which there are three issues to be addressed:

  • Privacy (Confidentiality) : information is not leaked in the transmission

  • Integrity (the Integrity) : information is not tampered with during transmission

  • Effectiveness (Availability) : user information is legitimate

For the above questions, you can use the following data encryption methods to solve (each data encryption there are a variety of different algorithms):

Data encryption description The main problem Commonly used algorithms
Symmetric encryption It refers to data encryption and decryption using the same key Confidentiality of data DES, AES
Asymmetric encryption Also called public key encryption, refer to different data encryption and decryption using the key - the key for children Authentication DSA, RSA
One-way encryption Refers to only encrypt data, not decrypt the data Data integrity MD5, SHA family of algorithms

One-way encryption

1 Introduction

Only one-way encryption means encrypts the plain data, and decrypt data.

For chestnut: Everyone has different fingerprints, see this person, you can draw his fingerprints and other information, and the only correspondence, but you look a fingerprint, it is impossible to see or read this person's looks or identity and other information.

The main function:

It is typically used to ensure data integrity.

Commonly used algorithm:

  • MD5: 128bits

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

Features:

  • Irreversible: Unable to restore the original data from the data fingerprint / signature.

  • 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.

  • 定长输出:任意长度的数据,算出的MD5值长度都是固定的。

2. Python的MD5, SHA系列使用

由于MD5模块在python3中被移除,在python3中使用hashlib模块进行md5操作

import hashlib

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

# 创建md5对象, sha系列把md5换成sha系列的名字就可以了
hl = hashlib.md5()

hl.update(str.encode())

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

运行结果

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

MD5长度

md5的长度,默认为128bit,也就是128个0和1的二进制串。这样表达是很不友好的。所以将二进制转成了16进制,每4个bit表示一个16进制,所以128/4 = 32 换成16进制表示后,为32位了。


2. 对称加密

1.简介

对称加密是指数据加密与解密使用相同的密钥。

主要功能:

通常用于保证数据的机密性。

常用的算法实现:

  • DES: Data Encryption Standard,秘钥长度为56位,2003年左右被破解--秘钥可以暴力破解。

  • 3DES: DES的改进版本。

  • AES: Advanced Encryption Standard,支持的秘钥长度包括 128bits,192bits,258bits,384bits,512bits。

需要说明的是,秘钥长度越长,数据加密与解密的时间就越久。

特点:

  • 加密与解密使用的密钥相同。

  • 但是由于算法一般都是公开的,因此机密性几乎完全依赖于密钥。

  • 通常使用的是相对较小的密钥,一般小于256bit。因为密钥越大,加密越强,但加密与解密的过程越慢。


2. python中的使用

PyCrypto是 Python 中密码学方面最有名的第三方软件包。可惜的是,它的开发工作于2012年就已停止。

幸运的是,有一个该项目的分支PyCrytodome 取代了 PyCrypto 。

PyCrypto文档: https://pycryptodome.readthedocs.io/en/latest/src/introduction.html

安装与导入

Windows安装之前需要先安装Microsoft Visual c++ 2015

在Linux上安装,可以使用以下 pip 命令:

pip install pycryptodome

导入:

import Crypto

在Windows 系统上安装则稍有不同:

pip install pycryptodomex

导入:

import Cryptodome

DES

简介

DES算法为密码体制中的对称密码体制,又被称为美国数据加密标准。

DES是一个分组加密算法,典型的DES以64位为分组对数据加密,加密和解密用的是同一个算法。

DES算法的入口参数有三个:Key、Data、Mode。其中Key为8个字节共64位,是DES算法的工作密钥;Data为8个字节64位,是要被加密或被解密的数据;Mode为DES的工作方式,有两种:加密或解密。

密钥长64位,密钥事实上是56位参与DES运算(第8、16、24、32、40、48、56、64位是校验位,使得每个密钥都有奇数个1),对64位二进制数据块进行加密,分组后的明文组和56位的密钥按位替代或交换的方法形成密文组。每次加密对64位的输入数据进行16轮编码,经过一系列替换和移位后转换成完全不同的64位输出数据。

例子

# 导入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())
print(encrypto_text)
print(binascii.b2a_hex(encrypto_text))

#解密的过程
decrypt_text = des.decrypt(encrypto_text)
print(decrypt_text)

3DES

简介

3DES(或称为Triple DES)是三重数据加密算法(TDEA,Triple Data Encryption Algorithm)块密码的通称。它相当于是对每个数据块应用三次DES加密算法。

由于计算机运算能力的增强,原版DES密码的密钥长度变得容易被暴力破解。3DES即是设计用来提供一种相对简单的方法,即通过增加DES的密钥长度来避免类似的攻击,而不是设计一种全新的块密码算法。

3DES(即Triple DES)是DES向AES过渡的加密算法(1999年,NIST将3-DES指定为过渡的加密标准),加密算法,其具体实现如下:设Ek()和Dk()代表DES算法的加密和解密过程,K代表DES算法使用的密钥,M代表明文,C代表密文,这样:

3DES加密过程为:C=Ek3(Dk2(Ek1(M)))

3DES解密过程为:M=Dk1(EK2(Dk3(C)))


AES

简介

高级加密标准(英语:Advanced Encryption Standard,缩写:AES),在密码学中又称Rijndael加密法,是美国联邦政府采用的一种区块加密标准。这个标准用来替代原先的DES,已经被多方分析且广为全世界所使用。经过五年的甄选流程,高级加密标准由美国国家标准与技术研究院(NIST)于2001年11月26日发布于FIPS PUB 197,并在2002年5月26日成为有效的标准。2006年,高级加密标准已然成为对称密钥加密中最流行的算法之一。

AES在软件及硬件上都能快速地加解密,相对来说较易于实作,且只需要很少的存储器。作为一个新的加密标准,目前正被部署应用到更广大的范围。

特点与思想

  1. 抵抗所有已知的攻击。

  2. 在多个平台上速度快,编码紧凑。

  3. 设计简单。

详解

AES为分组密码,分组密码也就是把明文分成一组一组的,每组长度相等,每次加密一组数据,直到加密完整个明文。在AES标准规范中,分组长度只能是128位,也就是说,每个分组为16个字节(每个字节8位)。密钥的长度可以使用128位、192位或256位。密钥的长度不同,推荐加密轮数也不同。

一般常用的是128位

例子

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初始化AES对象, 使用MODE_CFB模式
mycipher = AES.new(key, AES.MODE_CFB, iv)
# 加密的明文长度必须为16的倍数,如果长度不为16的倍数,则需要补足为16的倍数
# 将iv(密钥向量)加到加密的密文开头,一起传输
ciphertext = iv + mycipher.encrypt(data.encode())

# 解密的话要用key和iv生成新的AES对象
mydecrypt = AES.new(key, AES.MODE_CFB, ciphertext[:16])
# 使用新生成的AES对象,将加密的密文解密
decrypttext = mydecrypt.decrypt(ciphertext[16:])


print('密钥k为:', key)
print('iv为:', b2a_hex(ciphertext)[:16])
print('加密后数据为:', b2a_hex(ciphertext)[16:])
print('解密后数据为:', decrypttext.decode())

运行结果:

密钥k为: b'this is a 16 key'
iv为: b'3020aad2165cc917'
加密后数据为: b'25bd855fc0caca2a5f9f34dff175a36ade881337'
解密后数据为: 测试数据

3. 非对称加密(也叫公钥加密)

1.简介

指的是加密和解密使用不同的秘钥。

一把作为公开的公钥,另一把作为私钥。这对密钥中的公钥进行加密,私钥用于解密。反之亦然(被私钥加密的数据也可以被公钥解密) 。

在实际使用中私钥一般保存在发布者手中,是私有的不对外公开的,只将公钥对外公布,就能实现只有私钥的持有者才能将数据解密的方法。 这种加密方式安全系数很高,因为它不用将解密的密钥进行传递,从而没有密钥在传递过程中被截获的风险,而破解密文几乎又是不可能的。

但是算法的效率低,所以常用于很重要数据的加密,常和对称配合使用,使用非对称加密的密钥去加密对称加密的密钥。

事实上,公钥加密算法很少用于数据加密,它通常只是用来做身份认证,因为它的密钥太长,加密速度太慢--公钥加密算法的速度甚至比对称加密算法的速度慢上3个数量级(1000倍)。

主要作用:

通常用于保证身份验证。

常用的公钥加密算法有:

  • RSA: 可以实现数字签名 和 数据加密

  • DSA: 只能实现数字签名,不能实现数据加密

特点:

  • 加密与解密使用的不同的密钥。

  • 实际上它所使用的密钥是一对儿,一个叫公钥,一个叫私钥。这对密钥不是独立的,公钥是从私钥中提炼出来,因此私钥是很长的,968位、1024位、2048位、4096位的都有。

  • 通常公钥是公开的,所有人都可以得到;私钥是不能公开的,只有自己才有。

  • 用公钥机密的内容只能用与之对应的私钥才能解密,反之亦然。

2.python中的使用

RSA

RSA公钥加密算法是1977年由罗纳德·李维斯特(Ron Rivest)、阿迪·萨莫尔(Adi Shamir)和伦纳德·阿德曼(Leonard Adleman)一起提出的。RSA就是他们三人姓氏开头字母拼在一起组成的。 RSA是目前最有影响力的公钥加密算法,它能够抵抗到目前为止已知的绝大多数密码攻击,RSA算法基于一个十分简单的数论事实:将两个大质数相乘十分容易,但是想要对其乘积进行因式分解却极其困难,因此可以将乘积公开作为加密密钥。

首先我们需要安装一个rsa模块:

pip install rsa

而且,因为RSA加密算法的特性,RSA的公钥私钥都是10进制的,但公钥的值常常保存为16进制的格式,所以需要将其用int()方法转换为10进制格式。

用网页中的公钥把数据加密

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))

运行结果:

公钥n值长度: 256
7b2ab6bffebc258c9ad577fed797868c5321a919b817e7f4fbf0f67ba450ace6cd4d9574345912226d1875dab7f0c973b3c442fc12fe5f1b71f8be3dccd071f8ca91c4dac7da046bba8461b7c88b5c8acfb4995650746aa3f5e241f5c97aafc46f5da222b41a7883aaa54457d9e47b62428fab94dc093bd840ba2454477143ad

 

作业

将AES和RSA的加密过程通过面向对象的方式写成一个类,封装起来。

只需要传入一些参数就可以进行加密。

Guess you like

Origin www.cnblogs.com/winfun/p/10984156.html