简体   繁体   English

在PyCrypto AES MODE_CTR中包括随机数和块数

[英]Include nonce and block count in PyCrypto AES MODE_CTR

Some background information, you can skip this part for the actual question 一些背景信息,您可以跳过此部分以了解实际问题

this is my third question about this topic here at stackoverflow. 这是我在stackoverflow上关于此主题的第三个问题。 To be complete, these are the other questions AES with crypt-js and PyCrypto and Match AES de/encryption in python and javascript . 完整地说,这是AES与crypt-js和PyCrypto的其他问题,以及 python和javascript中的AES解密/匹配 Unfortunately my last attempt got two downvots for the original question. 不幸的是,我对原始问题的最后一次尝试有两次失败。 The problem was, even I did not know what my real question was . 问题是,即使我不知道我真正的问题是什么 I just dug around to find the real question I was looking for. 我只是四处寻找真正的问题。 With the feedback in the comments, and reading some additional information, I updated my question. 有了评论中的反馈,并阅读了一些其他信息,我更新了我的问题。 I excavate the right question, I think. 我认为,我提出了正确的问题。 But my problem didn't get any more views after my updates. 但是我的问题在更新后没有得到更多的视图。 So I really hope, that this question is now more clear and understandable - even I know what my Problem is now :D 所以我真的希望,这个问题现在更加清晰和可以理解-即使我知道我的问题是什么:D
Thank you all for making stackoverflow to this cool community - I often found here solutions for my problems. 谢谢大家为这个很酷的社区提供stackoverflow-我经常在这里找到我的问题的解决方案。 Please keep giving feedback to bad questions, so they can be improved and updated, which increases this huge knowledge and solutions database. 请继续提供对不良问题的反馈,以便对其进行改进和更新,从而增加了庞大的知识和解决方案数据库。 And feel free to correct my english grammar and spelling. 并随时纠正我的英语语法和拼写。

The Problem 问题

AES in Javascript Javascript中的AES

I have an encrypted String which I can decrypt with this this Javascript Implementation of AES 256 CTR Mode 我有一个加密的字符串,可以使用此Java AES 256 CTR模式的实现来解密

password = "myPassphrase"
ciphertext = "bQJdJ1F2Y0+uILADqEv+/SCDV1jAb7jwUBWk"
origtext = Aes.Ctr.decrypt(ciphertext, password, 256);
alert(origtext)

This decrypts my string and the alert box with This is a test Text pops up. 这将解密我的字符串,并弹出“ This is a test Text的警告框。

AES with PyCrypto 带有PyCrypto的AES

Now I want to decrypt this string with python and PyCrypto 现在我想用python和PyCrypto解密此字符串

password = 'myPassphrase'
ciphertext = "bQJdJ1F2Y0+uILADqEv+/SCDV1jAb7jwUBWk"
ctr = Counter.new(nbits=128)
encryptor = AES.new(key, AES.MODE_CTR, counter=ctr)
origtext = encryptor.decrypt(base64.b64decode(ciphertext))
print origtext

This code does not run. 此代码无法运行。 I get an ValueError: AES key must be either 16, 24, or 32 bytes long . 我收到ValueError: AES key must be either 16, 24, or 32 bytes long When I recognized, that I have to do more in PyCrypto then just call a decrypt method, I started to investigate end try to figure out what I have to do. 当我意识到必须在PyCrypto中做更多的事情之后才调用解密方法,我开始研究最终尝试以弄清楚我必须做的事情。

Investigation 调查中

The basic things I figured out first, were: 我首先想到的基本内容是:

  • AES 256 Bit (?). AES 256位(?)。 But AES standard is 128 bit. 但是AES标准是128位。 Does increasing the passphrase to 32 Byte is enough? 将密码短语增加到32字节是否足够?
  • Counter Mode. 计数器模式。 Easily to set in PyCrypto with AES.MODE_CTR. 可以使用AES.MODE_CTR在PyCrypto中轻松设置。 But I have to specify a counter() Method. 但是我必须指定一个counter()方法。 So I used the basic binary Counter provided by PyCrypto . 因此,我使用了PyCrypto提供基本二进制计数器 Is this compatible with the Javascript Implementation? 这与Javascript实现兼容吗? I can't figure out what they are doing. 我不知道他们在做什么。
  • The string is base64 encoded. 该字符串是base64编码的。 Not a big problem. 没什么大问题。
  • Padding in general. 填充一般。 Both passphrase and the encrypted string. 密码短语和加密的字符串。

