zoukankan      html  css  js  c++  java
  • python 实现RSA公钥加密,私钥解密

    from Crypto.PublicKey import RSA
    from Crypto.Cipher import PKCS1_v1_5 as Cipher_pkcs1_v1_5
    from Crypto.Signature import PKCS1_v1_5 as Signature_pkcs1_v1_5
    import base64
    
    # 私钥
    private_key = '''-----BEGIN RSA PRIVATE KEY-----
    5353dfggd
    -----END RSA PRIVATE KEY-----
    '''
    
    # 公钥
    public_key = '''-----BEGIN PUBLIC KEY-----
    hfgghftetet
    -----END PUBLIC KEY-----'''
    def rsa_encrypt(message):
        """校验RSA加密 使用公钥进行加密"""
        cipher = Cipher_pkcs1_v1_5.new(RSA.importKey(public_key))
        cipher_text = base64.b64encode(cipher.encrypt(message.encode())).decode()
        return cipher_text
    
    
    def rsa_decrypt(text):
        """校验RSA加密 使用私钥进行解密"""
        cipher = Cipher_pkcs1_v1_5.new(RSA.importKey(private_key))
        retval = cipher.decrypt(base64.b64decode(text), 'ERROR').decode('utf-8')
        return retval

    注意:

    从后台获取到的pubkey直接入参,会出现报错:ValueError:RSA key format is not supported

     

    正确应该如下方式

    def rsa_encrypt(password:str,publickey):
        """校验RSA加密 使用公钥进行加密"""
        public_key = '-----BEGIN PUBLIC KEY-----
    '+ publickey +'
    -----END PUBLIC KEY-----'
        cipher = Cipher_pkcs1_v1_5.new(RSA.importKey(public_key))
        cipher_text = base64.b64encode(cipher.encrypt(password.encode())).decode()
        return cipher_text
  • 相关阅读:
    joins and includes
    学习库
    HTML5 画图--文字
    http://qiye.qianzhan.com/ 企业查询宝
    js 获取input选择的图片的信息
    input:file属性
    CSS 箭头
    颜色
    CSS 点击图片替换样式
    图片转base64
  • 原文地址:https://www.cnblogs.com/cherylgi/p/13863370.html
Copyright © 2011-2022 走看看