为了账号安全,请及时绑定邮箱和手机立即绑定

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 关注
  • 120 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信