python和nodejs的aes128加密對比


之前的機器人是用python寫的,有同事想改寫成nodejs版,但是驗證一直通不過,於是幫忙爬了一下文檔。

python版的代碼大概是長這樣:

#encoding:utf8

from Crypto.Cipher import AES
import binascii

key = 'abcdabcdabcdabcd'
plaintext = 'Secret Message A'

encobj = AES.new(key, AES.MODE_ECB)
ciphertext = encobj.encrypt(plaintext)

# Resulting ciphertext in hex
print ciphertext.encode('hex')

 

nodejs提供了兩種方式創建加密,一種是crypto.createCipher(algorithm, password),另一種是crypto.createCipheriv(algorithm, key, iv)。從文檔里可以看到,createCipher默認支持的是密碼的加密方式,而不是key。這種方法底層會幫忙從密碼推導出key和iv。而createCipheriv才是py版對應的AES.new。於是得到了nodejs版:

var crypto = require("crypto");
var key = new Buffer('abcdabcdabcdabcd','ascii');
var text = 'Secret Message A';

var cipher = crypto.createCipheriv('AES-128-ECB',key,'');
var decipher = crypto.createDecipheriv('AES-128-ECB',key,'');
var c1 = []
var c2 = []
c1.push(cipher.update(text, "ascii", "hex"))
c1.push(cipher.final("hex"))
var encrypted_text = c1.join('')
console.log(encrypted_text)
c2.push(decipher.update(encrypted_text, "hex", "ascii"))
c2.push(decipher.final("ascii"))
console.log(c2.join(''))

但是有個問題,nodejs版加密出來的密文,總是比python版要長。感覺nodejs最后的final方法,輸出了多余的東西。參考了一些網文,如果密文不夠一個block,update是沒有輸出的,如果超過一個block,update只會輸出一個block,剩余的放在final里返回。用python版解密看了一下,原來final在密文剛好一個block的情況下,會返回padding字符串。。。。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM