Dav*_*vid 32 python encryption python-3.x
我一直在寻找如何加密和解密字符串.但大部分都在2.7中,任何使用3.2的东西都不允许我打印它或将它添加到字符串中.
所以我要做的是以下内容:
mystring = "Hello stackoverflow!"
encoded = encode(mystring,"password")
print(encoded)
Run Code Online (Sandbox Code Playgroud)
jgAKLJK34t3g(一串随机字母)
decoded = decode(encoded,"password")
print(decoded)
Run Code Online (Sandbox Code Playgroud)
你好stackoverflow!
无论如何这样做,使用python 3.X,当字符串被编码时,它仍然是一个字符串,而不是任何其他变量类型.
Pio*_*ski 29
看看PyCrypto.它支持Python 3.2,并且完全符合您的要求.
从他们的pip网站:
>>> from Crypto.Cipher import AES
>>> obj = AES.new('This is a key123', AES.MODE_CFB, 'This is an IV456')
>>> message = "The answer is no"
>>> ciphertext = obj.encrypt(message)
>>> ciphertext
'\xd6\x83\x8dd!VT\x92\xaa`A\x05\xe0\x9b\x8b\xf1'
>>> obj2 = AES.new('This is a key123', AES.MODE_CFB, 'This is an IV456')
>>> obj2.decrypt(ciphertext)
'The answer is no'
Run Code Online (Sandbox Code Playgroud)
如果要加密任意大小的消息AES.MODE_CFB而不是使用AES.MODE_CBC.
KRB*_*RBA 28
我在Windows 7系统和Python 3.5上编译所有最常提到的加密库时遇到了麻烦.
这是最终为我工作的解决方案.
from cryptography.fernet import Fernet
key = Fernet.generate_key() #this is your "password"
cipher_suite = Fernet(key)
encoded_text = cipher_suite.encrypt(b"Hello stackoverflow!")
decoded_text = cipher_suite.decrypt(encoded_text)
Run Code Online (Sandbox Code Playgroud)
Mil*_*vić 14
首先,我们需要安装密码学库:
pip3 install cryptography
Run Code Online (Sandbox Code Playgroud)
从密码学库中,我们需要导入Fernet并开始生成密钥 - 该密钥是对称加密/解密所必需的。
为了生成密钥,我们调用该generate_key()方法。
您需要将此密钥保存在安全的地方。如果丢失密钥,您将无法解密使用该密钥加密的数据。
一旦我们生成了密钥,我们需要加载密钥load_key()
这是一个三步过程:
encrypt()方法from cryptography.fernet import Fernet
def generate_key():
"""
Generates a key and save it into a file
"""
key = Fernet.generate_key()
with open("secret.key", "wb") as key_file:
key_file.write(key)
def load_key():
"""
Load the previously generated key
"""
return open("secret.key", "rb").read()
def encrypt_message(message):
"""
Encrypts a message
"""
key = load_key()
encoded_message = message.encode()
f = Fernet(key)
encrypted_message = f.encrypt(encoded_message)
print(encrypted_message)
if __name__ == "__main__":
# generate_key() # execute only once
encrypt_message("Hello stackoverflow!")
Run Code Online (Sandbox Code Playgroud)
输出:
b'gAAAAABgLX7Zj-kn-We2BI_c9NQhEtfJEnHUVhVqtiqjkDi5dgJafj-_8QUDyeNS2zsJTdBWg6SntRJOjOM1U5mIxxsGny7IEGqpVVdHwheTnwzSBlgpb80='
Run Code Online (Sandbox Code Playgroud)
要解密消息,我们只需调用库decrypt()中的方法即可Fernet。请记住,我们还需要加载密钥,因为需要密钥来解密消息。
from cryptography.fernet import Fernet
def load_key():
"""
Load the previously generated key
"""
return open("secret.key", "rb").read()
def decrypt_message(encrypted_message):
"""
Decrypts an encrypted message
"""
key = load_key()
f = Fernet(key)
decrypted_message = f.decrypt(encrypted_message)
print(decrypted_message.decode())
if __name__ == "__main__":
decrypt_message(b'gAAAAABgLX7Zj-kn-We2BI_c9NQhEtfJEnHUVhVqtiqjkDi5dgJafj-_8QUDyeNS2zsJTdBWg6SntRJOjOM1U5mIxxsGny7IEGqpVVdHwheTnwzSBlgpb80=')
Run Code Online (Sandbox Code Playgroud)
输出:
Hello stackoverflow!
Run Code Online (Sandbox Code Playgroud)
您的密码格式secret.key类似于以下密码:
B8wtXqwBA_zb2Iaz5pW8CIQIwGSYSFoBiLsVz-vTqzw=
Run Code Online (Sandbox Code Playgroud)
小智 9
尝试这个:
需要 Python 加密工具包 ( pycrypto )
$ pip install pycrypto
Run Code Online (Sandbox Code Playgroud)
代码:
from Crypto.Cipher import AES
from base64 import b64encode, b64decode
class Crypt:
def __init__(self, salt='SlTKeYOpHygTYkP3'):
self.salt = salt.encode('utf8')
self.enc_dec_method = 'utf-8'
def encrypt(self, str_to_enc, str_key):
try:
aes_obj = AES.new(str_key, AES.MODE_CFB, self.salt)
hx_enc = aes_obj.encrypt(str_to_enc.encode('utf8'))
mret = b64encode(hx_enc).decode(self.enc_dec_method)
return mret
except ValueError as value_error:
if value_error.args[0] == 'IV must be 16 bytes long':
raise ValueError('Encryption Error: SALT must be 16 characters long')
elif value_error.args[0] == 'AES key must be either 16, 24, or 32 bytes long':
raise ValueError('Encryption Error: Encryption key must be either 16, 24, or 32 characters long')
else:
raise ValueError(value_error)
def decrypt(self, enc_str, str_key):
try:
aes_obj = AES.new(str_key.encode('utf8'), AES.MODE_CFB, self.salt)
str_tmp = b64decode(enc_str.encode(self.enc_dec_method))
str_dec = aes_obj.decrypt(str_tmp)
mret = str_dec.decode(self.enc_dec_method)
return mret
except ValueError as value_error:
if value_error.args[0] == 'IV must be 16 bytes long':
raise ValueError('Decryption Error: SALT must be 16 characters long')
elif value_error.args[0] == 'AES key must be either 16, 24, or 32 bytes long':
raise ValueError('Decryption Error: Encryption key must be either 16, 24, or 32 characters long')
else:
raise ValueError(value_error)
Run Code Online (Sandbox Code Playgroud)
用法:
test_crpt = Crypt()
test_text = """Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod
tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam,
quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo
consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse
cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non
proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod
tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam,
quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo
consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse
cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non
proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod
tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam,
quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo
consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse
cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non
proident, sunt in culpa qui officia deserunt mollit anim id est laborum."""
test_key = 'MyKey4TestingYnP'
test_enc_text = test_crpt.encrypt(test_text, test_key)
test_dec_text = test_crpt.decrypt(test_enc_text, test_key)
print(f'Encrypted:{test_enc_text} Decrypted:{test_dec_text}')
Run Code Online (Sandbox Code Playgroud)
小智 8
您可以通过使用库轻松完成此操作cryptocode。以下是您的安装方法:
pip install cryptocode
Run Code Online (Sandbox Code Playgroud)
加密消息(示例代码):
import cryptocode
encoded = cryptocode.encrypt("mystring","mypassword")
## And then to decode it:
decoded = cryptocode.decrypt(encoded, "mypassword")
Run Code Online (Sandbox Code Playgroud)
文档可以在这里找到
| 归档时间: |
|
| 查看次数: |
106015 次 |
| 最近记录: |