獲取問題加密AES加密在cryptojs和蟒蛇解密Crypto.Cipher
<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>
而在對AES加密和解密的Python腳本我用
#!/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()
但相同IV,消息以及k ey在python和js中產生不同的加密消息,
JavaScript與python解密兼容的問題是什麼?
兩者都使用AES.MODE_CBC並假定使用了兩個Pkcs7填充。硬編碼iv現在這些是隨機生成的
CryptoJS.AES.encrypt()base64是否對輸出進行編碼?因爲在你的js代碼中,你正在返回base64編碼的AES東西。 –
將iv附加到CryptoJS.AES.encrypt()產生加密的消息作爲iv +加密然後做base64編碼,因爲它匹配python加密「base64.b64encode(iv + cipher.encrypt(raw))」 – UdayaLakmal
對不起,沒有看到btoa()調用。嗯.. –