python rsa加解密

# -*- coding: utf-8 -*-

import base64
import re
import binascii
from M2Crypto import RSA, BIO

class RSAED(object):
    
    def __init__(self):
        
        self.publicKey = None
        self.privateKey = None
        
        #pkcs1_padding,no_padding etc.
        #no_padding模式时原字符串长度貌似要是128,不够填\x00
        self.RSAModel = RSA.no_padding
    
    def makeKeyPair(self):
        
        rsa = RSA.gen_key(1024, 3, lambda *agr:None)
        pub_bio = BIO.MemoryBuffer()
        priv_bio = BIO.MemoryBuffer()
        
        rsa.save_pub_key_bio(pub_bio)
        rsa.save_key_bio(priv_bio, None)
        
        strPublicKey = pub_bio.read()
        pub_bio.write(strPublicKey)
        strPrivateKey = priv_bio.read()
        priv_bio.write(strPrivateKey)
        
        self.publicKey = RSA.load_pub_key_bio(pub_bio)
        self.privateKey = RSA.load_key_bio(priv_bio)


        pubfile = open('C:\\m2crypto_public.pem', 'w+')
        pubfile.write(strPublicKey)
        pubfile.close()
        
        prifile = open('C:\\m2crypto_private.pem', 'w+')
        prifile.write(strPrivateKey)
        prifile.close()
         
    def loadPublicKeyFromFile(self, strPublicKeyFilePath, strKeyFileFormat="DER"):
        
        f = open(strPublicKeyFilePath, "rb")
        self.publicKey=f.read()
        f.close()
        if strKeyFileFormat == "DER":
            self.publicKey = base64.encodestring(self.publicKey)
            self.publicKey = "-----BEGIN PUBLIC KEY-----\n%s-----END PUBLIC KEY-----" % self.publicKey
        pub_bio = BIO.MemoryBuffer(self.publicKey)
        self.publicKey = RSA.load_pub_key_bio(pub_bio)
    
    def loadPrivateKeyFromFile(self, strPrivateKeyFilePath, strKeyFileFormat="DER"):
        
        f=open(strPrivateKeyFilePath, "rb")
        self.privateKey=f.read()
        f.close()
        if strKeyFileFormat == "DER":
            self.privateKey = base64.encodestring(self.privateKey)
            self.privateKey = "-----BEGIN PRIVATE KEY-----\n%s-----END PRIVATE KEY-----" % self.privateKey
        priv_bio = BIO.MemoryBuffer(self.privateKey)
        self.privateKey = RSA.load_key_bio(priv_bio)
    
    def getRASEncrypt(self, strSource):
        
        strEncrypted = self.publicKey.public_encrypt(strSource, self.RSAModel)
        
        return strEncrypted
    
    def getRASDecrypt(self, strEncrypted):
        
        strDecrypted = self.privateKey.private_decrypt(strEncrypted, self.RSAModel)
        
        return strDecrypted
    
    def getAsciiStringfromHexString(self, strEncrypted):
        
        encryptedHexString = "".join([binascii.b2a_hex(i) for i in strEncrypted]).upper()
        
        return encryptedHexString
    
    def getHexStringfromAsciiString(self, strEncrypted):
        
        encryptedHexString = "".join([chr(int(i, 16)) for i in re.findall('.{2}', strEncrypted)])
        
        return encryptedHexString
    
    def splitStringWithWidth(self, strSource, width=128):
        
        lstTemp = []
        if len(strSource) <= 128:
            strSource += '\x00'*(128-len(strSource))
            lstTemp.append(strSource)
        else:
            lstTemp = re.findall('.{%s}' % width, strSource)
            nTemp = len("".join(lstTemp))
            if nTemp != len(strSource):
                lstTemp.append(strSource[nTemp:])
                lstTemp[-1] += '\x00'*(128-len(lstTemp[-1]))
            
        return lstTemp
    
if __name__ == "__main__":
    
    objRSAED = RSAED()
#     objRSAED.makeKeyPair()
#     objRSAED.loadPublicKeyFromFile("C:\\m2crypto_public.pem", "PEM")
#     objRSAED.loadPrivateKeyFromFile("C:\\m2crypto_private.pem", "PEM")


    objRSAED.loadPublicKeyFromFile("C:\\test-public.key")
    objRSAED.loadPrivateKeyFromFile("C:\\test-private.key")
    strSource = 'zz'*64 + 'w'
    for strSource in objRSAED.splitStringWithWidth(strSource):
        strEncrypted = objRSAED.getRASEncrypt(strSource)
        print strEncrypted
        print objRSAED.getAsciiStringfromHexString(strEncrypted)
        print objRSAED.getRASDecrypt(strEncrypted)
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值