使用Python进行字符串加密 利用win32com.client和CAPICOM

      在Python编程中,我们会使用到字符串加密,包括哈希加密以及密钥加密,哈希加密可以使用Python自带的hashlib,调用自带的MD5或者sha256等都可以,但是这种加密算法是不可逆的,理论来说除了哈希碰撞外无法解密,这当然不是我想要的。另外又有提到使用pycrypto,但是对于Windows下的支持不是很好。在网上找到了一些,如http://wangwei007.blog.51cto.com/68019/1108784,基本网上对于文章中的方法,都是生搬硬套,没有经过多少验证。找了一堆都是类似的文章,叫苦连天。

    在这些文章中,描述使用密钥进行加密解密,都是贴了类似的代码:

<span style="font-size:18px;">import win32com.client 
def encrypt(key,content): # key:密钥,content:明文 
    EncryptedData = win32com.client.Dispatch('CAPICOM.EncryptedData') 
    EncryptedData.Algorithm.KeyLength = 5 
    EncryptedData.Algorithm.Name = 2 
    EncryptedData.SetSecret(key) 
    EncryptedData.Content = content 
    return EncryptedData.Encrypt() 
 
def decrypt(key,content): # key:密钥,content:密文 
    EncryptedData = win32com.client.Dispatch('CAPICOM.EncryptedData') 
    EncryptedData.Algorithm.KeyLength = 5 
    EncryptedData.Algorithm.Name = 2 
    EncryptedData.SetSecret(key) 
    EncryptedData.Decrypt(content) 
    str = EncryptedData.Content 
    return str 
 
s1 = encrypt('lovebread', 'hello world') 
s2 = decrypt('lovebread', s1) 
print s1,s2 
 
# MGEGCSsGAQQBgjdYA6BUMFIGCisGAQQBgjdYAwGgRDBCAgMCAAECAmYBAgFABAgq 
# GpllWj9cswQQh/fnBUZ6ijwKDTH9DLZmBgQYmfaZ3VFyS/lq391oDtjlcRFGnXpx 
# lG7o 
# hello world </span>

    在实际使用的时候,在下载http://sourceforge.net/projects/pywin32/ 下载win32com组件,是必须要的。另外,在使用时还会出现系列的问题,主要原因包括:

1、未下载CAPICOM组件,该组件可以在http://www.microsoft.com/en-us/download/confirmation.aspx?id=25281下载;

2、对于下载的CAPICOM组件,还需要进行注册,在命令行下使用“regsvr32 capicom.dll”,对该组件进行注册。


    这样,就可以顺利方便的在Python下使用“CAPICOM.EncryptData”进行字符串的加密和解密了。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值