• Python---RSA非对称加解密、AES对称加解密排坑:ciphertext with incorrect length和 rsaIV is not meaningful for the ECB mode


    引:

      最近做自定义TCP数据包通信,使用加解密库crypto,遇到的小问题排坑如下:


    写在前面:
    若要是使用crypto库,linux下需要按照如下包名安装

    pip install pycryptodome

    一、对称AES

    1、Python aes加密IV is not meaningful for the ECB mode。。。
      (加不加IV)EBC不加Ⅳ, CBC模式加Ⅳ,所以EBC模式不给第三个参数,CBC模式可以加第三个参数


    2、Object type class 'str' cannot be passed to C code。。。     
      key ,vi,传入endtryde的data,三个数据都要变为bytes, (encode)
      KEY  VI  传入的data,均要为bytes,实践中注意KEY也需要encode

    附: # 对称加密AES 加密

    def aes_encrypt(data: str, key: bytes):
        cryptor = AES.new(key.encode('utf-8'), AES.MODE_ECB)
        # mode = AES.MODE_CBC
        # cryptor = AES.new(key.encode('utf-8'), mode, b'0000000000000000')
    
        ciphertext = str(base64.b64encode(cryptor.encrypt(add_to_16(data))), encoding='utf-8').replace('
    ', '').encode('utf-8')
        return ciphertext

      

      # 对称加密AES 解密:

    # 对称加密AES 解密
    def aes_decrypt(data: bytes, key: bytes) -> str:
        cryptor = AES.new(key.encode('utf-8'), AES.MODE_ECB)
    
        plain_text = cryptor.decrypt(base64.b64decode(data))
        return plain_text.decode('utf-8').rstrip('')


    二、非对称RSA:
    1、ciphertext with incorrect length rsa   
    若已经用encode decode64加解密过,则较长的数据已经变为了128位,无需再分段解密。
    且,需看加密端要求传入的公钥N 和E  (或约定的P、Q等参数),是否为16进制,若两边进制不匹配,会导致解密时无法成功,报错亦如上。会报长度问题和解密失败

    附:# 非对称RSA加密
    # 非对称RSA加密
    def rsa_encrypt(data: bytes, public_key):
        pub_key = RSA.importKey(public_key)
        cipher = PKCS1_cipher.new(pub_key)
        rsa_text = base64.b64encode(cipher.encrypt(data))
        return rsa_text
    # 非对称RSA解密
    # 非对称RSA解密
    def rsa_decrypt(data: bytes, private_key):
        # 私钥解密
        pri_key = RSA.importKey(private_key)
        cipher = PKCS1_cipher.new(pri_key)
        back_text = cipher.decrypt(base64.b64decode(data), 0)
        print(back_text.decode('utf-8'))
        return back_text.decode('utf-8')

     

  • 相关阅读:
    android 读中文文本文件
    Android-将RGB彩色图转换为灰度图
    andriod 获取电池的信息
    android studio快捷键
    2016年深圳市服务业占GDP比重首次突破六成
    三分钟看完北京城市(含京津冀)【总体规划2016-2050】
    CentOS 7.3.1611系统安装配置图解教程
    为何北美华裔二代三代之后长相就跟中国人不一样了?
    别看不起印度,印度比中国好多了?
    东南亚十大城市
  • 原文地址:https://www.cnblogs.com/zhangxingcomeon/p/14678705.html
Copyright © 2020-2023  润新知