AES encrypt in cryptojs and decrypt in python Crypto.Cipher

廉价感情. 提交于 2019-12-09 20:39:50

问题


Getting problem with encrypt using js CryptoJS and decrypt that using python crypto.Cipher

This is my implementation in js, append iv with encrypted message and encode with base64

<script src="http://crypto-js.googlecode.com/svn/tags/3.1.2/build/rollups/aes.js"></script>
<script>
    var message='Secreat Message to Encrypt';
    var key = CryptoJS.enc.Hex.parse('824601be6c2941fabe7fe256d4d5a2b7');
    var iv  = CryptoJS.enc.Hex.parse('1011121314151617');

    var encrypted = CryptoJS.AES.encrypt(message, key, { iv: iv, mode: CryptoJS.mode.CBC });
    encrypted =encrypted.toString();


    encrypted = iv+encrypted;
    encrypted = btoa(encrypted);
    console.log('encrypted',encrypted );    
    alert(encrypted); 

   // var decrypted =  CryptoJS.AES.decrypt(encrypted, key, { iv: iv, mode: CryptoJS.mode.CBC });
   // console.log('decrypted', decrypted);
   //alert(decrypted.toString(CryptoJS.enc.Utf8));
</script>

And in the python script for aes encryption and decryption i used

#!/usr/bin/python

import os, random, struct
from Crypto.Cipher import AES
from Crypto import Random
import base64
class AESCipher:
    def __init__(self, key):
        BS = 16
        self.pad = lambda s: s + (BS - len(s) % BS) * chr(BS - len(s) % BS)
        self.unpad = lambda s : s[0:-ord(s[-1])]
        self.key = self.pad(key[0:16])

    def encrypt(self, raw):
        raw = self.pad(raw)
        iv = "1011121314151617"
        cipher = AES.new(self.key, AES.MODE_CBC, iv)
        return base64.b64encode(iv + cipher.encrypt(raw))

    def decrypt(self, enc):
        enc = enc.replace(' ', '+')
        enc = base64.b64decode(enc)
        iv = enc[:16]
        cipher = AES.new(self.key, AES.MODE_CBC, iv)
        return self.unpad(cipher.decrypt( enc[16:]))


def main():     

    cipher = AESCipher('824601be6c2941fabe7fe256d4d5a2b7')
    encrypteddata =cipher.encrypt(''Secreat Message to Encrypt'')
    print encrypteddata         

    decryptdata =cipher.decrypt(encrypteddata)
    print decryptdata 

main()

but same iv, message and key produce different encrypted message in python and js,

what is the problem with JavaScript to compatible with python decryption?

Both used AES.MODE_CBC and assume both used Pkcs7 padding. hard coded iv for now those are generate randomly


回答1:


Try with an IV that has actually the same size as the block size of AES, 16 bytes. You are currently specifying 8 bytes in hexadecimals. CBC mode requires an IV of the same size as the block size and the Python API specifies (including final typo):

For all other modes, it must be block_size bytes longs.

It's best to use a method or (predefined) constant like above.



来源:https://stackoverflow.com/questions/20972851/aes-encrypt-in-cryptojs-and-decrypt-in-python-crypto-cipher

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!