Should text be hashed before being used as an encryption key? Let's say I have an API that provides an encryption wrapper around another API. I give the consuming programmer the option of either passing a string or byte array as an encryption key.

The byte array must be the correct size, and is used directly as the encryption key.

However, if they pass a string, I hash it using SHA256/SHA192/SHA128 before passing it to the encryption function.

Is it correct to hash text of arbitrary length before using it as a key?

Or should it be accepted as is, even if it means the encryption key will either have a large amount of \0 bytes if it is too short, or be truncated if it too long?



The underlying cipher is AES/Rijndael
Considering that someone will probably end up supplying a password for that argument at some point, it would be better to use a proper slow key derivation function like pbkdf2/scrypt/argon2. 

Even if they don't end up sticking a password in there, meaningful/arbitrary text and passwords should be treated the same in regards to an adversary's ability to guess the string. If the string is not actually a random value - meaning it's not the output of /dev/urandom - then it will not have 8 bits/byte of entropy, parts of it are guessable, and it should not be used directly as a key. Hashing an easily guessed value with SHA256 does not make the result unguessable - all it will do is make the output more appropriately sized.

Note

With that being said, if the option is available, you should prefer to use pre-existing crypto libraries such as libsodium. They have already handled all of these sorts of details (as well as all sorts of obscure pitfalls, side channels, and other black magic) and produced a succinct interface that more or less removes all of these sorts of questions for the developer.