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)
Go Sample:
aesBlock, err4 := aes.NewCipher(password) cfbDecrypter := cipher.NewCFBEncrypter(aesBlock, iv)
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)
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]) } }
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!