我在 Ubuntu 16.04 上使用 Python2.7 和 pycryptodome 3.6.6 和 Golang1.10.4。我選擇的加密算法是 AES-CTR-128。但是用Python和Golang加密的數據結果是不一樣的。因此,這兩種語言編寫的應用程序之間的通信存在問題。這是我的工具:Python:#coding=utf-8from __future__ import absolute_importimport binasciifrom Crypto.Cipher import AESfrom Crypto.Util import Counterdef hexlify(binary): return binascii.hexlify(binary)class AES_CTR(object): def __init__(self, key, iv): assert len(key) == 16 assert len(iv) == 16 ctr = Counter.new(128) self.aes = AES.new(key, AES.MODE_CTR, counter=ctr) def encrypt(self, plain_data): return self.aes.encrypt(plain_data) def decrypt(self, encrypted_data): return self.aes.decrypt(encrypted_data)if __name__ == '__main__': aes = AES_CTR('abcdef0123456789', '0123456789abcdef') print hexlify(aes.encrypt("hello")) #print '9b1a038478' print hexlify(aes.encrypt("hello")) #print '8751ea0448' print hexlify(aes.encrypt("world")) #print 'b6aa7c286b'戈朗package mainimport ( "crypto/aes" "crypto/cipher" "encoding/hex" "fmt")type AESCipher struct { iv []byte stream cipher.Stream}func NewAESCipher(key []byte, iv []byte) *AESCipher { if (len(iv) != 16 || len(key) != 16) { panic("iv length or key length error") } block, err := aes.NewCipher(key) if (err != nil) { panic(err) } return &AESCipher { iv: iv, stream: cipher.NewCTR(block, iv), }}func (cipher *AESCipher) Encrypt(buffer []byte) []byte { encrypted := make([]byte, len(buffer)) cipher.stream.XORKeyStream(encrypted, buffer) return encrypted}func (cipher *AESCipher) Decrypt(buffer []byte) []byte { decrypted := make([]byte, len(buffer)) cipher.stream.XORKeyStream(decrypted, buffer) return decrypted}
3 回答

慕蓋茨4494581
TA貢獻1850條經驗 獲得超11個贊
pycryptodome 的默認實現是不正確的。我們可以更改它Counter
以使其按預期工作。
ctr?=?Counter.new(128,?initial_value=bytes_to_long(iv))
現在它完美地工作。

呼啦一陣風
TA貢獻1802條經驗 獲得超6個贊
Counter
您可以通過根本不使用該類來簡化代碼,此處記錄如下:
self.aes?=?AES.new(key,?AES.MODE_CTR,?initial_value=iv)

拉莫斯之舞
TA貢獻1820條經驗 獲得超10個贊
試試這個:
ctr = Counter.new(128, initial_value= int.frombytes(iv.encode(),'little'))
IV 始終作為整數值和字節格式的 Key 傳遞。從上述鏈接檢查文檔
- 3 回答
- 0 關注
- 254 瀏覽
添加回答
舉報
0/150
提交
取消