使用openssl中的MD5函數,該函數返回16位元組的unsigned char類型的資料,每個位元組的範圍都在0~255間,把
它格式化為十六進位就是32位md5編碼。註:一個位元組為8位,正好可以表示2位的十六進位。
使用登入用戶端的使用者名稱從Redis資料庫中得到salt值和加密後的密碼,然後把登入用戶端的密碼經過salt加密後,與
Redis資料庫中的密碼進行比較。相同則驗證通過,否則驗證失敗。
Redis資料庫中密碼的儲存格式為password:salt
使用者驗證演算法如下:
int user_authenticate(char *username, char *password)
{
char *salt_pw, *salt, *pw;
char buf[40];
char tmp[3]={'\0'}, md5_str[33]={'\0'};
unsigned char md[16];
int i;
//get_salt_pw調用Redis資料庫獲得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++){
sprintf(tmp, "%02x", md[i]);
strcat(md5_str, tmp);
}
//compare encode password using md5
if(strcmp((char*)md5_str, pw)){
return 0;
}
return 1;
}
其中要注意strtok函數的使用,以及16位元組的unsigned char轉換為32位十六進位數的過程。