问题描述
我正在使用python 2.7.1我想使用AES在CTR模式下加密sth。我为python安装了PyCrypto库。我写了以下代码:
secret = os.urandom(16)
crypto = AES.new(os。 urandom(32),AES.MODE_CTR,counter = lambda:secret)
encrypted = crypto.encrypt(asdk)
print crypto.decrypt(encrypted)
我必须像我的明文的字节大小一样运行crypto.decrypt,以便正确解密解密的数据。即:
encrypted = crypto.encrypt(test)
print crypto.decrypt(encrypted)
print crypto.decrypt(encrypted)
print crypto.decrypt(encrypted)
print crypto.decrypt(encrypted)
最后一次解密将会给我明文。解密的其他输出是一些乱码。
我想知道这是否正常?我必须每次都加入大小与我的明文大小相等的循环,否则我有错误?
根据@gertvdijk,AES_CTR是一个流密码,不需要填充。所以我删除了相关的代码。
这是我知道的东西。
-
加密和解密时,您必须使用相同的密钥(
AES.new(...)中的第一个参数)/ / code>),并将密钥保密。
-
加密/解密方法是有状态,即
crypto.en(de)crypt abcd)== crypto.en(de)crypt(abcd)
是不始终为true。在您的点击率中,您的计数器回调总是返回相同的事情,所以当加密(我不是100%确定是原因)时,它成为无状态,但是我们仍然发现它在解密中有些状态。作为一个结论,我们应该总是使用一个新的对象去做。 -
加密和解密两者中的
计数器回调函数应该表现相同。在你的情况下,这样做是为了使两者都返回相同的秘密。但我不认为
秘密
是一个秘密。您可以使用随机生成的secret
,并将其传递给通信对等体,而不进行任何加密,以便对方可以直接使用它,只要秘密
是不可预测。
所以我会写这样的密码,希望它会提供一些帮助。
import os
import hashlib
import Crypto.Cipher.AES as AES
class Cipher:
@staticmethod
def md5sum(raw):
m = hashlib.md5()
m.update(raw)
return m.hexdigest()
BS = AES.block_size
@staticmethod
def pad(s )
注意填充不是必需的
返回s +(Cipher.BS - len(s)%Cipher.BS)* chr(Cipher.BS - len(s)%Cipher.BS)
return s
@staticmethod
def unpad(s )
return s [0:-ord(s [-1])]
return s
def __init __(self,key) b $ b self.key = Cipher.md5sum(key)
#计数器回调的状态
self.cnter_cb_called = 0
self.secret =无
def _reset_counter_callback_state(self,secret):
self.cnter_cb_called = 0
self.secret = secret
def _counter_callback(self):
这个功能应该是有状态的
self.cnter_cb_called + = 1
return self.secret [self.cnter_cb_called%Cipher.BS] * Cipher.BS
def加密(self,raw):
secret = os.urandom(Cipher.BS)#random选择一个不秘密的秘密
self._reset_counter_callback_state(secret)
cipher = AES.new(self.key,AES.MODE_CTR,counter = self._counter_callback)
raw_padded = Cipher.pad(raw)
enc_padded = cipher.encrypt(raw_padded)
返回密码+ enc_padded #yes,它不是秘密
def decrypt(self,enc):
secret = enc [:Cipher.BS]
self._reset_counter_callback_state(secret)
cipher = AES.new(self.key,AES.MODE_CTR,counter = self._counter_callback)
enc_padded = enc [Cipher.BS:] #we没有加密秘密,所以不要解密
raw_padded = cipher.decrypt(enc_padded)
返回Cipher.unpad(raw_padded)
一些测试:
>>>从密码导入密码
>>> x =密码(这是关键)
>>> a== x.decrypt(x.encrypt(a))
True
>>> b== x.decrypt(x.encrypt(b))
True
>>> c== x.decrypt(x.encrypt(c))
True
>>> x.encrypt(a)== x.encrypt(a)
False#虽然输入是相同的,输出是不同的
参考:
I am using python 2.7.1I want to encrypt sth using AES in CTR mode. I installed PyCrypto library for python. I wrote the following code:
secret = os.urandom(16)
crypto = AES.new(os.urandom(32), AES.MODE_CTR, counter=lambda: secret)
encrypted = crypto.encrypt("asdk")
print crypto.decrypt(encrypted)
i have to run crypto.decrypt as many times as the byte size of my plaintext in order to get correctly the decrypted data. I.e:
encrypted = crypto.encrypt("test")
print crypto.decrypt(encrypted)
print crypto.decrypt(encrypted)
print crypto.decrypt(encrypted)
print crypto.decrypt(encrypted)
The last call to decrypt will give me the plaintext back. The other outputs from decrypt are some gibberish strings .I am wondering if this is normal or not? Do i have to include into a loop with size equal of my plaintext every time or i have gotten sth wrong?
According to @gertvdijk, AES_CTR is a stream cipher which does not need padding. So I've deleted the related codes.
Here's something I know.
You have to use a same key(the first parameter in
AES.new(...)
) in encryption and decryption, and keep the key private.The encryption/decryption methods are stateful, that means
crypto.en(de)crypt("abcd")==crypto.en(de)crypt("abcd")
is not always true. In your CTR, your counter callback always returns a same thing, so it becomes stateless when encrypt (I am not 100% sure it is the reason), but we still find that it is somewhat stateful in decryption. As a conclusion, we should always use a new object to do them.The
counter callback
function in both encryption and decryption should behave the same. In your case, it is to make both of them return the same secret. Yet I don't think thesecret
is a "secret". You can use a random generated"secret"
and pass it across the communicating peers without any encryption so that the other side can directly use it, as long as thesecret
is not predictable.
So I would write my cipher like this, hope it will offer some help.
import os
import hashlib
import Crypto.Cipher.AES as AES
class Cipher:
@staticmethod
def md5sum( raw ):
m = hashlib.md5()
m.update(raw)
return m.hexdigest()
BS = AES.block_size
@staticmethod
def pad( s ):
"""note that the padding is no necessary"""
"""return s + (Cipher.BS - len(s) % Cipher.BS) * chr(Cipher.BS - len(s) % Cipher.BS)"""
return s
@staticmethod
def unpad( s ):
"""return s[0:-ord(s[-1])]"""
return s
def __init__(self, key):
self.key = Cipher.md5sum(key)
#the state of the counter callback
self.cnter_cb_called = 0
self.secret = None
def _reset_counter_callback_state( self, secret ):
self.cnter_cb_called = 0
self.secret = secret
def _counter_callback( self ):
"""
this function should be stateful
"""
self.cnter_cb_called += 1
return self.secret[self.cnter_cb_called % Cipher.BS] * Cipher.BS
def encrypt(self, raw):
secret = os.urandom( Cipher.BS ) #random choose a "secret" which is not secret
self._reset_counter_callback_state( secret )
cipher = AES.new( self.key, AES.MODE_CTR, counter = self._counter_callback )
raw_padded = Cipher.pad( raw )
enc_padded = cipher.encrypt( raw_padded )
return secret+enc_padded #yes, it is not secret
def decrypt(self, enc):
secret = enc[:Cipher.BS]
self._reset_counter_callback_state( secret )
cipher = AES.new( self.key, AES.MODE_CTR, counter = self._counter_callback )
enc_padded = enc[Cipher.BS:] #we didn't encrypt the secret, so don't decrypt it
raw_padded = cipher.decrypt( enc_padded )
return Cipher.unpad( raw_padded )
Some test:
>>> from Cipher import Cipher
>>> x = Cipher("this is key")
>>> "a"==x.decrypt(x.encrypt("a"))
True
>>> "b"==x.decrypt(x.encrypt("b"))
True
>>> "c"==x.decrypt(x.encrypt("c"))
True
>>> x.encrypt("a")==x.encrypt("a")
False #though the input is same, the outputs are different
Reference: http://packages.python.org/pycrypto/Crypto.Cipher.blockalgo-module.html#MODE_CTR
这篇关于CTR中的AES如何用于PyCrypto的Python?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!