AES 256 加密 -> 更改初始化向量会在不知道密钥的情况下稍微更改解密的消息

2023-12-20

我通过 AES 加密/解密示例进行了以下观察,这对我来说非常违反直觉。

我尝试在 CBC 模式下使用 AES 加密和解密一个简单的有效负载。 我的理解是,根据这个答案,初始化向量不必是秘密的:https://security.stackexchange.com/a/17046 https://security.stackexchange.com/a/17046。 在我看到的大多数示例中,初始化向量是加密有效负载的非随机部分。

但通过更改初始化向量,我能够在加密期间更改消息。

例如,请参阅我复制并改编自的这个 python 示例https://stackoverflow.com/a/21928790/669561 https://stackoverflow.com/a/21928790/669561。 我设置了硬编码iv for encrypt我稍微调整了一下iv for decrypt。 通过此更改,我可以更改消息"hello world" to "hello!world".

import base64
import hashlib

from Crypto.Cipher import AES


class AESCipher(object):

    def __init__(self, key):
        self.bs = AES.block_size
        self.key = hashlib.sha256(key.encode()).digest()

    def encrypt(self, raw):
        raw = self._pad(raw)
        #iv = Random.new().read(AES.block_size)
        #                    | here is the difference to the iv from decrypt
        iv = b'\xe2\xe0l3H\xc42*N\xb0\x152\x98\x9cBh'
        cipher = AES.new(self.key, AES.MODE_CBC, iv)
        code = cipher.encrypt((raw.encode()))
        return base64.b64encode(iv + code)

    def decrypt(self, enc):
        enc = base64.b64decode(enc)
        #iv = enc[:AES.block_size]
        #                    | here is the difference to the iv from encrypt
        iv = b'\xe2\xe0l3H\xc52*N\xb0\x152\x98\x9cBh'
        cipher = AES.new(self.key, AES.MODE_CBC, iv)
        return self._unpad(cipher.decrypt(enc[AES.block_size:])).decode('utf-8')

    def _pad(self, s):
        return s + (self.bs - len(s) % self.bs) * chr(self.bs - len(s) % self.bs)

    @staticmethod
    def _unpad(s):
        return s[:-ord(s[len(s) - 1:])]


if __name__ == '__main__':
    text = "hello world"
    print(text) # -> "hello world"
    aes = AESCipher("F56hnXWaUWMh6ThQZ5l3mBg9zHFx6vQg")
    payload = aes.encrypt(text)
    print(aes.decrypt(payload)) # -> "hello!world"

这个简单例子的结果对我来说完全违反直觉。 看来中间有人可以拿走有效负载,改变iv稍微改变一下,甚至在不知道秘密密钥的情况下改变解密的消息!

根据我的理解,仅通过更改初始化向量来更改加密消息的内容应该不是那么容易的。更改初始化向量应该会导致完全不同的结果!

难道我的想法有问题吗?

你能帮我澄清一下我的误解吗?


AES 和一般的分组密码通常只提供“保密性”——它们不保证完整性。

您的观察是正确的 - 更改 IV 确实会更改解密后生成的明文。您还会注意到,在我的情况下,更改密文本身的字节仍然可以在 AES-CBC 下成功解密(尽管是不同的明文)。

您想要的是一种方法来验证自初始加密操作发生以来 IV 和密文没有被修改。

实现这一目标的两种最常见的方法是:

  • MAC(HMAC 很常见)
  • 首选经过身份验证的加密模式,例如 GCM。

你可能会发现这是 Python 中 AES-GCM 加密的示例 https://github.com/luke-park/SecureCompatibleEncryptionExamples/blob/master/Python/SCEE.py有用。我已将其包含在下面:

from Crypto.Hash import SHA256, HMAC
from Crypto.Cipher import AES
from Crypto.Random import get_random_bytes
from Crypto.Protocol.KDF import PBKDF2
import base64

ALGORITHM_NONCE_SIZE = 12
ALGORITHM_TAG_SIZE = 16
ALGORITHM_KEY_SIZE = 16
PBKDF2_SALT_SIZE = 16
PBKDF2_ITERATIONS = 32767
PBKDF2_LAMBDA = lambda x, y: HMAC.new(x, y, SHA256).digest()

