在Linux中使用MD5實現使用者驗證的解決方案

來源:互聯網
上載者:User

使用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位十六進位數的過程。

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.