Search code examples
encryptiongoinitialization-vector

Why doesn't the golang crypto example use a random IV?


According to CWE-329 NON-Random IV's allow for the possibility of a dictionary attack. However, in the AES crypto example, golang docs use a non-random IV:

ciphertext := make([]byte, aes.BlockSize+len(plaintext))
iv := ciphertext[:aes.BlockSize]

Is this implementation safe or should I use a random function to get my IV?


Solution

  • It is secure, because the IV is filled from a Cryptographically Secure Pseudo Random Number Generator (CSPRNG) which is /dev/urandom by default and provided from the OS. From the ExampleNewCBCEncrypter function:

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