fleur_de_lris 2023-07-10 20:05 采纳率: 0%
浏览 37
已结题

AES/CBC/Nopadding,Hex编码怎么实现啊

需要使用python实现一个AES加密,AES加密,CBC模式,Nopadding填充模式,HEX编码
我自己使用pycryptodome仅能实现b64和UTF-8编码,有没有人帮忙看看啊
希望实现的是这样一个效果↓

img

  • 写回答

10条回答 默认 最新

  • threenewbee 2023-07-10 20:08
    关注
    获得1.80元问题酬金
    from Crypto.Cipher import AES
    import binascii
    
    def aes_encrypt(key, iv, plaintext):
        cipher = AES.new(key, AES.MODE_CBC, iv)
        ciphertext = cipher.encrypt(plaintext)
        return ciphertext
    
    def aes_decrypt(key, iv, ciphertext):
        cipher = AES.new(key, AES.MODE_CBC, iv)
        plaintext = cipher.decrypt(ciphertext)
        return plaintext
    
    def add_padding(plaintext):
        padding_length = AES.block_size - (len(plaintext) % AES.block_size)
        padded_plaintext = plaintext + bytes([padding_length] * padding_length)
        return padded_plaintext
    
    def remove_padding(padded_plaintext):
        padding_length = padded_plaintext[-1]
        plaintext = padded_plaintext[:-padding_length]
        return plaintext
    
    def encrypt_text(key, iv, plaintext):
        padded_plaintext = add_padding(plaintext)
        ciphertext = aes_encrypt(key, iv, padded_plaintext)
        return binascii.hexlify(ciphertext).decode()
    
    def decrypt_text(key, iv, ciphertext):
        ciphertext = binascii.unhexlify(ciphertext)
        padded_plaintext = aes_decrypt(key, iv, ciphertext)
        plaintext = remove_padding(padded_plaintext)
        return plaintext.decode()
    
    key = b'0123456789abcdef'  # 16字节的密钥
    iv = b'abcdef9876543210'  # 16字节的初始向量
    plaintext = b'This is a secret message'
    
    encrypted_text = encrypt_text(key, iv, plaintext)
    print("加密后的文本:", encrypted_text)
    
    decrypted_text = decrypt_text(key, iv, encrypted_text)
    print("解密后的文本:", decrypted_text)
    
    评论

报告相同问题?

问题事件

  • 系统已结题 7月18日
  • 创建了问题 7月10日