Pycrypto与RSA密码技术笔记

本文介绍如何使用Pycrypto库实现RSA非对称加密技术,包括密钥生成、加密解密及签名验证的过程。通过实际代码演示了Master与Ghost之间如何安全地交换信息。
Pycrypto与RSA密码技术笔记
 


参考资料:http://www.jianshu.com/p/6a39610122fa
根据自己的实践修正了参考资料中的一些错误并根据自己的理解进行了一些整理。


RSA是一种非对称加密
具体自行百度


一些准备工作
pip install pycrypto
即可安装


如果安装完毕后import报错说未找到crypto,试着找到安装路径把Crypto改成crypto


# -*- coding: utf-8 -*-
from __future__ importunicode_literals,division
import os
os.chdir('Z:/')
from Crypto import Random
from Crypto.Hash import SHA
from Crypto.Cipher import PKCS1_v1_5 asCipher_pkcs1_v1_5
from Crypto.Signature import PKCS1_v1_5 asSignature_pkcs1_v1_5
from Crypto.PublicKey import RSA
import base64






#来源见
#Pycrypto与RSA密码技术笔记.docx




# 伪随机数生成器
random_generator = Random.new().read
# rsa算法生成实例
rsa = RSA.generate(1024, random_generator)




假设Master给Ghost进行秘密通信,则两人分别各自产生一个密钥对,并发给对方自己的公钥。


# master这边
# master的秘钥对的生成
private_pem = rsa.exportKey()
with open('master-private.pem', 'w') as f:
    f.write(private_pem)
public_pem = rsa.publickey().exportKey()
with open('master-public.pem', 'w') as f:
    f.write(public_pem)


# ghost这边
# ghost的秘钥对的生成
private_pem = rsa.exportKey()
with open('ghost-private.pem', 'w') as f:
    f.write(private_pem)
public_pem = rsa.publickey().exportKey()
with open('ghost-public.pem', 'w') as f:
    f.write(public_pem)




Master利用收到的ghost的公钥和自己要发送的内容(str类型)生成一段加密的信息发给对方




#注意,被加密的内容必须为str类型
message = b'hello ghost, this is a pliantext'
#或者这样
message = '糖,溶啦!!!'.encode('utf-8')
with open('ghost-public.pem') as f:
    key = f.read()
    rsakey = RSA.importKey(key)
    cipher = Cipher_pkcs1_v1_5.new(rsakey)
    cipher_text = base64.b64encode(cipher.encrypt(message))
    print cipher_text
    #注意,每次运行得到的cipher_text都不一样。。。


Ghost利用自己的私钥对收到的加密信息进行解密
encrypt_text=cipher_text


with open('ghost-private.pem') as f:
    key = f.read()
    rsakey = RSA.importKey(key)
    cipher = Cipher_pkcs1_v1_5.new(rsakey)
    text = cipher.decrypt(base64.b64decode(encrypt_text), random_generator)
    print text




Ghost为了确认这段消息是Master发的
Master用自己的私钥对自己所发的消息进行签名


with open('master-private.pem') as f:
    key = f.read()
    rsakey = RSA.importKey(key)
    signer = Signature_pkcs1_v1_5.new(rsakey)
    digest = SHA.new()
    digest.update(message)
    sign = signer.sign(digest)
    signature = base64.b64encode(sign)
    print signature




Ghost利用Master提供的公钥对签名进行验证
with open('master-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 = verifier.verify(digest, base64.b64decode(signature))
    print is_verify






总结
加密解密:公钥加密,私钥解密
签名验签:私钥签名,公钥验签
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值