Home > Backend Development > Golang > Why Do My Go and PyCrypto AES-CFB Implementations Produce Different Ciphertexts?

Why Do My Go and PyCrypto AES-CFB Implementations Produce Different Ciphertexts?

Barbara Streisand
Release: 2024-12-11 14:55:10
Original
524 people have browsed it

Why Do My Go and PyCrypto AES-CFB Implementations Produce Different Ciphertexts?

Different Results in Go and Pycrypto with AES-CFB

This question arises from the need to integrate a Go application into an existing Python codebase that utilizes PyCrypto for encryption. The problem manifests when the Python and Go implementations of AES-CFB encryption produce different cyphertexts.

Python Sample:

cipher = Crypto.Cipher.AES.new(
            key=password, 
            mode=Crypto.Cipher.AES.MODE_CFB, 
            IV=iv)
Copy after login

Go Sample:

aesBlock, err4 := aes.NewCipher(password)
cfbDecrypter := cipher.NewCFBEncrypter(aesBlock, iv)
Copy after login

In Go, the NewCFBEncrypter function uses 16-bit segments by default, while in Python, PyCrypto uses 8-bit segments (CFB8). To resolve this discrepancy and allow Go to decrypt cyphertext encrypted using the PyCrypto settings, the Go implementation must be modified to support CFB8.

Solution:

Research reveals that Go's CFBDecrypter and CFBEncrypter source code can be easily adapted to support CFB8. The modification involves changing the segment size in the following lines:

Original Code:

func (f *cfb) XORKeyStream(dst, src []byte)
Copy after login

Modified Code:

func (f *cfb) XORKeyStream(dst, src []byte) {
    for i := 0; i < len(src); i += 1 {
        f.b[0] = f.b[0] << 8 | src[i] >> 8
        f.b[1] = src[i]
        dst[i] = f.b[f.s] ^ f.update(f.b[0]^f.b[1])
    }
}
Copy after login

By implementing this modification, Go will support CFB8 and be able to decrypt cyphertext encrypted using the Python implementation's settings.

The above is the detailed content of Why Do My Go and PyCrypto AES-CFB Implementations Produce Different Ciphertexts?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template