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('\n', '').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('\0')

 


二、非對稱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')

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM