python aes加密_在不到5分钟的时间内用python编码aes128位加密

本文介绍了如何在Python中快速实现AES128位加密,详细讲解了加密过程,适合对加密算法感兴趣的开发者参考。
摘要由CSDN通过智能技术生成

python aes加密

Rapid implementation of symmetric key encryption using the Fernet cipher, in Python’s cryptography library.

在Python的密码库中使用Fernet密码快速实现对称密钥加密。

Symmetric key encryption is one of the simplest forms of message encryption where sender and recipient(s) utilize the exact same secret key to both encrypt and decrypt. The key is shared securely with all parties that want to read the ciphertext, and they decipher it by loading it into the algorithm that was used to encode it. Here, we’ll be using the AES128-bit Fernet cipher with Python’s cryptography library.

对称密钥加密是消息加密的最简单形式之一,其中发件人和收件人使用完全相同的秘密密钥进行加密和解密。 密钥与所有希望读取密文的各方安全地共享,他们通过将密文加载到用于对其进行编码的算法中来对其进行解密。 在这里,我们将结合使用AES128位Fernet密码和Python的密码库。

A “key” or a “secret” in cryptography is just a chain of bytes generated by the cipher method (the encryption algorithm) that is used on one end to encrypt a message, and on the other end to decrypt a message. Think, for example: “I will shift every letter in this message by one, to the next letter in the alphabet, so when you get this ciphertext, shift every letter by one, to the previous letter, to reveal my original, encoded message.”

密码术中的“密钥”或“秘密”只是由加密方法(加密算法)生成的一串字节,该加密方法的一端用于加密消息,另一端用于解密消息。 例如,想想:“我将把此消息中的每个字母都移动一个,移至字母表中的下一个字母,因此,当您获得密文时,将每个字母都移动一个字母,移至上一个字母,以显示我的原始编码消息。”

Try deciphering this secret message with the key I just described: Dbo zpv sfbe uijt? Cf tvsf up esjol zprs pwbmujof.

尝试使用我刚刚描述的密钥来解密此秘密消息:Dbo zpv sfbe uijt? cf tvsf up esjol zprs pwbmujof。

As an example, here’s what a computer generated key file typically looks like on the inside:

例如,这是计算机生成的密钥文件通常在内部的外观:

s_g6nE4J-nKktINfrO2b8qyX1H7cpfsqyMnxrWoVSQU=

s_g6nE4J-nKktINfrO2b8qyX1H7cpfsqyMnxrWoVSQU=

As long as you and another person have the same string of bytes, you’ll be able to encrypt a message into an indecipherable bunch of letters and numbers, and no one will be able to decode what you wrote without the key, or else at least some quantum computing power at their disposal.

只要您和另一个人使用相同的字节串,您就可以将邮件加密为一堆无法辨认的字母和数字,并且没有人将无法解码您在没有密钥的情况下写的内容,否则至少有一些量子计算能力可供使用。

Unlike asymmetric encryption, where each person has their own unique, private key, and openly shared public keys, symmetric encryption is simple, straight-forward and easy to manage for basic projects and wide range of encryption needs. The tricky part is securely sharing the key without exposing it to snoopy snoopers.

非对称加密不同, 非对称加密每个人都有自己的唯一私钥和公开共享的公共密钥,而对称加密则简单,直接且易于管理,可满足基本项目和各种加密需求。 棘手的部分是安全地共享密钥,而不会将其暴露给窥探者。

If you’re just starting and want to get into some decent quality, small message encryption, really quickly and easily — read on.

如果您只是刚刚开始并且想获得某种体面的质量,真正快速,轻松地进行小消息加密-请继续阅读。

第1部分。在密码学库中进行设置 (Part 1. Getting set up in the Cryptography library)

Step 1: Install cryptography. For detailed instructions, go here. Otherwise, just start from your command line:

步骤1:安装加密。 有关详细说明,请转到此处 。 否则,只需从命令行开始:

pip install cryptography # or pip3

Step 2: Import your libraries into a fresh python file by putting this at the top. Suggestion: just call it fernet_encryption.py if you don’t want to think of a name.

