예제 #1
0
def aes_cbc_dec(aesKey, bsEncMsg, bsMacMsg):
    '''
    AuthenticatedEncryption - Check mac then decrypt given encrypted message.
    '''
    ### Prepare for mac
    sha256 = SHA256()
    hmac = HMAC(aesKey, sha256, default_backend())
    ### do mac
    hmac.update(bsEncMsg)
    macMsg = hmac.finalize()
    if (macMsg != bsMacMsg):
        raise Exception("ERRR:AEDecrypt:Mismatch, skipping")
        return None
    ### Prepare for decryption
    blockLen = 16
    iv = os.urandom(blockLen)
    aes = AES(aesKey)
    cbc = CBC(iv)
    aesCbc = Cipher(aes, cbc, default_backend())
    aesCbcDec = aesCbc.decryptor()
    ### do decrypt
    decMsg = aesCbcDec.update(bsEncMsg)
    decFina = aesCbcDec.finalize()
    decMsg = decMsg + decFina
    # do pkcs7 depadding
    unpad = PKCS7(blockLen * 8).unpadder()
    decMsg = unpad.update(decMsg)
    decMsg += unpad.finalize()
    # Discard the initial random block, as corresponding enc and this dec uses
    # non communicated random iv and inturn discardable random 0th block
    decMsg = decMsg[blockLen:]
    return decMsg
예제 #2
0
 def aes_decrypt(data, iv, key):
     cipher = Cipher(AES(key), CBC(iv), default_backend())
     decryptor = cipher.decryptor()
     plain_text = decryptor.update(data) + decryptor.finalize()
     padding = plain_text[len(plain_text) - 1]
     return plain_text[:len(plain_text) - padding]