How do I control an access code safely? Upon registration an user has to specify an access code of five digits. This access code is also used as a password for the encryption and decryption of certain strings.

The user types in "12345" (ACCESS_CODE).

Obviously, we don't want to save this access code on the device.

Now, when the user wants to decrypt he types in the access code, and if the code is correct, the decryption will happen succesfully. 

However, preferably, I would like, before the decyrption takes place, check whether the access code is right, without saving it on the device.

How can this be achieved?

One way I was thinking is to encrypt a string "CHECKSTRING" with the access code. Then the check would be:


Decrypt the encrypted "CHECKSTRING" (ENCR_STRING) --> (DECR_STRING) with ACCESS_CODE
Check if DEC_STRING == "CHECKSTRING", then code is correct, otherwise not.


But this seems to me quite unsafe, as someone could simulate an encryption of the "CHECKSTRING" (which is known and visible in the code) for all combinations of 12345 and then cross match which code I used to obtain the ENCR_STRING.

What other alternatives are there?
So you have a secret with low entropy which you want to verify in a secure way.

This is a standard scenario in password-based cryptography (PINs are sort of a password).

What you'll do in both scenarios described below:
The user first enters his access-code (=PIN), which get buffered in the RAM. Now storage media (the device/a drive) will provide the program (processor) with a random looking string that the media stored. (This is the salt) The media supplies parameters as well. (Iteration Counts, (N,R,P)-Values, (t_cost,m_cost)-Values). Now you use a password-hashing function (scrypt/winner of PHC) using the supplied parameters, the salt and the password to derive a tag/key.

You have two ways at approaching your problem:


The straight forward way to do what you want is to get a tag generated by the PHS (password-hashing scheme), store this on first entry on the storage media (along with salt and parameters) and just check if the tag matches with what will be generated at verification-time. I wouldn't recommend this way, as it relies on your code to be bug-free.
The better way (in my eyes) would be to derive a key using the PHS, which will be used for verification/decryption. So the security of the data would strongly rely on the password and not on some authorization code. The storage media would only store salt and parameters and you'd  see that the access-code is correct as verification succeeds.