第2步:将库放在顶部,将您的库导入到新的python文件中。 建议:如果您不想考虑名称,只需将其命名为fernet_encryption.py

# Import the Fernet class. 
from cryptography.fernet import Fernet

第2部分:加密秘密消息 (Part 2: Encrypting a secret message)

Now, to generate a secret message, we’ll need a few things.

现在,要生成一条秘密消息,我们需要做一些事情。

  1. Generate a fresh key.

    生成一个新密钥。
  2. Create a message to encode.

    创建一条消息进行编码。
  3. Encrypt that message with the key, and store it as a ciphertext variable.

    用密钥加密该消息,并将其存储为密文变量。
  4. Pass that message to the recipient.

    将该消息传递给收件人。

1.生成密钥: (1. Generating the key:)

First, we’ll generate the key, and then we’ll write it to a .key file. We’ll use the same folder where your python file is located for now, but you may choose any path.

首先,我们将生成密钥,然后将其写入.key文件。 我们现在将使用您的python文件所在的文件夹,但是您可以选择任何路径。

# Use Fernet to generate the key file.
key = Fernet.generate_key() # Store the file to disk to be accessed for en/de:crypting later.
with open('secret.key', 'wb') as new_key_file:
new_key_file.write(key)print(key)>>> b'G5mX1vlxKVaQkdg3CfhH6pVQIctECVw3MN6uCXbJpGo='

Encoding types: That ‘b’ at the front of the message means it is being stored as bytes. Encoding types are different ways of storing the same data. Here, it’s a ‘UTF-8’ type encoding, and those are the characters used to encode it. It’s a more advanced topic, and you will need to travel back and forth between different types like ‘base64’, or ‘hex’ if you get really deep into cryptography, but for this introduction, don’t even worry about it. When you see b, just think “that’s not a string, that’s bytes!”

编码类型:消息开头的“ b”表示将其存储为字节。 编码类型是存储相同数据的不同方式。 在这里,它是“ UTF-8”类型的编码,这些是用于对其进行编码的字符。 这是一个更高级的主题,如果您真的很了解密码技术,那么您将需要在'base64'或'hex'之类的不同类型之间来回移动,但是对于本入门,您甚至不必担心。 当您看到b时,只需思考“那不是字符串,那是字节!”

Python gives us a real simple way to translate back and forth between strings and bytes with the .encode() and .decode() functions. If you start to get funny errors, make sure your strings are encoded(string.encode()) when needed, and your byte-string messages are decoded (bytes_msg.decode()) when required.

Python使用.encode()和.decode()函数为我们提供了一种在字符串和字节之间来回转换的真正简单方法。 如果您开始遇到有趣的错误,请确保在需要时对字符串进行编码(string.encode()),并在需要时对字节字符串消息进行解码(bytes_msg.decode())。

2.创建一条消息进行编码: (2. Creating a message to encode:)

This is your encryption “hello world” so pick anything you want, it doesn’t matter. Here’s what I’m using:

这是您的加密“ hello world”,因此选择任何您想要的东西都没关系。 这是我正在使用的:

msg = "Into the valley of death, rode the 600."# Encode this as bytes to feed into the algorithm.
# (Refer to Encoding types above).msg = msg.encode()

3.加密消息: (3. Encrypting the message:)

Instantiate a Fernet() object as f, using the key you just created. This tells the algorithm to encrypt and decrypt using that key. Then, pass your message into it, and store it off as the encrypted message ciphertext.

使用刚创建的密钥将Fernet()对象实例化为f 。 这告诉算法使用该密钥进行加密和解密。 然后,将您的消息传递给它,并将其作为加密的消息ciphertext.存储起来ciphertext.

# Instantiate the object with your key.
f = Fernet(key)# Pass your bytes type message into encrypt.
ciphertext = f.encrypt(msg)print(ciphertext)

You should see something like this:

您应该会看到以下内容:

b'gAAAAABfRyALC7N-3gxMZsGYMjZMZIegYgBca2ZNzjtyS--TNYCqBP10YsZTQnzOMlrLuuSUALkq9GnNb5BBZeHwuztqM7ir_Yh9hoXwsQH6ywbW7ehbgUIUNtmasBuj63vHD-EHNo9U'

