亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

Python AES-CTR 與 Golang 不兼容

Python AES-CTR 與 Golang 不兼容

Go
BIG陽 2023-05-22 16:56:36
我在 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))

現在它完美地工作。


查看完整回答
反對 回復 2023-05-22
?
呼啦一陣風

TA貢獻1802條經驗 獲得超6個贊

Counter您可以通過根本不使用該類來簡化代碼,此處記錄如下:

self.aes?=?AES.new(key,?AES.MODE_CTR,?initial_value=iv)


查看完整回答
反對 回復 2023-05-22
?
拉莫斯之舞

TA貢獻1820條經驗 獲得超10個贊

試試這個:

ctr = Counter.new(128, initial_value= int.frombytes(iv.encode(),'little'))

IV 始終作為整數值和字節格式的 Key 傳遞。從上述鏈接檢查文檔


查看完整回答
反對 回復 2023-05-22
  • 3 回答
  • 0 關注
  • 254 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號