def encryptString(plaintext, password):
    # Generate a 128-bit salt using a CSPRNG.
    salt = get_random_bytes(PBKDF2_SALT_SIZE)

    # Derive a key using PBKDF2.
    key = PBKDF2(password, salt, ALGORITHM_KEY_SIZE, PBKDF2_ITERATIONS, PBKDF2_LAMBDA)

    # Encrypt and prepend salt.
    ciphertextAndNonce = encrypt(plaintext.encode('utf-8'), key)
    ciphertextAndNonceAndSalt = salt + ciphertextAndNonce

    # Return as base64 string.
    return base64.b64encode(ciphertextAndNonceAndSalt)

def decryptString(base64CiphertextAndNonceAndSalt, password):
    # Decode the base64.
    ciphertextAndNonceAndSalt = base64.b64decode(base64CiphertextAndNonceAndSalt)

    # Get the salt and ciphertextAndNonce.
    salt = ciphertextAndNonceAndSalt[:PBKDF2_SALT_SIZE]
    ciphertextAndNonce = ciphertextAndNonceAndSalt[PBKDF2_SALT_SIZE:]

    # Derive the key using PBKDF2.
    key = PBKDF2(password, salt, ALGORITHM_KEY_SIZE, PBKDF2_ITERATIONS, PBKDF2_LAMBDA)

    # Decrypt and return result.
    plaintext = decrypt(ciphertextAndNonce, key)

    return plaintext.decode('utf-8')

def encrypt(plaintext, key):
    # Generate a 96-bit nonce using a CSPRNG.
    nonce = get_random_bytes(ALGORITHM_NONCE_SIZE)

    # Create the cipher.
    cipher = AES.new(key, AES.MODE_GCM, nonce)

    # Encrypt and prepend nonce.
    ciphertext, tag = cipher.encrypt_and_digest(plaintext)
    ciphertextAndNonce = nonce + ciphertext + tag

    return ciphertextAndNonce

def decrypt(ciphertextAndNonce, key):
    # Get the nonce, ciphertext and tag.
    nonce = ciphertextAndNonce[:ALGORITHM_NONCE_SIZE]
    ciphertext = ciphertextAndNonce[ALGORITHM_NONCE_SIZE:len(ciphertextAndNonce) - ALGORITHM_TAG_SIZE]
    tag = ciphertextAndNonce[len(ciphertextAndNonce) - ALGORITHM_TAG_SIZE:]

    # Create the cipher.
    cipher = AES.new(key, AES.MODE_GCM, nonce)

    # Decrypt and return result.
    plaintext = cipher.decrypt_and_verify(ciphertext, tag)

    return plaintext
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

AES 256 加密 -> 更改初始化向量会在不知道密钥的情况下稍微更改解密的消息 的相关文章

  • CryptoJS 使用密码加密 AES,但 PHP 解密需要密钥

    我在用CryptoJS https code google com p crypto js AES加密字符串 function doHash msg msg String msg var passphrase aggourakia var
  • Python 切片对象和 __getitem__

    python 中是否有内部的东西来处理传递给的参数 getitem 不同 并自动转换start stop step构造成切片 这是我的意思的演示 class ExampleClass object def getitem self args
  • 在python中将数据库表写入文件的最快方法

    我正在尝试从数据库中提取大量数据并将其写入 csv 文件 我正在尝试找出最快的方法来做到这一点 我发现在 fetchall 的结果上运行 writerows 比下面的代码慢 40 with open filename a as f writ
  • Ruby openssl 文档 [关闭]

    Closed 这个问题正在寻求书籍 工具 软件库等的推荐 不满足堆栈溢出指南 help closed questions 目前不接受答案 有没有 Ruby 的在线文档openssl图书馆 我能找到的只是博客文章和第三方文章 而 rdoc 本
  • 是否可以从 Julia 调用 Python 函数并返回其结果?

    我正在使用 Python 从网络上抓取数据 我想使用这些数据在 Julia 中运行计算 是否可以在 Julia 中调用该函数并返回其结果 或者我最好直接导出到 CSV 并以这种方式加载数据 绝对地 看PyCall jl https gith
  • Matplotlib:如何有效地将大量线段着色为独立渐变

    Python 绘图库 如何有效地将大量线段着色为独立渐变 已经 阅读this https stackoverflow com questions 8500700 how to plot a gradient color line in ma
  • 如何通过 python 多处理利用所有核心

    我一直在摆弄Python的multiprocessing现在已经使用了一个多小时的功能 尝试使用并行化相当复杂的图形遍历函数multiprocessing Process and multiprocessing Manager import
  • 如何过滤 Pandas GroupBy 对象并获取 GroupBy 对象?

    当对 Pandas groupby 操作的结果执行过滤时 它返回一个数据帧 但假设我想执行进一步的分组计算 我必须再次调用 groupby 这似乎有点绕 有更惯用的方法吗 EDIT 为了说明我在说什么 我们无耻地从 Pandas 文档中窃取
  • 类型错误:需要二进制或 unicode 字符串,得到 618.0

    I ve been trying to implement this ML Linear Model into my dataset https www tensorflow org tutorials estimator linear L
  • Python Tkinter 模块不显示输出

    我正在尝试学习 Python 并尝试使用 Python 中的 GUI 并遇到了这个 Tkinter 模块 我的代码运行 但运行时窗口没有出现 我的代码如下 from Tkinter import to create a root windo
  • Arcpy 模数在 Pycharm 中不显示

    如何将 Arcpy 集成到 Pycharm 中 我尝试通过导入模块但它没有显示 我确实知道该模块仅适用于 2 x python arcpy 在 PyPi Python 包索引 上不可用 因此无法通过 pip 安装 要使用 arcpy 您需要
  • Python HMAC:类型错误:字符映射必须返回整数、None 或 unicode

    我在使用 HMAC 时遇到了一个小问题 运行这段代码时 signature hmac new key secret key msg string to sign digestmod sha1 我收到一个奇怪的错误 File usr loca
  • Paste.httpserver 并通过 HTTP/1.1 Keep-alive 减慢速度;使用 httperf 和 ab 进行测试

    我有一个基于paste httpserver 的Web 服务器作为HTTP 和WSGI 之间的适配器 当我使用 httperf 进行性能测量时 如果每次使用 num conn 启动一个新请求 我每秒可以执行超过 1 000 个请求 如果我使
  • 使用 for 循环创建一系列元组

    我已经搜索过 但找不到答案 尽管我确信它已经存在了 我对 python 很陌生 但我以前用其他语言做过这种事情 我正在以行形式读取数据文件 我想将每行数据存储在它自己的元组中 以便在 for 循环之外访问 tup i inLine wher
  • pandas 相当于 np.where

    np where具有向量化 if else 的语义 类似于 Apache Spark 的when otherwise数据帧方法 我知道我可以使用np where on pandas Series but pandas通常定义自己的 API
  • 如何查找或安装适用于 Python 的主题 tkinter ttk

    过去 3 个月我一直在制作一个机器人 仅用代码就可以完美运行 现在我的下一个目标是为它制作一个 GUI 但是我发现了一些障碍 主要的一个是能够看起来不像一个 30 年前的程序 我使用的是 Windows 7 我仅使用 Python 3 3
  • rpy2 无法加载外部库

    希望有人能帮忙解决这个问题 R版本 2 14 1rpy2版本 2 2 5蟒蛇版本 2 7 3 一直在尝试在 python 脚本中使用 rpy2 加载 R venneuler 包 该包以 rJava 作为依赖项 venneuler 和 rJa
  • Mysql加密/存储敏感数据,

    我的 PHP 网站有以下内容 启用 SSL 饼干 session set cookie params cookieParams lifetime cookieParams path cookieParams domain secure ht
  • 将 Keras 集成到 SKLearn 管道?

    我有一个 sklearn 管道 对异构数据类型 布尔 分类 数字 文本 执行特征工程 并想尝试使用神经网络作为我的学习算法来拟合模型 我遇到了输入数据形状的一些问题 我想知道我想做的事情是否可能 或者我是否应该尝试不同的方法 我尝试了几种不
  • 如何使用 python 定位和读取 Data Matrix 代码

    我正在尝试读取微管底部的数据矩阵条形码 我试过libdmtx http libdmtx sourceforge net 它有 python 绑定 当矩阵的点是方形时工作得相当好 但当矩阵的点是圆形时工作得更糟 如下所示 另一个复杂问题是在某

随机推荐