我需要在Python中加密一个小字符串。可以使用秘钥来加密字符串吗?是否有一种好的方法只使用Python库就可以实现合理的加密水平?您能向我展示如何做到这一点吗?
我的密码学知识非常基础。
我需要在Python中加密一个小字符串。可以使用秘钥来加密字符串吗?是否有一种好的方法只使用Python库就可以实现合理的加密水平?您能向我展示如何做到这一点吗?
我的密码学知识非常基础。
看一下py-bcrypt。也许它可以满足你的需求。从网站上可以看到:
py-bcrypt是OpenBSD Blowfish密码哈希代码的Python包装器,正如Niels Provos和David Mazières在《未来适应性密码方案》中所描述的那样。
Keyczar 是一个开源的加密工具包,旨在使开发人员更轻松、更安全地在他们的应用程序中使用加密。Keyczar 支持对称和非对称密钥的身份验证和加密。
crypter = Crypter.Read("/path/to/your/keys")
ciphertext = crypter.Encrypt("Secret message")
codeword = input('Enter codeword : ')
codeword = codeword.replace(" ", "")
encrypt = input('Enter text to encrypt : ')
encrypt = encrypt.replace(" ", "")
j = 0
for i in codeword:
print(chr(ord(encrypt[j])+ ord(codeword[j])-96))
j+=1
我会使用易于使用的cryptocode
库(https://github.com/gdavid7/cryptocode)来完成这项任务。
与其他库相比,加密和解密相对简单:
## Encrypting:
>>> import cryptocode
>>> myEncryptedMessage = cryptocode.encrypt("I like trains", "password123")
>>> print(myEncryptedMessage)
M+Wykmlub0z7FhEdmA==*PvAbXRNx0SiSDHHxLsKZ5w==*ihQM/fdkgrX3G+yOItyAUQ==*QFNDmuUP1ysgo01/P2MNpg==
## Decrypting:
>>> import cryptocode
>>> myDecryptedMessage = cryptocode.decrypt("M+Wykmlub0z7FhEdmA==*PvAbXRNx0SiSDHHxLsKZ5w==*ihQM/fdkgrX3G+yOItyAUQ==*QFNDmuUP1ysgo01/P2MNpg==", "password123")
>>> print(myDecryptedMessage)
I like trains
from cryptography.fernet import Fernet
import pyperclip
print("For this program to work, please send the file named 'pwkey' and the encrypted code to the other user.")
key = Fernet.generate_key()
file = open('pwkey', 'wb')
file.write(key)
file.close()
print('File Generated')
original = input('Enter message>>>')
message = original.encode()
f = Fernet(key)
encrypted = f.encrypt(message)
encrypted = encrypted.decode("ascii")
print('Encrypted:', encrypted)
pyperclip.copy(encrypted)
print('Please tell the other user to input the encrypted code in the Decrypt program')
print('(Code copied to Clipboard)')
print("Note: Please delete the 'pwkey' file after sending it to the other user. It
is for one-time use only.")
解密
# Decrypt
from cryptography.fernet import Fernet
print("For this program to work, make sure you have the file named 'pwkey' in your Python folder and the encrypted "
"code.")
file = open('pwkey', 'rb')
key = file.read()
file.close()
print('Key Retrieved')
encrypted = input('Please input your encrypted code>>>')
encrypted = bytes(encrypted, 'utf-8')
f = Fernet(key)
decrypted = f.decrypt(encrypted)
decrypted = decrypted.decode()
print('Decrypted Message:')
print(decrypted)
print("Note: Please delete the 'pwkey' file after getting the decrypted message. It is for one-time use only.")