python 输入密码加密显示_如何在python中用密码加密文本?

本文介绍了使用Python的Crypto库实现AES加密解密的过程,包括密码转化为AES密钥、生成初始化向量、字符串填充和解填充,以及Base64编码解码。提供了完整的测试用例以确保加密解密的正确性。
摘要由CSDN通过智能技术生成

基于zwer的答案,但解决了一个小错误,当源正好是16的倍数。

代码:from builtins import bytes

import base64

from Crypto.Cipher import AES

from Crypto.Hash import SHA256

from Crypto import Random

def encrypt(string, password):

"""

It returns an encrypted string which can be decrypted just by the

password.

"""

key = password_to_key(password)

IV = make_initialization_vector()

encryptor = AES.new(key, AES.MODE_CBC, IV)

# store the IV at the beginning and encrypt

return IV + encryptor.encrypt(pad_string(string))

def decrypt(string, password):

key = password_to_key(password)

# extract the IV from the beginning

IV = string[:AES.block_size]

decryptor = AES.new(key, AES.MODE_CBC, IV)

string = decryptor.decrypt(string[AES.block_size:])

return unpad_string(string)

def password_to_key(password):

"""

Use SHA-256 over our password to get a proper-sized AES key.

This hashes our password into a 256 bit string.

"""

return SHA256.new(password).digest()

def make_initialization_vector():

"""

An initialization vector (IV) is a fixed-size input to a cryptographic

primitive that is typically required to be random or pseudorandom.

Randomization is crucial for encryption schemes to achieve semantic

security, a property whereby repeated usage of the scheme under the

same key does not allow an attacker to infer relationships

between segments of the encrypted message.

"""

return Random.new().read(AES.block_size)

def pad_string(string, chunk_size=AES.block_size):

"""

Pad string the peculirarity that uses the first byte

is used to store how much padding is applied

"""

assert chunk_size <= 256, 'We are using one byte to represent padding'

to_pad = (chunk_size - (len(string) + 1)) % chunk_size

return bytes([to_pad]) + string + bytes([0] * to_pad)

def unpad_string(string):

to_pad = string[0]

return string[1:-to_pad]

def encode(string):

"""

Base64 encoding schemes are commonly used when there is a need to encode

binary data that needs be stored and transferred over media that are

designed to deal with textual data.

This is to ensure that the data remains intact without

modification during transport.

"""

return base64.b64encode(string).decode("latin-1")

def decode(string):

return base64.b64decode(string.encode("latin-1"))

测试:def random_text(length):

def rand_lower():

return chr(randint(ord('a'), ord('z')))

string = ''.join([rand_lower() for _ in range(length)])

return bytes(string, encoding='utf-8')

def test_encoding():

string = random_text(100)

assert encode(string) != string

assert decode(encode(string)) == string

def test_padding():

assert len(pad_string(random_text(14))) == 16

assert len(pad_string(random_text(15))) == 16

assert len(pad_string(random_text(16))) == 32

def test_encryption():

string = random_text(100)

password = random_text(20)

assert encrypt(string, password) != string

assert decrypt(encrypt(string, password), password) == string

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值