如何使用纯文本密码加密AES256 CTR?

I'm working with this example to try to encrypt data using AES-256. However, when I use the password WeakPasswordForTesting as input, I get an error: crypto/aes: invalid key size. I get the impression that it has to do with my plain password length. How can I use this example code to encrypt the data using a short plain-text password?

func Encrypt(password []byte, plainSource []byte) ([]byte, error) {
    key, _ := hex.DecodeString(string(password))
    block, err := aes.NewCipher(key)
    if err != nil {
        panic(err)
    }

    // The IV needs to be unique, but not secure. Therefore it's common to
    // include it at the beginning of the ciphertext.
    ciphertext := make([]byte, aes.BlockSize+len(plainSource))
    iv := ciphertext[:aes.BlockSize]
    if _, err := io.ReadFull(rand.Reader, iv); err != nil {
        panic(err)
    }
    stream := cipher.NewCTR(block, iv)
    stream.XORKeyStream(ciphertext[aes.BlockSize:], plainSource)

    return ciphertext, nil
}

The Advanced Encryption Standard (AES) is a block cipher which expects a key of a fixed size. The key length is in the name of the cipher: AES-256 means a key length of 256 bits.

As your password is not a key which conforms to this spec, you need to implement a process to make it so. A common mechanism is a key derivation function, which takes an input passphrase of entropy significantly lower than the desired key length, and pads it with various data to produce a key of the required length. The PBKDF family (password-based key derivation function) is an example of this, as is scrypt.


You should not implement a naïve mechanism to pad your input data in this way, as the security of a good cryptosystem is entirely dependent on the quality of the key, and it is highly unlikely any homegrown solution will be resistant to a variety of attacks.

This question on crypto.SE may be interesting regarding a more thorough assessment of implementation recommendations using PBKDF2.