Gregorio Di Stefano
Gregorio Di Stefano

Reputation: 1203

Golang crypto: encrypted file not prefixed with IV

I am using an IV in cipher.NewOFB, but my encrypted file never gets prefixed with it. I followed the golang examples at https://golang.org/pkg/crypto/cipher/, but can't seem to figure out why the prefix isn't being considered.

Does anyone see what the problem is?

func generateRandomIV(length int) []byte {
    iv := make([]byte, aes.BlockSize)

    if _, err := io.ReadFull(rand.Reader, iv); err != nil {
        panic(err)
    }

    return iv
}


func encryptFile(filename, keystring string) error {
    readFile, err := os.Open(filename)
    iv := generateRandomIV(aes.BlockSize)

    outFile, err := os.OpenFile(filename+".enc", os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0600)
    if err != nil {
        panic(err)
    }

    defer readFile.Close()
    defer outFile.Close()

    key := []byte(keystring)

    block, err := aes.NewCipher(key)

    if err != nil {
        panic(err)
    }

    fmt.Println("IV:", iv)
    writer := &cipher.StreamWriter{S: cipher.NewOFB(block, iv), W: outFile}

    if _, err := io.Copy(writer, readFile); err != nil {
        return err
    }

    return nil
}

Upvotes: 1

Views: 316

Answers (1)

zaph
zaph

Reputation: 112857

Add the IV prefix yourself or pre-share the IV. If you prefix it you will have the remove it and apply it on decryption.

How an IV is shared is not part of the encryption standard, it is a developer choice. Prefixing the IV is common but not required or the only way, it is however a good choice.

Upvotes: 2

Related Questions