pycrypto-AES CBC加密中的未知错误,密钥被剥离为16字节,但仍然会出现以下错误:
来源帮助文章:http://support.ideascale.com/kb/ideascale-setup/single-sign-on-multipass-token-based更新类模块:类multipassGenerator():definit(self):api_key="61fd537c-8961-479f-a13-aa91a401c3f5-5e866a4c-09c7-4ba0-8da1-cd8e4e88e3ec"app_key="25151"
def generateMultipass(self,usrEmail,usrName):
if usrEmail and usrName:
# EXAMPLE: Multipass JSON Token
message = {"email":usrEmail,"name":usrName,"expires":"2099-02-24T19:55:31.111-08:00"}
block_size = 16
mode = AES.MODE_CBC
# Replace api_key and app_key with your Community's API Key and Site Key
# The keys below are for this community: http://multipass.ideascale.com/
# Do not share your keys - the keys below are for testing purposes only.
# See: http://support.ideascale.com/kb/ideascale-setup/single-sign-on-multipass-token-based
api_key = self.api_key
app_key = self.app_key
json = JSON.dumps(message, separators=(',',':'))
salted = api_key+app_key
saltedHash = hashlib.sha1(salted).digest()[:16]
logging.info(message)
logging.info(salted)
#logging.info(saltedHash)
logging.info(len(saltedHash))
json_bytes = array.array('b', json[0 : len(json)])
pad = block_size - len(json_bytes.tostring()) % block_size
data = json_bytes.tostring() + pad * chr(pad)
aes = AES.new(saltedHash, mode)
encrypted_bytes = aes.encrypt(data)
b64token = base64.b64encode(encrypted_bytes)
b64token = re.sub(r's+' ,'' ,b64token)
b64token = re.sub(r'=+$','' ,b64token)
b64token = re.sub(r'+' ,'-',b64token)
b64token = re.sub(r'/' ,'_',b64token)
token = urllib.quote(b64token)
return token
我们执行这个:
from getUserMuiltipass import multipassGenerator
tokenGenerator = multipassGenerator()
tokenGenerator.api_key = u"61fd537c-8961-479f-a413-aa91a401c3f5-5e866a4c-09c7-4ba0-8da1-cd8e4e88e3ec"
tokenGenerator.app_key = u"25151"
email = 'sanvvvdeepkffffs@advaiddddya.com' # any input same issue
print email.split('@')[0]
ssoToken = tokenGenerator.generateMultipass(email,email.split('@')[0])
print ssoToken
这部分代码导致了问题:AES.new(saltedHash,mode)
Traceback (most recent call last):
File "C:Program Files (x86)Googlegoogle_appenginegoogleappenginetoolsdevappserver2pythonrequest_handler.py", line 156, in handle_interactive_request
exec(compiled_code, self._command_globals)
File "<string>", line 7, in <module>
File "C:appengineideasONSMSgetUserMuiltipass.py", line 59, in generateMultipass
aes = AES.new(saltedHash, mode)
File "C:Python27libsite-packagesCryptoCipherAES.py", line 95, in new
return AESCipher(key, *args, **kwargs)
File "C:Python27libsite-packagesCryptoCipherAES.py", line 59, in __init__
blockalgo.BlockAlgo.__init__(self, _AES, key, *args, **kwargs)
File "C:Python27libsite-packagesCryptoCipherblockalgo.py", line 141, in __init__
self._cipher = factory.new(key, *args, **kwargs)
ValueError: IV must be 16 bytes long
这可能是因为AES.new fn需要3个参数用于CBC模式:
AES.new(key, *args, **kwargs)
三维arg为IV。可以这样生成:
iv = Random.new().read(AES.block_size)