That, ladies, gents and other, is your ciphertext. Well it’s mine. Yours will look different. Why? Because it is the message created from feeding your message string, converted to bytes, into the encrypt method of a Fernet object, created with your private key. How do you read it? You guessed it — Fernet’s decrypt method.

女士们,绅士们和其他人就是您的密文。 好吧,这是我的。 您的外观会有所不同。 为什么? 因为它是从喂养你的消息字符串创建的消息,转换成字节,进encrypt一个Fernet对象的方法,使用私钥创建的。 您如何阅读? 您猜对了-Fernet的decrypt方法。

第3部分。解密收到的消息。 (Part 3. Decrypting a received message.)

Let’s assume you’re not on the same runtime that the message was created on. Therefore, we’re going to load the key. If the key is in the same folder as your python file, the following code will store the key as a variable, and use it to decrypt your new message. This key must be the same as the key that was used to generate the cipher text.

假设您不在创建消息的同一运行时。 因此,我们将加载密钥。 如果密钥与python文件位于同一文件夹中,则以下代码会将密钥存储为变量,并用它来解密新消息。 该密钥必须与用于生成密文的密钥相同。

收件人档案: (Recipient’s file:)

from cryptography.fernet import Fernet# Load the private key from a file.
with open('secret.key', 'rb') as my_private_key:
key = my_private_key.read()# Instantiate Fernet on the recip system.
f = Fernet(key)# Decrypt the message.
cleartext = f.decrypt(ciphertext)# Decode the bytes back into a string.
cleartext = cleartext.decode()print(cleartext)
>>> Into the valley of death, rode the 600.

That is literally it. You are now able to send and receive messages encrypted with AES128 encryption, and 128-bits is pretty solid:

就是这样。 现在,您可以发送和接收使用AES128加密加密的消息,并且128位非常可靠:

“in 2017… the most powerful computer in the world would still take some 885 quadrillion years to brute force a 128-bit AES key.” — proprivacy.com

“在2017年……世界上功能最强大的计算机仍然需要大约885万亿年才能强行使用128位AES密钥。” — proprivacy.com

Specifically, from the Fernet documentation:

具体来说,从Fernet 文档中

Fernet is built on top of a number of standard cryptographic primitives. Specifically it uses:

Fernet建立在许多标准密码原语之上。 具体来说,它使用:

AES in CBC mode with a 128-bit key for encryption; using PKCS7 padding.

CBC模式下的AES ,带有用于加密的128位密钥; 使用PKCS7填充。

HMAC using SHA256 for authentication.

HMAC使用SHA256进行身份验证。

Initialization vectors are generated using os.urandom().

初始化向量是使用os.urandom()生成的。

If you wanted to hide nuclear secrets, consult a security professional. But if you just want to keep prying eyes off all of your data in plaintext, it is a really solid, super simple option.

如果您想隐藏核秘密,请咨询安全专家。 但是,如果您只是想窥视所有明文数据,这是一个非常可靠的超级简单的选择。

潜水更深 (Diving deeper)

For further reading, if you‘d like to understand some good advice for cryptography n00bs, start with Latacora’s Cryptographic Right Answers. I’ll cover the recommended PyNaCl library for Python in a later article, but this should get you going for now.

为了进一步阅读,如果您想了解有关n00bs加密的一些好的建议,请从Latacora的Cryptographic Right Answers开始 。 在以后的文章中,我将介绍推荐的Python PyNaCl库,但这应该可以帮助您。

将以上代码下载到可用模块中: (Download the above code in a usable module:)

Here it is in a class if you want to use it for your code: https://github.com/sachio222/medium/blob/master/FernetCipher.py

如果要在代码中使用它,则它在类中: https : //github.com/sachio222/medium/blob/master/FernetCipher.py

It contains basically the same methods, just arranged in a way so you can call them easily in your code:

它包含基本相同的方法,只是以一种方式安排,因此您可以在代码中轻松地调用它们:

Happy encrypting!

加密愉快!

翻译自: https://medium.com/swlh/coding-aes128-bit-encryption-in-python-in-less-than-5-minutes-f6bcbddd2b82

python aes加密

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值