# Using a hash with a constant key to create easily verifiable codes

I'll keep my question short. If I keep handing out different codes generated by this function, will it be trivial to figure out the secret key?

secret_key = {random bytes}

function generate_code(parameters)
return sha256(parameters + secret_key)


I know little about these things. What I like about this function is that it's trivial to verify if a code is valid given the same parameters. If this is a bad way of achieving this, what is a better way?

-
Your question is a short version of this one: crypto.stackexchange.com/questions/2669/… The construct sha256(secret + parameters) wouldn't have been secure. The industry standard is to use an HMAC, which uses a nested hash. –  Yolanda Ruiz Mar 9 at 23:40

I will keep my answer short.

Yes it is trivial, in order to verify the code you need the parameters AND the key, thus there is no easy way to keep the key secure except through a hardware security module.

The correct way would be to use a digital signature:

Sign(SHA256(parameters),secret_key)


The signature can be verified by anyone with the public key, and the secret key is not required or exposed.

-
Well, I have two problems with this answer: (1) it doesn't mention HMAC, which the question just screams to recommend IMO, and (2) it suggests signing a digest of the message, which should already be handled by the signature's padding scheme. –  Reid Mar 9 at 23:15
HMAC still requires the secret key to verify the code. Sign() in my answer is a generic "pad and perform the asymmetric algorithm on the input", and not a full digital signature algorithm. If i had used DSA() in its place, then the hash is performed. Sorry that was not clear enough. Technically no hash is required if the parameter is small enough. –  Richie Frame Mar 9 at 23:33