Golang AES CFB - Mutation IV
I am writing a client application in Go that needs to interact with a program on the server. The client performs AES CFB encryption and the server decrypts. Unfortunately the server side has a bug when reusing the initialization vector. It tries to do 3 decryption operations based on: -
key1, iv
key2, iv
key3, iv
Because of this issue, iv is actually modified between decrypted operations. Now my problem is how to reproduce this client-side behavior using Go.
Inserting Println into the encryption function below, I see a cfb structure that I think contains the modified IV for the next block, but since this is a stream interface, I'm not sure how to extract it into a byte slice. Any suggestions?
thank
package main
import (
"fmt"
"encoding/hex"
"crypto/cipher"
"crypto/aes"
)
func encrypt_aes_cfb(plain, key, iv []byte) (encrypted []byte) {
block, err := aes.NewCipher(key)
if err != nil {
panic(err)
}
encrypted = make([]byte, len(plain))
stream := cipher.NewCFBEncrypter(block, iv)
stream.XORKeyStream(encrypted, plain)
fmt.Println(stream)
return
}
func main() {
plain := []byte("Hello world...16Hello world...32")
key := make([]byte, 32)
iv := make([]byte, 16)
enc := encrypt_aes_cfb(plain, key, iv)
fmt.Println("Key: ", hex.EncodeToString(key))
fmt.Println("IV: ", hex.EncodeToString(iv))
fmt.Println("Enc: ", hex.EncodeToString(enc))
}
source to share
Going down the path you are hinting at is a little ugly and prone to interruption when the implementation changes.
You can get IV from stream:
s := reflect.Indirect(reflect.ValueOf(stream))
lastIV := s.FieldByName("next").Bytes()
But, there is an easier way! Concatenate simple text inputs such that the stream for the second starts at IV from the end of the first (and so on).
combined := append(plain, plain2...) encCombined := encrypt_aes_cfb(combined, key, iv) enc := encCombined[:len(plain)] enc2 := encCombined[len(plain):]
source to share