美文网首页
rsa 加解密签名

rsa 加解密签名

作者: Canon_2020 | 来源:发表于2020-04-20 09:39 被阅读0次
    import Crypto.Cipher as Cipher
    import Crypto.Signature as Sign
    import Crypto.Hash as Hash
    from Crypto.PublicKey import RSA
    from Crypto.Cipher import PKCS1_v1_5 as PKCS1_v1_5_cipper
    from Crypto.Signature import PKCS1_v1_5 as PKCS1_v1_5_sign
    from Crypto.Hash import SHA1
    
    
    class Rsa:
        """
        RSA加解密签名类
        """
        def __int__(self, ciper_lib=PKCS1_v1_5_cipper, sign_lib=PKCS1_v1_5_sign, hash_lib=SHA1,
                    pub_file=None, pri_file=None, pub_skey=None, pri_skey=None, pub_key=None, pri_key=None,
                    reversed_size=11):
    
            # 加解密库
            self.ciper_lib = ciper_lib
            self.sign_lib = sign_lib
            self.hash_lib = hash_lib
    
            # 公钥密钥
            if pub_key:
                self.pub_key = pub_key
            elif pub_skey:
                self.pub_key = RSA.importKey(pub_skey)
            elif pub_file:
                self.pub_key = RSA.importKey(open(pub_file).read())
    
            if pri_key:
                self.pri_key = pri_key
            elif pri_skey:
                self.pri_key = RSA.importKey(pri_skey)
            elif pri_file:
                self.pri_key = RSA.importKey(open(pri_file).read())
    
            # 分块保留长度
            self.block_reversed_size = reversed_size
    
        # 根据 key 长度计算分块大小
        def get_block_size(self, rsa_key):
            try:
                # RSA仅支持限定长度内的数据的加解密,需要分块
                # 分块大小
                reserve_size = self.block_reversed_size
                key_size = rsa_key.size_in_bits()
                if (key_size % 8) != 0:
                    raise RuntimeError('RSA 密钥长度非法')
    
                # 密钥用来解密,解密不需要预留长度
                if rsa_key.has_private():
                    reserve_size = 0
    
                bs = int(key_size / 8) - reserve_size
            except Exception as err:
                print('计算加解密数据块大小出错', rsa_key, err)
            return bs
    
        # 返回块数据
        def block_data(self, data, rsa_key):
            bs = self.get_block_size(rsa_key)
            for i in range(0, len(data), bs):
                yield data[i:i + bs]
    
        # 加密
        def enc_bytes(self, data, key=None):
            text = b''
            try:
                rsa_key = self.pub_key
                if key:
                    rsa_key = key
    
                cipher = self.ciper_lib.new(rsa_key)
                for dat in self.block_data(data, rsa_key):
                    cur_text = cipher.encrypt(dat)
                    text += cur_text
            except Exception as err:
                print('RSA加密失败', data, err)
            return text
    
        # 解密
        def dec_bytes(self, data, key=None):
            text = b''
            try:
                rsa_key = self.pri_key
                if key:
                    rsa_key = key
    
                cipher = self.ciper_lib.new(rsa_key)
                for dat in self.block_data(data, rsa_key):
                    if type(self.ciper_lib) == Cipher.PKCS1_OAEP:
                        cur_text = cipher.decrypt(dat)
                    else:
                        cur_text = cipher.decrypt(dat, '解密异常')
                    text += cur_text
            except Exception as err:
                print('RSA解密失败', data, err)
            return text
    
        # RSA签名
        def sign_bytes(self, data, key=None):
            signature = ''
            try:
                rsa_key = self.pri_key
                if key:
                    rsa_key = key
    
                h = self.hash_lib.new(data)
                signature = self.sign_lib.new(rsa_key).sign(h)
            except Exception as err:
                print('RSA签名失败', '', err)
            return signature
    
        # RSA签名验证
        def sign_verify(self, data, sig, key=None):
            try:
                rsa_key = self.pub_key
                if key:
                    rsa_key = key
                h = self.hash_lib.new(data)
                self.sign_lib.new(rsa_key).verify(h, sig)
                ret = True
            except (ValueError, TypeError):
                ret = False
            return ret
    
    
    def main():
        # 加密
        # rsa_key = "MFwwDQYJKoZIhvcNAQEBBQADSwAwSAJBAK1XW+0ec7l7TfaNLaY8bBA5wTaLsLlpHmKqrHNEqDoHi8pQZb/r2XS6C4rk6RjyMwtzXoLodwx75cXte7oRQ2cCAwEAAQ=="
        # data = '{"userName": "test", "deviceId": "111", "password": "a665a45920422f9d417e4867efdc4fb8a04a1f3fff1fa07e998e86f7f7a27ae3", "token": ""}'
        # encrypt_val = Rsa.enc_bytes(data.encode("utf-8"), rsa_key)
        # print(encrypt_val)
    
        # 解密
        encrypt = "DzGwi82HBoFF9CVNhvyJiOErQTsXkzj3YxGw6EnqXU9PR2EaLshHRlwTZ43Gf0BlUd8MKH/GobFLZsGw/o4LRAHbIjEneA9Csxao2ewXZaEz+HLB9/nRAE2+T3WVngE9sE7kdItCSvQJA6Rsn08WF4z2+3qF2Sxt3MrRH6mYFcWSIjTTcnf+dmuz3PMZh6RLxL0VYKtqY0Urc1VZZSI72p5WoWgVjgu8kGvz5jFjZMliksq1GYQiQvI4o1L/iQxl"
        # encrypt = encrypt_val
        private_key = "MIIBVAIBADANBgkqhkiG9w0BAQEFAASCAT4wggE6AgEAAkEArVdb7R5zuXtN9o0tpjxsEDnBNouwuWkeYqqsc0SoOgeLylBlv+vZdLoLiuTpGPIzC3Neguh3DHvlxe17uhFDZwIDAQABAkANq0XkfPJDPiX3u0pOQZWD8gn6cymMdW2f+jV/IXrimHRdCGRrFKOQ2pPbGoYLP9AelHeXVsvmhL2xuVcq7BeBAiEA5+qKdT9WNkT9QbKC6Voa6GsmN84QEtuxq7QBDGu8MmUCIQC/V5ynafGkf+EDa+GLvo0E9av0MJDmThVP8RRqVuOb2wIhAKltGTXKzarb/8DtLuJXZ20ASm1eZzO/uC7eVB3E3zpZAiAgK8/oChUZ7nJby+i5QUmemtvVi9DhGCHXNhaTppZQXwIgVp3QcvfFeDeiD3wz8zcKdZtqpv9mW75iJOOYZSm6CO4="
        print(Rsa(pri_key=private_key).dec_bytes(encrypt))
    
    
    if __name__ == '__main__':
        main()
    
    
    #!/usr/local/python3
    # -*- coding: utf-8 -*-
    # @Date    : 2018-04-15 09:00:00
    # @Author  : Canon
    # @Link    : https://www.python.org
    # @Version : 3.6.1
    
    """
    pip install pycryptodome
    
    只适应 python 进行加密解密
    """
    
    import base64
    from Crypto.PublicKey import RSA
    from Crypto.Cipher import PKCS1_v1_5
    
    
    def rsa_encrypt(pub_key_str, msg, default_length=48):
        """
        RSA 加密, 分块加密
        单次加密串的长度最大为 (key_size/8)-11
        :param pub_key_str: RSA 公钥
        :param msg: 需要加密的字符串
        :param default_length: 单次加密的长度
        :return:
        """
        begin = "-----BEGIN -----\n"
        end = "\n-----END -----"
        msg = msg.encode('utf-8')
        length = len(msg)
        res = []
        try:
            # 公钥加密
            pubobj = PKCS1_v1_5.new(RSA.importKey(begin+pub_key_str+end))
            # 长度小于默认值时, 不用分块
            if length < default_length:
                return base64.b64encode(pubobj.encrypt(msg)).decode('utf-8')
            # 需要分块
            offset = 0
            while length - offset > 0:
                if length - offset > default_length:
                    res.append(pubobj.encrypt(msg[offset:offset+default_length]))
                else:
                    res.append(pubobj.encrypt(msg[offset:]))
                offset += default_length
        except Exception as err:
            print('RSA加密失败', err)
        byte_data = b''.join(res)
        return base64.b64encode(byte_data).decode('utf-8')
    
    
    def rsa_decrypt(priv_key_str, msg, default_length=64):
        """
        RSA 解密, 分块解密
        单次加密串的长度最大为 (key_size/8)-11
        :param priv_key_str: RSA 私钥
        :param msg: 需要解密的字符串
        :param default_length: 单次解密的长度
        :return:
        """
        begin = "-----BEGIN -----\n"
        end = "\n-----END -----"
        msg = base64.b64decode(msg)
        length = len(msg)
        res = []
        try:
            # 私钥解密
            priobj = PKCS1_v1_5.new(RSA.importKey(begin+priv_key_str+end))
            # 长度小于默认值时, 不用分块
            if length < default_length:
                return b''.join(priobj.decrypt(msg, b'comment')).decode('utf-8')
            # 需要分块
            offset = 0
            while length - offset > 0:
                if length - offset > default_length:
                    res.append(priobj.decrypt(msg[offset:offset+default_length], b'decrypt error'))
                else:
                    res.append(priobj.decrypt(msg[offset:], b'decrypt error'))
                offset += default_length
        except Exception as err:
            print('RSA解密失败', err)
        return b''.join(res).decode('utf-8')
    
    # 加密
    rsa_key = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAzWnCzXxfWVRsbVm1nDgHgGeWl38J6gCwNMSfEdXvC55xbFUZZU2iyUSIJWK9Tgbn3ODv6PxZjvY6Xw/n/tQpwfDp2en8WjtOiFoCgWrrb0TnIAov4GQ/4Ht7/dGUotmbEalRbE6yNYKnd5nsuXCCHhg71hFktOh89YfhMM8LTeh3Egk23/M/P9AVh9B/BmP7FtT4QVr588Puct42+89iENB11W216wDyLM+tPL8Qe1G1D/70fi6lqVjww23VxtXbJqq2Yb8VRT30dQMAf7mPuTGHtA8WtG1WdCYMR1BRTvoqFT3M7Y9eVs2070/CL66X01rCjWWRGIkbz4BdOY5TvwIDAQAB"
    data = '{"userName": "test", "deviceId": "111", "password": "a665a45920422f9d417e4867efdc4fb8a04a1f3fff1fa07e998e86f7f7a27ae3", "token": ""}'
    encrypt_val = rsa_encrypt(rsa_key, data)
    print(encrypt_val)
    
    # 解密
    # encrypt = "DzGwi82HBoFF9CVNhvyJiOErQTsXkzj3YxGw6EnqXU9PR2EaLshHRlwTZ43Gf0BlUd8MKH/GobFLZsGw/o4LRAHbIjEneA9Csxao2ewXZaEz+HLB9/nRAE2+T3WVngE9sE7kdItCSvQJA6Rsn08WF4z2+3qF2Sxt3MrRH6mYFcWSIjTTcnf+dmuz3PMZh6RLxL0VYKtqY0Urc1VZZSI72p5WoWgVjgu8kGvz5jFjZMliksq1GYQiQvI4o1L/iQxl"
    encrypt = encrypt_val
    pri_key = "MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQDNacLNfF9ZVGxtWbWcOAeAZ5aXfwnqALA0xJ8R1e8LnnFsVRllTaLJRIglYr1OBufc4O/o/FmO9jpfD+f+1CnB8OnZ6fxaO06IWgKBautvROcgCi/gZD/ge3v90ZSi2ZsRqVFsTrI1gqd3mey5cIIeGDvWEWS06Hz1h+EwzwtN6HcSCTbf8z8/0BWH0H8GY/sW1PhBWvnzw+5y3jb7z2IQ0HXVbbXrAPIsz608vxB7UbUP/vR+LqWpWPDDbdXG1dsmqrZhvxVFPfR1AwB/uY+5MYe0Dxa0bVZ0JgxHUFFO+ioVPcztj15WzbTvT8IvrpfTWsKNZZEYiRvPgF05jlO/AgMBAAECggEADrkxctwi03rXKMFg4JkthHkoVKSQ99pjxux/AF7Guxz4wUyaPOYjMGz+mztoGUMqdG0VFSydWL9ycKTpupzHf3S+tlVstqUAnIpjGpao2HlmXagNRXa6E2OWgBt5H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+a6HXiv/3jrNh2ca+eSFAp"
    print(rsa_decrypt(pri_key, encrypt))
    
    
    #!/usr/local/python3
    # -*- coding: utf-8 -*-
    # @Date    : 2018-04-15 09:00:00
    # @Author  : Canon
    # @Link    : https://www.python.org
    # @Version : 3.6.1
    
    """
    pip install pycryptodome
    
    适用于 python 与 java 进行加密解密
    """
    
    import base64
    from Crypto.Hash import SHA256
    from Crypto.PublicKey import RSA
    from Crypto.Cipher import PKCS1_OAEP
    from Crypto.Cipher import PKCS1_v1_5
    import Crypto.Cipher as Cipher
    
    
    def get_block_size(key_obj):
        # 根据 key 长度计算分块大小
        block_size = 0
        try:
            # RSA 仅支持限定长度内的数据的加解密,需要分块
            # 分块大小
            reserve_size = 63
            # 获取密钥的字节长度
            key_size = key_obj.size_in_bits()
            if (key_size % 8) != 0:
                raise RuntimeError('RSA 密钥长度非法')
            # 密钥用来解密,解密不需要预留长度
            if key_obj.has_private():
                reserve_size = 0
            block_size = int(key_size / 8) - reserve_size
        except Exception as err:
            print('计算加解密数据块大小出错', key_obj, err)
        return block_size
    
    
    def block_data(data, key_obj):
        # 返回块数据
        block_size = get_block_size(key_obj)
        for i in range(0, len(data), block_size):
            yield data[i:i + block_size]
    
    
    def rsa_decrypt(priv_key_str, msg):
        text = b''
        begin = "-----BEGIN -----\n"
        end = "\n-----END -----"
        msg = base64.b64decode(msg)
        # 私钥解密
        try:
            key_obj = RSA.importKey(begin+priv_key_str+end)
            cipher = PKCS1_v1_5.new(key_obj)
            for dat in block_data(msg, key_obj):
                if type(PKCS1_v1_5) == Cipher.PKCS1_OAEP:
                    cur_text = cipher.decrypt(dat)
                else:
                    cur_text = cipher.decrypt(dat, '解密异常')
                text += cur_text
        except Exception as err:
            print('RSA解密失败', msg, err)
        return text.decode('utf-8')
    
    
    def rsa_encrypt(pub_key_str, msg):
        text = b''
        begin = "-----BEGIN -----\n"
        end = "\n-----END -----"
        msg = msg.encode('utf-8')
        # 公钥加密
        try:
            key_obj = RSA.importKey(begin+pub_key_str+end)
            cipher = PKCS1_v1_5.new(key_obj)
            for dat in block_data(msg, key_obj):
                cur_text = cipher.encrypt(dat)
                text += cur_text
        except Exception as err:
            print('RSA加密失败', msg, err)
        return base64.b64encode(text).decode('utf-8')
    
    
    # 加密
    rsa_key = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAzWnCzXxfWVRsbVm1nDgHgGeWl38J6gCwNMSfEdXvC55xbFUZZU2iyUSIJWK9Tgbn3ODv6PxZjvY6Xw/n/tQpwfDp2en8WjtOiFoCgWrrb0TnIAov4GQ/4Ht7/dGUotmbEalRbE6yNYKnd5nsuXCCHhg71hFktOh89YfhMM8LTeh3Egk23/M/P9AVh9B/BmP7FtT4QVr588Puct42+89iENB11W216wDyLM+tPL8Qe1G1D/70fi6lqVjww23VxtXbJqq2Yb8VRT30dQMAf7mPuTGHtA8WtG1WdCYMR1BRTvoqFT3M7Y9eVs2070/CL66X01rCjWWRGIkbz4BdOY5TvwIDAQAB"
    data = '{"userName": "test", "deviceId": "111", "password": "123456", "token": ""}'
    encrypt_val = rsa_encrypt(rsa_key, data)
    print(encrypt_val)
    
    # 解密
    data = "KSUtQlCXGanb/SDD3rQF0jw9qJb8OvYO8XimC0ZAKaVck5UavSSsSQeoGJxg/lkvi9Cg4vXnFvuBr64Cyl3A+g=="
    # data = encrypt_val
    pri_key = "MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQDNacLNfF9ZVGxtWbWcOAeAZ5aXfwnqALA0xJ8R1e8LnnFsVRllTaLJRIglYr1OBufc4O/o/FmO9jpfD+f+1CnB8OnZ6fxaO06IWgKBautvROcgCi/gZD/ge3v90ZSi2ZsRqVFsTrI1gqd3mey5cIIeGDvWEWS06Hz1h+EwzwtN6HcSCTbf8z8/0BWH0H8GY/sW1PhBWvnzw+5y3jb7z2IQ0HXVbbXrAPIsz608vxB7UbUP/vR+LqWpWPDDbdXG1dsmqrZhvxVFPfR1AwB/uY+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MyN9NJ8KikxTVuuompRQ9WUk9gF4jFGhUGiWlCbNEwKBgF/ywJowLGzqmPLYA/0xHB9DUnX4lzaIZrCIKcoVVbNOmbHP9DVcgCv4+xJ1w7u/GZQ3E2q+oKdrrvlf1rNlxahCFetWPVpAN1evw8UxAenxtBDUCGf/fc/hXItMTXEPTbdLitqx4WjRG+CA5FRTWl+a6HXiv/3jrNh2ca+eSFAp"
    print(rsa_decrypt(pri_key, data))
    
    

    相关文章

      网友评论

          本文标题:rsa 加解密签名

          本文链接:https://www.haomeiwen.com/subject/vwqtwctx.html