1.Python实现RSA算法的加密、解密、签名/验证签名
1.1生成秘钥
from Crypto.PublicKey import RSA
from Crypto import Random
random_generator = Random.new().read
random_generator
key = RSA.generate(2048,random_generator)# rsa算法生成实例
# 秘钥对的生成
private_pem = key.exportKey()
private_pem
public_pem = key.publickey().exportKey()
public_pem
1.2加密
from Crypto.Cipher import PKCS1_v1_5 as Cipher_pkcs1_v1_5
import base64
message = 'hello , this is a test text'
rsakey = RSA.importKey(public_pem)
cipher = Cipher_pkcs1_v1_5.new(rsakey)#加密
cipher_text = base64.b64encode(cipher.encrypt(message.encode("utf-8")))#序列化
cipher_text
1.3解密
rsakey = RSA.importKey(private_pem)
cipher = Cipher_pkcs1_v1_5.new(rsakey)
text = cipher.decrypt(base64.b64decode(cipher_text), random_generator)#解密
text
with open('private.pem', 'wb') as f:
f.write(private_pem)
with open('public_pem', 'wb') as f:
f.write(public_pem)
1.4数字签名
from Crypto.PublicKey import RSA
from Crypto.Hash import SHA
from Crypto.Signature import PKCS1_v1_5 as Signature_pkcs1_v1_5
import base64
#使用自己的秘钥对内容进行签名
message = 'hello , this is a test text'
with open('private.pem') as f:
key = f.read()
rsakey = RSA.importKey(key)
signer = Signature_pkcs1_v1_5.new(rsakey)# 构建签名
digest = SHA.new()
digest.update(message) # 使用SHA算法获得摘要
sign = signer.sign(digest) # 使用摘要签名
signature = base64.b64encode(sign) #序列化
#使用公钥解码签名
with open('public_pem') as f:
key = f.read()
rsakey = RSA.importKey(key)
verifier = Signature_pkcs1_v1_5.new(rsakey)
digest = SHA.new()
# Assumes the data is base64 encoded to begin with
digest.update(message)
is_verify = signer.verify(digest, base64.b64decode(signature))
#对比解码后的签名和原文的摘要已确认
print is_verify
用Python实现DH秘钥交换协议
用crypto模块实现
const crypto = require('crypto');
// xiaoming's keys:
var ming = crypto.createDiffieHellman(512);
var ming_keys = ming.generateKeys();
var prime = ming.getPrime();
var generator = ming.getGenerator();
console.log('Prime: ' + prime.toString('hex'));
console.log('Generator: ' + generator.toString('hex'));
// xiaohong's keys:
var hong = crypto.createDiffieHellman(prime, generator);
var hong_keys = hong.generateKeys();
// exchange and generate secret:
var ming_secret = ming.computeSecret(hong_keys);
var hong_secret = hong.computeSecret(ming_keys);
// print secret:
console.log('Secret of Xiao Ming: ' + ming_secret.toString('hex'));
console.log('Secret of Xiao Hong: ' + hong_secret.toString('hex'));
网友评论