A solution to implement user authentication using MD5 in Linux
- 2020-05-06 12:08:26
- OfStack
Use the MD5 function in openssl, which returns 16 bytes of data of type unsigned char, with each byte ranging from 0 to 255
It's formatted as hexadecimal which is the 32-bit md5 code. Note: a byte is 8 bits, which is exactly 2 bits of hexadecimal.
The user name of the login client is used to obtain the salt value and the encrypted password from the Redis database, and then the password of the login client is encrypted by salt and then compared with
Compare passwords in the Redis database. The same is validated, otherwise the validation fails.
The password in the Redis database is stored in password:salt
The user verification algorithm is as follows:
int user_authenticate(char *username, char *password)
{
salt salt_pw char * and * and * pw;
char buf [40].
char tmp [3] = {} '\ 0', md5_str [33] = {} '\ 0';
unsigned char md [16].
int i;
//get_salt_pw calls Redis database to get password:salt
salt_pw = get_salt_pw (db username);
pw = strtok (salt_pw, ":");
if (! pw) {
return 0;
}
salt = strtok (NULL, ":");
if (! salt) {
return 0;
}
strcpy (buf password);
strcat (buf salt);
MD5((const unsigned char*)buf, strlen(buf), md);
//transform to md5 string
for (i = 0; i < 16; i++){
02 x sprintf (tmp, "%", md [i]);
strcat (md5_str tmp);
}
//compare encode password using md5
if (strcmp ((char *) md5_str pw)) {
return 0;
}
return 1;
}
Note the use of the strtok function and the conversion of the 16-byte unsigned char to a 32-bit hexadecimal number.