python2,3实现基于口令的PGP加解密

本文介绍了如何使用Python2和Python3实现基于口令的PGP加解密。首先,利用口令加密私钥,然后用对称密码加密数据并用接收者的公钥加密会话密钥。Python2版本需要安装pycrypto库,可能遇到编译问题;Python3版本着重处理了字节与字符串的转换,以避免乱码问题。欢迎提出改进建议,转载请注明出处。
摘要由CSDN通过智能技术生成

首先,接受者私钥是要基于口令加密放在电脑上,所以第一层加密就是,使用基于口令的对称密码加密接受者私钥

第二步,将数据用对称密码加密,且将会话密钥用接受者公钥加密,拼接在消息中,发送给接受者。

第三部,接受者解密

 python2版本实现:

需要pip install pycrypto

可能会出现问题,详见Microsoft Visual C++ 9.0 is required Unable to find vcvarsall.bat

No module named Crypto 

#!usr/bin/python
# encoding:utf-8
import base64
import hashlib
import re
import os
from Crypto.Cipher import DES
from Crypto.PublicKey import RSA
from Crypto import Random
from Crypto.Cipher import PKCS1_v1_5 as Cipher_pkcs1_v1_5

"""
Note about PBEWithMD5AndDES in java crypto library:

Encrypt:
  Generate a salt (random): 8 bytes
  <start derived key generation>
  Append salt to the password
  MD5 Hash it, and hash the result, hash the result ... 1000 times
  MD5 always gives us a 16 byte hash
  Final result: first 8 bytes is the "key" and the next is the "initialization vector"
  (there is something about the first 8 bytes needing to be of odd paraity, therefore
  the least significant bit needs to be changed to 1 if required. We don't do it,
  maybe the python crypto library does it for us)
  <end derived key generation>

  Pad the input string with 1-8 bytes (note: not 0-7, so we always have padding)
    so that the result is a multiple of 8 bytes. Padding byte value is same as number of
    bytes being padded, eg, \x07 if 7 bytes need to be padded.
  Use the key and iv to encrypt the input string, using DES with CBC mode.
  Prepend the encrypted value with the salt (needed for decrypting since it is random)
  Base64 encode it -> this is your result

Decrypt:
  Base64 decode the input message
  Extract the salt (first 8 bytes). The rest is the encoded text.
  Use derived key generation as in Encrypt above to get the key and iv
  Decrypt the encoded text using key and iv
  Remove padding -> this is your result

"""

#使用口令与盐,创建对称密钥(前8位)与初始化向量(后8位)
def get_derived_key(password, salt, count):
    key = str(password) + salt
    for i in range(count):
        m = hashlib.md5(key)
  • 2
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值