在 Go 中解密在 Python 中以 CFB 模式使用 AES 加密的内容

问题

我希望能够在 Go 中解密在 Python 中加密的内容。加密/解密函数分别在每种语言中工作,但当我在 Python 中加密和在 Go 中解密时,我猜测编码有问题,因为我得到了乱码输出:


Rx����d��I�K|�ap���k��B%F���UV�~d3h�����|�����>�B��B�

Python中的加密/解密

def encrypt(plaintext, key=config.SECRET, key_salt='', no_iv=False):

    """Encrypt shit the right way"""


    # sanitize inputs

    key = SHA256.new((key + key_salt).encode()).digest()

    if len(key) not in AES.key_size:

        raise Exception()

    if isinstance(plaintext, string_types):

        plaintext = plaintext.encode('utf-8')


    # pad plaintext using PKCS7 padding scheme

    padlen = AES.block_size - len(plaintext) % AES.block_size

    plaintext += (chr(padlen) * padlen).encode('utf-8')


    # generate random initialization vector using CSPRNG

    if no_iv:

        iv = ('\0' * AES.block_size).encode()

    else:

        iv = get_random_bytes(AES.block_size)

    log.info(AES.block_size)

    # encrypt using AES in CFB mode

    ciphertext = AES.new(key, AES.MODE_CFB, iv).encrypt(plaintext)


    # prepend iv to ciphertext

    if not no_iv:

        ciphertext = iv + ciphertext

    # return ciphertext in hex encoding

    log.info(ciphertext)

    return ciphertext.hex()



def decrypt(ciphertext, key=config.SECRET, key_salt='', no_iv=False):

    """Decrypt shit the right way"""


    # sanitize inputs

    key = SHA256.new((key + key_salt).encode()).digest()

    if len(key) not in AES.key_size:

        raise Exception()

    if len(ciphertext) % AES.block_size:

        raise Exception()

    try:

        ciphertext = codecs.decode(ciphertext, 'hex')

    except TypeError:

        log.warning("Ciphertext wasn't given as a hexadecimal string.")


    # split initialization vector and ciphertext

    if no_iv:

        iv = '\0' * AES.block_size

    else:

        iv = ciphertext[:AES.block_size]

        ciphertext = ciphertext[AES.block_size:]


    # decrypt ciphertext using AES in CFB mode

    plaintext = AES.new(key, AES.MODE_CFB, iv).decrypt(ciphertext).decode()



饮歌长啸
浏览 234回答 1
1回答

繁花如伊

CFB 模式使用与每个加密步骤加密的位相对应的段大小,请参阅CFB。Go 仅支持 128 位 (CFB128) 的段大小,至少没有更深层次的修改(参见此处和此处)。相反,PyCryptodome 中的段大小是可配置的,默认为 8 位 (CFB8),s。在这里。发布的 Python 代码使用此默认值,因此这两个代码不兼容。由于段大小在Go代码中是不可调整的,所以在Python代码中必须设置为CFB128:cipher&nbsp;=&nbsp;AES.new(key,&nbsp;AES.MODE_CFB,&nbsp;iv,&nbsp;segment_size=128)此外,密文在 Python 代码中是十六进制编码的,因此它必须在 Go 代码中进行十六进制解码,这在发布的代码中尚未发生。通过这两个更改,可以解密使用 Python 代码生成的密文。以下 Go 代码中的密文是使用 Python 代码使用 128 位的段大小和密码短语创建的my passphrase,并成功解密:package mainimport (&nbsp; &nbsp; "crypto/aes"&nbsp; &nbsp; "crypto/cipher"&nbsp; &nbsp; "crypto/sha256"&nbsp; &nbsp; "encoding/hex"&nbsp; &nbsp; "fmt")func main() {&nbsp; &nbsp; ciphertextHex := "546ddf226c4c556c7faa386940f4fff9b09f7e3a2ccce2ed26f7424cf9c8cd743e826bc8a2854bb574df9f86a94e7b2b1e63886953a6a3eb69eaa5fa03d69ba5" // Fix 1: Apply CFB128 on the Python side&nbsp; &nbsp; fmt.Println(Decrypt(ciphertextHex))&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;// The quick brown fox jumps over the lazy dog}func PKCS5UnPadding(src []byte) []byte {&nbsp; &nbsp; length := len(src)&nbsp; &nbsp; unpadding := int(src[length-1])&nbsp; &nbsp; return src[:(length - unpadding)]}func Decrypt(ciphertext string) string {&nbsp; &nbsp; h := sha256.New()&nbsp; &nbsp; //h.Write([]byte(os.Getenv("SECRET")))&nbsp; &nbsp; h.Write([]byte("my passphrase")) // Apply passphrase from Python side&nbsp; &nbsp; key := h.Sum(nil)&nbsp; &nbsp; //ciphertext_bytes := []byte(ciphertext)&nbsp; &nbsp; ciphertext_bytes, _ := hex.DecodeString(ciphertext) // Fix 2. Hex decode ciphertext&nbsp; &nbsp; block, err := aes.NewCipher(key)&nbsp; &nbsp; if err != nil {&nbsp; &nbsp; &nbsp; &nbsp; panic(err)&nbsp; &nbsp; }&nbsp; &nbsp; iv := ciphertext_bytes[:aes.BlockSize]&nbsp; &nbsp; if len(ciphertext) < aes.BlockSize {&nbsp; &nbsp; &nbsp; &nbsp; panic("ciphertext too short")&nbsp; &nbsp; }&nbsp; &nbsp; ciphertext_bytes = ciphertext_bytes[aes.BlockSize:]&nbsp; &nbsp; stream := cipher.NewCFBDecrypter(block, iv)&nbsp; &nbsp; stream.XORKeyStream(ciphertext_bytes, ciphertext_bytes)&nbsp; &nbsp; plaintext := PKCS5UnPadding(ciphertext_bytes)&nbsp; &nbsp; return string(plaintext)}安全:使用摘要作为密钥派生函数是不安全的。应用专用的密钥派生函数,如 PBKDF2。静态或丢失的盐也是不安全的。为每次加密使用随机生成的盐。将非秘密盐与密文(类似于 IV)连接起来,例如salt|IV|ciphertext。该变体no_iv=True应用静态 IV(零 IV),这是不安全的,不应使用。正确的方法在 variant 中有描述no_iv=False。CFB 是一种流密码模式,因此不需要填充/解填充,因此可以在两侧删除。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go