7

Looking in some cryptographic algorithms, I've realized that: The way the plain text is encrypted/decrypted is always specified, but what about the key? Every paper I've seen describing the algorithm never show a way to generate a key, but show the available key sizes.

This leads me to a question: How should I generate a key as someone who is implementing an algorithm? For example: The Twofish paper (https://www.schneier.com/paper-twofish-paper.pdf) says that Twofish has available key sizes of 128, 192 and 256 bits, but how should I create a 128 bit key? Not even the reference implementations I found contains code that seems to be aimed to be a key generation algorithm (again speaking of Twofish).

For a university work, I'll write a simple implementation of Twofish in C#, and I need a way to create a key but I don't know how to do it or even if there's a correct way to do this, that's why I ask this question.

A real example: When I encrypt anything with GnuPG (https://www.gnupg.org/) using symmetric keys, it does not generate any key or the like, it just asks for a password and does it. What's happening behind the scenes? How does GPG uses this password and how it's is related to the key generation?

Sid
  • 173
  • 1
  • 1
  • 4

1 Answers1

8

Symmetric keys don't need to be in any particular format -- they're just a sequence of (pseudo)random bits.

Most programming environments provide some sort of "secure random" mechanism (a CSPRNG). You can use this to acquire a byte array of the appropriate length (e.g. 32 bytes for AES256), which can be used as a key. Be sure to pass in the raw bytes, and not, e.g., a hex-encoded string.

Alternatively, you may want to derive a key from some other source. A Key Derivation Function (KDF) is a function that transforms some input into a key. GPG uses a Password-Based KDF (PBKDF, also known as a "password hash") to transform a password into a symmetric key.

Many PBKDFs use an iterated hashing approach; you might be interested in reviewing the design of "PBKDF2", or see scrypt for a more modern design. Generally though, as a developer, you can use an existing implementation and not be particularly concerned about the underlying details.

For completeness, there are also Key-Based KDFs such as HKDF that can derive symmetric keys from other keys, but I suspect that's not what you're after.

Tim McLean
  • 2,914
  • 1
  • 16
  • 26