For the passphrase they do this: 对于密码短语,他们这样做:

for (var i=0; i<nBytes; i++) {
    pwBytes[i] = isNaN(password.charCodeAt(i)) ? 0 : password.charCodeAt(i);
}

Then I did this in python 然后我在python中做到了

l = 32
key = key + (chr(0)*(l-len(key)%l))

But this did not help. 但这并没有帮助。 I still get a weird string ? A???B??d9= ,?h????' 我仍然得到一个奇怪的字符串? A???B??d9= ,?h????' ? A???B??d9= ,?h????' with the following code 用下面的代码

l = 32
key = 'myPassphrase'
key = key + (chr(0)*(l-len(key)%l))
ciphertext = "bQJdJ1F2Y0+uILADqEv+/SCDV1jAb7jwUBWk"
ctr = Counter.new(nbits=128)
encryptor = AES.new(key, AES.MODE_CTR, counter=ctr)
origtext = encryptor.decrypt(base64.b64decode(ciphertext))
print origtext

Then I read more about the Javascript Implementation and it says 然后,我阅读了有关Javascript实现的更多信息,并说

[...] In this implementation, the initial block holds the nonce in the first 8 bytes, and the block count in the second 8 bytes. [...]在此实现中,初始块在前8个字节中保存随机数,而块的计数在后8个字节中保存。 [...] [...]

I think this could be the key to the solution. 我认为这可能是解决方案的关键。 So I tested what happens when I encrypt an empty string in Javascript: 所以我测试了用Java加密空字符串时会发生什么:

origtext = ""
var ciphertext =Aes.Ctr.encrypt(origtext, password, 256);
alert(ciphertext)

The alert box shows /gEKb+N3Y08= (12 characters). 警报框显示/gEKb+N3Y08= (12个字符)。 But why 12? 但是为什么12? Shouldn't it be 8+8 = 16Bytes? 它不应该是8 + 8 = 16Bytes吗? Well anyway, I tried a bruteforce method on the python decryption by testing the decryption with for i in xrange(0,20): and ciphertext[i:] or base64.b64decode(ciphertext)[i:] . 好吧,无论如何,我通过for i in xrange(0,20):ciphertext[i:]base64.b64decode(ciphertext)[i:]中用for i in xrange(0,20):解密测试,对python解密尝试了蛮力方法。 I know this is a very embarrassing try, but I got more and more desperate. 我知道这是一个非常令人尴尬的尝试,但是我越来越绝望了。 And it didn't work either. 而且它也不起作用。

The future prospects are also to implement the encryption in the same way. 未来的前景也将以相同的方式实现加密。

additional information 附加信息

The encrypted string was not originally encrypted with this Javascript implementation , It's from another source. 加密的字符串最初并未使用此Javascript实现进行加密,它来自另一个来源。 I just recognized, that the Javascript code does the right thing. 我刚刚意识到,JavaScript代码可以正确地执行操作。 So I affirm that this kind of implementation is something like a "standard" . 因此,我肯定这种实现类似于“标准”

The question 问题

What can I do, that the encryption and decryption from a string with PyCrypto is the same like in the Javascript implementation, so that I can exchange data between Javascript and Python? 我该怎么做,用PyCrypto从字符串进行加密和解密与在Javascript实现中一样,以便可以在Javascript和Python之间交换数据? I also would switch to another crypto library in python, if you can suggest another one. 如果您可以建议另一个库,我也将切换到python中的另一个加密库。 Furthermore I'm happy with any kind of tips and feedback. 此外,我对任何提示和反馈感到满意。

And I think, all comes down to How can I include the nonce and block count to the encrypted string? 而且我认为,所有这些都归结为如何将现时数和块数包括在加密的字符串中? and How can I extract this information for decryption? 以及如何提取此信息进行解密?

We are still dealing with a bunch of questions here. 我们在这里仍在处理许多问题。

How can I extract the nonce and the counter for decryption? 如何提取随机数和计数器进行解密?

This is easy. 这很容易。 In the Javascript implementation (which does not follow a particular standard in this respect) the 8-byte nonce is prepended to the encrypted result. 在Javascript实现中(在这方面没有遵循特定的标准),8字节的随机数被放在加密结果的前面。 In Python, you extract it with: 在Python中,您可以使用以下命令提取它:

import base64
from_js_bin = base64.decode(from_js)
nonce = from_js_bin[:8]
ciphertext = from_js_bin[8:]

