The ElGamal and DSA algorithms

For RSA, the K parameters are unused; if you like, you can just pass empty strings. The ElGamal and DSA algorithms require a real K value for technical reasons; see Schneier's book for a detailed explanation of the respective algorithms. This presents a possible hazard that can inadvertently reveal the private key. Without going into the mathematical details, the danger is as follows. K is never derived or needed by others; theoretically, it can be thrown away once the encryption or signing operation is performed. However, revealing K for a given message would enable others to derive the secret key data; worse, reusing the same value of K for two different messages would also enable someone to derive the secret key data. An adversary could intercept and store every message, and then try deriving the secret key from each pair of messages.

This places implementors on the horns of a dilemma. On the one hand, you want to store the K values to avoid reusing one; on the other hand, storing them means they could fall into the hands of an adversary. One can randomly generate K values of a suitable length such as 128 or 144 bits, and then trust that the random number generator probably won't produce a duplicate anytime soon. This is an implementation decision that depends on the desired level of security and the expected usage lifetime of a private key. I can't choose and enforce one policy for this, so I've added the K parameter to the encrypt and sign methods. You must choose K by generating a string of random data; for ElGamal, when interpreted as a big-endian number (with the most significant byte being the first byte of the string), K must be relatively prime to self.p-1; any size will do, but brute force searches would probably start with small primes, so it's probably good to choose fairly large numbers. It might be simplest to generate a prime number of a suitable length using the Crypto.Util.number module.