"Characters" is the wrong level of abstraction here, and fixating on that can only lead you astray. Proper cryptographic keys are not passwords!
- Passwords are normally human-chosen, and users may be expected to memorize them.
- Cryptographic keys must not be human-chosen! And no good key is human-memorable—you should generally keep keys as copies under secure storage (which may be password-protected).
Why is this so important? Because most cryptographic algorithms expect you to choose keys uniformly at random from the whole range of allowed values. For algorithms where the key is a fixed-length bit sequence, that means any sequence of bits of the required size should be equally likely as any other.
This means that to generate a cryptographic key you must not ask humans to choose characters like you do for passwords, because humans are bad at randomness. Rather, you must use a cryptographically secure random number generator to produce an array of randomly-chosen raw bytes. So to work with keys you should stay clear of any character string types that involve character encodings like ASCII or Unicode, and learn how to work with byte arrays in the programming language of your choice. For example in Java it would be the
byte type; in Rust it would be
[u8] (byte slice) or
[u8; N] (byte array of size
N); in C it would be
char (a type that in hindsight should have had a different name); etc. Or even better, you should work with a type that abstracts away from this, like Java's
Note that keys are sometimes serialized as base-64 or hexadecimal ASCII string, but that's just a format for, e.g., sticking them into file types like JSON that can't accept arbitrary bytes. But the algorithms want the raw byte arrays!
Also, there is something called password-based key derivation, which is the use of specialized cryptographic algorithms to turn user-selected passwords into pseudo-random cryptographic keys. Well-designed encryption programs that work off passwords don't use the user-supplied passwords directly as keys, but rather run them through such an algorithm. This is sometimes called "password-based encryption." Popular algorithms for deriving keys from passwords are:
Note that this approach trades security for user-friendliness. Users find passwords easier to (mis)use and (mis)understand than proper cryptographic keys, but they are very unlikely to choose passwords that are nearly as strong as a proper, randomly-generated key. (And the very few users who choose equivalently strong passwords are likely sophisticated enough to use proper keys!)