是否有一種簡單的方法來用密鑰加密/解密字符串。用私鑰簡單加密/解密Python中的lib
財產以後這樣的:
key = '1234'
string = 'hello world'
encrypted_string = encrypt(key, string)
decrypt(key, encrypted_string)
我無法找到任何簡單的做到這一點。
是否有一種簡單的方法來用密鑰加密/解密字符串。用私鑰簡單加密/解密Python中的lib
財產以後這樣的:
key = '1234'
string = 'hello world'
encrypted_string = encrypt(key, string)
decrypt(key, encrypted_string)
我無法找到任何簡單的做到這一點。
http://www.dlitz.net/software/pycrypto/應該做你想做的。
取自他們的文檔頁面。
>>> from Crypto.Cipher import DES
>>> obj=DES.new('abcdefgh', DES.MODE_ECB)
>>> plain="Guido van Rossum is a space alien."
>>> len(plain)
34
>>> obj.encrypt(plain)
Traceback (innermost last):
File "<stdin>", line 1, in ?
ValueError: Strings for DES must be a multiple of 8 in length
>>> ciph=obj.encrypt(plain+'XXXXXX')
>>> ciph
'\021,\343Nq\214DY\337T\342pA\372\255\311s\210\363,\300j\330\250\312\347\342I\3215w\03561\303dgb/\006'
>>> obj.decrypt(ciph)
'Guido van Rossum is a space alien.XXXXXX'
pyDES是完全用python編寫的DES和Triple-DES實現。
下面是一個簡單而便攜的示例,應該足夠安全以滿足基本的字符串加密需求。只要把pyDES模塊在同一文件夾作爲您的程序,並嘗試一下:
發件人的電腦
>>> from pyDES import * # pyDes if installed from pip
>>> ciphertext = triple_des('a 16 or 24 byte password').encrypt("secret message", padmode=2) #plain-text usually needs padding, but padmode = 2 handles that automatically
>>> ciphertext
')\xd8\xbfFn#EY\xcbiH\xfa\x18\xb4\xf7\xa2' #gibberish
收件人的計算機
>>> from pyDES import *
>>> plain_text = triple_des('a 16 or 24 byte password').decrypt(')\xd8\xbfFn#EY\xcbiH\xfa\x18\xb4\xf7\xa2', padmode=2)
>>> plain_text
"secret message"
謝謝!我一直在尋找一個純粹的python加密/解密方案(所以它實際上是可移植的),而這是我偶然發現的唯一一個。 – leetNightshade 2013-05-01 17:14:58
爲Python 2,你應該使用keyczar http://www.keyczar.org/
for python 3,直到keyczar是可用,我寫了簡單的隱窩http://pypi.python.org/pypi/simple-crypt
我回答這兩年很晚,因爲事情發生了變化,因爲問題被問到。
請注意,此問題的以前的答案使用弱密碼(按今天的標準),並沒有任何關鍵的加強。這兩個建議可能會更安全。
如果KeyCzar.org沒有重定向,因爲它在8月份不適合我,它的直接網址是https:// github。com/google/keyczar – AnneTheAgile 2015-09-08 20:20:05
使用加密密鑰加密短文本片段的最簡單和最快速的方法是使用加密哈希函數(md5,sha等)之一。
即您的密鑰的計算md5,然後xor您的字符串片段與此md5散列。如果您需要對長度超過md5的文本碎片進行編碼 - 執行md5(md5散列)並加密下一個碎片。
該解決方案的安全性比使用3-DES更差,但平均情況下足夠安全(即,在配置文件中不存儲非常安全的密碼),並且除了基本的python發行版之外不需要任何其他軟件。
如果您需要更好的安全性 - 尋找AES,Blowfish等實現之一,但要真正爲AES帶來好處,您需要做一些額外的工作來將數據與隨機數據混合。
要擴大dsamersoff的答案..這是簡單和不安全的,但某些任務可能是有用的。這裏有一些代碼:
import crypt
import getpass
import os.path
def auth_func():
return (raw_input('Username:'), getpass.getpass('Password:'))
def xor(a,b):
assert len(b) >= len(a)
return "".join([chr(ord(a[i])^ord(b[i])) for i in range(len(a))])
# create a new credentials file if needed
if not os.path.exists('cred'):
with open('cred', 'w') as f:
user, pwd = auth_func()
f.write ("{}\n".format(user))
f.write ("{}\n".format(xor(pwd, crypt.crypt('secret', 'words'))))
f.close()
# read credentials and print user/password
with open('cred', 'r') as f:
user, pwd = f.read().split('\n')[:2]
print user
print xor(pwd, crypt.crypt('secret', 'words'))
你已經爲* RSA *和* Python *搜索了嗎? – 2010-09-28 18:01:15