zoukankan      html  css  js  c++  java
  • 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')

     

  • 相关阅读:
    模拟循环单击事件实现layout中间panel全屏
    easyui tree自定义属性用法
    jquery给动态添加的dom元素绑定事件
    基于easyui fom分组插件
    ubuntu adb 安装
    vim状态保存跟恢复
    ubuntu-删除内核
    u盘安装14.04ubuntu系统
    findFocus-获得拥有焦点的控件
    xml中控件调用构造方法
  • 原文地址:https://www.cnblogs.com/zhangxingcomeon/p/14678705.html
Copyright © 2011-2022 走看看