Where from_js is a binary string you received. 其中from_js是您收到的二进制字符串。

The counter cannot be extracted because the JS implementation does not transmit it. 由于JS实现不传输计数器,因此无法提取该计数器。 However, the initial value is (as typically happens) 0. 但是,初始值为(通常会发生)0。

How can I use the nonce and counter to decrypt the string in Python? 如何使用随机数和计数器在Python中解密字符串?

First, it must be established how nonce and counter are combined to get the counter block. 首先,必须确定随机数和计数器如何组合以获得计数器块。 It seems that the JS implementation follows the NIST 800-38A standard , where the left half is the nonce, and the right half is the counter. 似乎JS实现遵循NIST 800-38A标准 ,其中左半部分是随机数,右半部分是计数器。 More precisely, the counter is in big endian format (LSB is the rightmost byte). 更准确地说,计数器采用大字节序格式(LSB是最右边的字节)。 This is also what Wikipedia shows: 这也是Wikipedia显示的内容: AES CTR模式 .

Unfortunately, CTR mode is poorly documented in PyCrypto (a well-known problem ). 不幸的是,PyCrypto中很少记录CTR模式(这是一个众所周知的问题 )。 Basically, the counter parameter must be a callable object that returns the correct 16-byte (for AES) counter block, for each subsequent call. 基本上, counter参数必须是一个可调用对象,它为每个后续调用返回正确的16字节(对于AES)计数器块。 Crypto.Util.Counter does that, but in an obscure way. Crypto.Util.Counter可以这样做,但是用一种晦涩的方式。

It is there only for performance purposes though. 它只是出于性能目的而存在。 You can easily implement it yourself like this: 您可以这样轻松地自己实现它:

from Crypto.Cipher import AES
import struct

class MyCounter:

  def __init__(self, nonce):
    """Initialize the counter object.

    @nonce      An 8 byte binary string.
    """
    assert(len(nonce)==8)
    self.nonce = nonce
    self.cnt = 0

  def __call__(self):
    """Return the next 16 byte counter, as binary string."""
    righthalf = struct.pack('>Q',self.cnt)
    self.cnt += 1
    return self.nonce + righthalf

cipher_ctr = AES.new(key, mode=AES.MODE_CTR, counter=MyCounter(nonce))
plaintext = cipher_ctr.decrypt(ciphertext)

How long is the key for AES? AES密钥需要多长时间?

The key length for AES-128 is 16 bytes. AES-128的密钥长度为16个字节。 The key length for AES-192 is 24 bytes. AES-192的密钥长度为24个字节。 The key length for AES-256 is 32 bytes. AES-256的密钥长度为32个字节。 Each algorithm is different, but much of the implementation is shared. 每种算法都不同,但是许多实现是共享的。 In all cases, the algorithm operate on 16 byte blocks of data. 在所有情况下,该算法都对16字节的数据块进行操作。 For simplicity, stick to AES-128 ( nBits=128 ). 为简单起见,请坚持使用AES-128( nBits=128 )。

Will your code work? 您的代码可以工作吗?

I have the feeling it won't, because the way you compute the AES key seems incorrect. 我感觉不会,因为您计算AES密钥的方式似乎不正确。 The JS code encodes the password in UTF-8 and encrypts it with itself. JS代码使用UTF-8对密码进行编码,并对其进行加密。 The result is the actual key material. 结果是实际的关键材料。 It is 16 byte long, so for AES-192 and -256, the implementation copies part of it at the back. 它的长度为16个字节,因此对于AES-192和-256,实现将其部分复制到后面。 Additionally, the plaintext is also UTF-8 encoded before encryption. 此外,在加密之前,明文还经过UTF-8编码。

In general, I suggest you follow this approach: 通常,我建议您遵循以下方法:

  1. Make your JS implementation reproducible (right now encryption depends on the current time, which changes quite often ;-) ). 使您的JS实现具有可重现性(目前,加密取决于当前时间,该时间经常更改;-))。
  2. Print the value of the keys and data at each step (or use a debugger). 在每个步骤中打印键和数据的值(或使用调试器)。
  3. Try to reproduce the same algorithm in Python, and print the values too. 尝试在Python中重现相同的算法,并打印值。
  4. Investigate where they start to differ. 调查他们开始有所不同的地方。

Once you have duplicated the encryption algorithm in Python, the decryption one should be easy. 在Python中复制了加密算法后,解密就应该很容易了。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM