首先,接受者私钥是要基于口令加密放在电脑上,所以第一层加密就是,使用基于口令的对称密码加密接受者私钥
第二步,将数据用对称密码加密,且将会话**用接受者公钥加密,拼接在消息中,发送给接受者。
第三部,接受者解密
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)
key = m.digest()
return (key[:8], key[8:])
# DES-CBC解密
def decrypt(msg, password):
msg_bytes = base64.b64decode(msg)
salt = msg_bytes[:8]
enc_text = msg_bytes[8:]
(dk, iv) = get_derived_key(password, salt, 1000)
crypter = DES.new(dk, DES.MODE_CBC, iv)
text = crypter.decrypt(enc_text)
# remove the padding at the end, if any
return re.sub(r'[\x01-\x08]', '', text)
# DES-CBC 加密
def encrypt(msg, password):
salt = os.urandom(8)
pad_num = 8 - (len(msg) % 8)
for i in range(pad_num):
msg += chr(pad_num)
(dk, iv) = get_derived_key(password, salt, 1000)
# 填充到8位的整数倍
crypter = DES.new(dk, DES.MODE_CBC, iv)
enc_text = crypter.encrypt(msg)
return base64.b64encode(salt + enc_text)
# 用于解密对称会话**
class RSA_encryto:
def __init__(self):
rsa = RSA.generate(1024, Random.new().read)
private = rsa.exportKey()
public_key = rsa.publickey().exportKey()
self.__private_key = private
self.public_key = public_key
# 导出明文公钥
def export_public_key(self):
return self.public_key
# 导出DES加密后的**
def export_encypted_private_key(self):
salt = os.urandom(8)
private = self.__private_key
pad_num = 8 - (len(private) % 8)
for i in range(pad_num):
private += chr(pad_num)
password = raw_input("口令:")
(dk, iv) = get_derived_key(password, salt, 1000)
crypter = DES.new(dk, DES.MODE_CBC, iv)
enc_text = crypter.encrypt(private)
return base64.b64encode(salt + enc_text)
def main():
rsa = RSA_encryto() #创建rsa实体对象
commuicate_key = "helloworld" #产生会话**
msg = raw_input("msg:") #读取msg
ec_msg = encrypt(msg, commuicate_key) #加密消息msg
# 1. 导出rsa**到pc上
ec_private_key = rsa.export_encypted_private_key()
print ("加密后rsa**:"+ec_private_key)
# 2. RSA加密会话**
publickey = rsa.export_public_key()
rsakey = RSA.importKey(publickey)
cipher = Cipher_pkcs1_v1_5.new(rsakey)
cipher_text = base64.b64encode(cipher.encrypt(commuicate_key.encode(encoding="utf-8")))
# cipher_text = cipher.encrypt(commuicate_key)
print("加密文件内容:" + ec_msg+ ", 加密会话**为: "+cipher_text)
# 3. 解密RSA私钥
password = raw_input("口令:")
rsa_privatekey = decrypt(ec_private_key, password)
# 4. 解密会话**
rsa_key = RSA.importKey(rsa_privatekey) # 导入读取到的私钥
cipher = Cipher_pkcs1_v1_5.new(rsa_key) # 生成对象
commuicatekey = cipher.decrypt(base64.b64decode(cipher_text), "ERROR")
# commuicatekey = cipher.decrypt(cipher_text, "ERROR")
# 5. 解密msg
de_msg = decrypt(ec_msg, commuicatekey)
print("msg:" + de_msg)
if __name__ == "__main__":
main()
python3 版本:
与py2最头痛的点就是bytes与str的转换,一定要清楚加解密之后是bytes而不是str,否则会导致结果乱码。
#!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
"""
#使用口令与盐,创建对称**与初始化向量
def get_derived_key(password, salt, count):
key = str(password)+ str(salt)
for i in range(count):
m = hashlib.md5(str(key).encode('utf-8'))
key = m.digest()
return (key[:8], key[8:])
# DES-CBC解密
def decrypt(msg, password):
msg_bytes = base64.b64decode(msg)
salt = msg_bytes[:8]
enc_text = msg_bytes[8:]
(dk, iv) = get_derived_key(password, salt, 1000)
crypter = DES.new(dk, DES.MODE_CBC, iv)
text = crypter.decrypt(enc_text)
# remove the padding at the end, if any
return re.split(rb'[\x01-\x08]',text)[0]
#return re.sub(r'[\x01-\x08]', '', text.decode())
# DES-CBC 加密
def encrypt(msg, password):
salt = os.urandom(8)
pad_num = 8 - (len(msg) % 8)
for i in range(pad_num):
msg += chr(pad_num)
(dk, iv) = get_derived_key(password, salt, 1000)
crypter = DES.new(dk, DES.MODE_CBC, iv)
enc_text = crypter.encrypt(msg.encode(encoding='utf-8'))
return base64.b64encode(salt + enc_text)
# 用于解密对称会话**
class RSA_encryto:
def __init__(self):
rsa = RSA.generate(1024, Random.new().read)
private = rsa.exportKey()
public_key = rsa.publickey().exportKey()
self.__private_key = private
self.public_key = public_key
self.__rsa = rsa
def export_public_key(self):
return self.public_key
def export_encypted_private_key(self):
salt = os.urandom(8)
private = self.__private_key
pad_num = 8 - (len(private) % 8)
for i in range(pad_num):
private += chr(pad_num).encode(encoding='utf-8')
password = input("口令:")
(dk, iv) = get_derived_key(password, salt, 1000)
crypter = DES.new(dk, DES.MODE_CBC, iv)
enc_text = crypter.encrypt(private)
return base64.b64encode(salt + enc_text)
def main():
rsa = RSA_encryto() #创建rsa实体对象
commuicate_key = "helloworld" #产生会话**
msg = input("msg:") #读取msg
ec_msg = encrypt(msg, commuicate_key) #加密消息msg
# 1. 导出rsa**到pc上
ec_private_key = rsa.export_encypted_private_key()
print ("加密后rsa**:"+str(ec_private_key))
# 2. RSA加密会话**
publickey = rsa.export_public_key()
rsakey = RSA.importKey(publickey)
cipher = Cipher_pkcs1_v1_5.new(rsakey)
cipher_text = base64.b64encode(cipher.encrypt(commuicate_key.encode(encoding='utf-8')))
# cipher_text = cipher.encrypt(commuicate_key)
print("加密文件内容:" + str(ec_msg)+ ", 加密会话**为: "+str(cipher_text))
# 3. 解密RSA私钥
password = input("口令:")
rsa_privatekey = decrypt(ec_private_key, password)
# 4. 解密会话**
rsa_key = RSA.importKey(rsa_privatekey) # 导入读取到的私钥
cipher = Cipher_pkcs1_v1_5.new(rsa_key) # 生成对象
commuicatekey = cipher.decrypt(base64.b64decode(cipher_text), "ERROR")
# commuicatekey = cipher.decrypt(cipher_text, "ERROR")
# 5. 解密msg
de_msg = decrypt(ec_msg, str(commuicatekey, encoding='utf-8'))
print("msg:" + str(de_msg, encoding='utf-8'))
if __name__ == "__main__":
main()
如果大家有什么改进意见,感谢大家留言,转载还请注明出处