首先,接受者私钥是要基于口令加密放在电脑上,所以第一层加密就是,使用基于口令的对称密码加密接受者私钥
第二步,将数据用对称密码加密,且将会话密钥用接受者公钥加密,拼接在消息中,发送给接受者。
第三部,接受者解密
python2版本实现:
需要pip install pycrypto
可能会出现问题,详见Microsoft Visual C++ 9.0 is required Unable to find vcvarsall.bat
#!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)