python rsa 实践

来源:互联网 发布:unity3d 2d地图 编辑:程序博客网 时间:2024/06/18 11:24

最近在用python写长连接的东西,两三周前才开始接触python,所以一直在看书,写起代码来有点痛苦,基本上是跪着在摸索的。前一篇博客的protobuf(之前写android 只是接json,所以没对这个没什么概念)所以只能去github上看readme,readme好长,配合文档看了一个多小时,拉代码下来拉了两个多小时,这几天写python基本上是这个状态….

python 上的RSA其实用起来挺简单的,找到文档之后就很好解决了

https://www.dlitz.net/software/pycrypto/api/2.6/

简单包了一下,因为服务器是直接要ne 的,所以n, e 我都拿出来了,代码如下

# https://www.dlitz.net/software/pycrypto/api/2.6/import astfrom Crypto.PublicKey import RSAfrom Crypto import Randomfrom codecs import encodefrom Crypto.PublicKey.RSA import constructfrom binascii import unhexlifyclass RSAUtil(object):    def __init__(self):        self._key = None        self._public_key = None        self._n = None        self._e = None    def generate(self):        random_generator = Random.new().read        self._key = RSA.generate(1024, random_generator)        self._public_key = self._key.publickey()        self._n = self._key.n        self._e = self._key.e    def create(self, modulus, public_exponent):        self._e = int(public_exponent)        self._n = modulus        self._public_key = construct((int(encode(modulus, 'hex'), 16), public_exponent))    def public_key(self):        return self._public_key.exportKey()    def private_key(self):        if self._key is None:            raise ValueError("not private key,func generate() should be call before this")        return self._key.exportKey()    def public_exponent(self):        if self._e is None:            raise ValueError("not private key,func generate() should be call before this")        return self._e    def modulus(self):        if self._n is None:            raise ValueError("not private key,func generate() should be call before this")        return str(self.long_to_bytes(self._n))    def encode(self, data):        if self._public_key is None:            raise ValueError("not private key,func generate() should be call before this")        return self._public_key.encrypt(data, None)[0]    def decode(self, encrypts):        if self._key is None:            raise ValueError("not private key,func generate() should be call before this")        temp = (encrypts,)        return self._key.decrypt(ast.literal_eval(str(temp)))    def long_to_bytes(self, value, endianness='big'):        # https://stackoverflow.com/questions/8730927/convert-python-long-int-to-fixed-size-byte-array        width = value.bit_length()        width += 8 - ((width % 8) or 8)        fmt = '%%0%dx' % (width // 4)        s = unhexlify(fmt % value)        if endianness == 'little':            # see http://stackoverflow.com/a/931095/309233            s = s[::-1]        return s

测试代码:

if __name__ == "__main__":    # from Tool import RSAUtil    t = RSAUtil()    t.generate()    raw = "hello yeshen"    # encode    print raw    transfer = t.encode(raw)    # decode    print transfer    print t.decode(transfer)    # clone    clone = RSAUtil()    clone.create(t.modulus(), t.public_exponent())    transfer_clone = clone.encode(raw)    print transfer_clone    print t.decode(transfer_clone)

输出:

hello yeshen                                                                                                                                                                                                                                                        V��Y�j�����8���޷��yd�C%%I5��5b�� ��n���S?ƭ#l���/����(�����`����(8�<dMX0�o8I��Å�hello yeshen                                                                                                                                                                                                                                                        V��Y�j�����8���޷��yd�C%%I5��5b�� ��n���S#l���/����(�����`����(8�<dMX0�o8I��Å�hello yeshen

如果上面的这个不能用,应该是用另外一个实现!!!

from codecs import encodefrom Crypto.PublicKey.RSA import constructfrom binascii import unhexlifyimport rsaclass RSAUtil(object):    def __init__(self):        self._public_key = None        self._private_key = None        self._n = None        self._e = None    def generate(self):        public_key, private_key = rsa.newkeys(1024)        self._public_key = public_key        self._private_key = private_key        self._n = public_key.n        self._e = public_key.e    def create(self, modulus, public_exponent):        self._e = int(public_exponent)        self._n = modulus        self._public_key = construct((int(encode(modulus, 'hex'), 16), public_exponent))    def public_exponent(self):        if self._e is None:            raise ValueError("not private key,func generate() should be call before this")        return self._e    def modulus(self):        if self._n is None:            raise ValueError("not private key,func generate() should be call before this")        return str(self.long_to_bytes(self._n))    def decode(self, encrypts):        if self._private_key is None:            raise ValueError("not private key,func generate() should be call before this")        return rsa.decrypt(encrypts, self._private_key)    def long_to_bytes(self, value, endianness='big'):        # https://stackoverflow.com/questions/8730927/convert-python-long-int-to-fixed-size-byte-array        width = value.bit_length()        width += 8 - ((width % 8) or 8)        fmt = '%%0%dx' % (width // 4)        s = unhexlify(fmt % value)        if endianness == 'little':            # see http://stackoverflow.com/a/931095/309233            s = s[::-1]        return s
原创粉丝点击