2010-09-28 76 views
25

是否有一种简单的方法来用密钥加密/解密字符串。用私钥简单加密/解密Python中的lib

财产以后这样的:

key = '1234' 
string = 'hello world' 
encrypted_string = encrypt(key, string) 
decrypt(key, encrypted_string) 

我无法找到任何简单的做到这一点。

+0

你已经为* RSA *和* Python *搜索了吗? – 2010-09-28 18:01:15

回答

23

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' 
21

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" 
+1

谢谢!我一直在寻找一个纯粹的python加密/解密方案(所以它实际上是可移植的),而这是我偶然发现的唯一一个。 – leetNightshade 2013-05-01 17:14:58

10

为Python 2,你应该使用keyczar http://www.keyczar.org/

for python 3,直到keyczar是可用,我写了简单的隐窝http://pypi.python.org/pypi/simple-crypt

我回答这两年很晚,因为事情发生了变化,因为问题被问到。

请注意,此问题的以前的答案使用弱密码(按今天的标准),并没有任何关键的加强。这两个建议可能会更安全。

+0

如果KeyCzar.org没有重定向,因为它在8月份不适合我,它的直接网址是https:// github。com/google/keyczar – AnneTheAgile 2015-09-08 20:20:05

1

使用加密密钥加密短文本片段的最简单和最快速的方法是使用加密哈希函数(md5,sha等)之一。

即您的密钥的计算md5,然后xor您的字符串片段与此md5散列。如果您需要对长度超过md5的文本碎片进行编码 - 执行md5(md5散列)并加密下一个碎片。

该解决方案的安全性比使用3-DES更差,但平均情况下足够安全(即,在配置文件中不存储非常安全的密码),并且除了基本的python发行版之外不需要任何其他软件。

如果您需要更好的安全性 - 寻找AES,Blowfish等实现之一,但要真正为AES带来好处,您需要做一些额外的工作来将数据与随机数据混合。

1

要扩大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'))