最初linux將用戶的密碼通過某種one-way function得到一個散列(加密)後的字符串,並存儲該字符串在密碼文件中,但這種方式易遭受字典攻擊,攻擊者只有準備好字典,使用相同的one-way function計算出對應的值,逐個對比就ok就可以攻破。
爲了提高安全性,引入salt,所謂的salt,即爲一個隨機數,引入的時候爲一個2字符的字符串(從[A-Za-z0-9./]共64個字符選取,後來salt擴展到最多12個字符),當用戶設置密碼時,會隨機生成一個salt,與用戶的密碼一起加密,得到一個加密的字符串(salt以明文形式包含在該字符串中),存儲到密碼文件中,這樣就將攻擊的難度擴大了64*64即4096倍。
crypt將用戶的key和salt一起適應某種算法進行加密(散列)
char *crypt(const char *key, const char *salt);
crypt中可以使用多種加密(散列)機制,包括最初的DES,還有後來爲提高安全性引入的md5,blowfish,sha-256,sha-512.
crypt爲支持不同的方式,將salt進行格式化,格式爲:
$id$salt$encoded (這也是保存在shadow文件中的格式)
這裏不同id代表不同的算法,不同算法salt的長度也不同。
id | Method | 實際加密後的密碼長度 |
1 | MD5(12 個 salt 字符) | 22 |
2a | Blowfish | 只在某些發行版中支持 |
5 | SHA-256 (12 個 salt 字符) | 43 |
6 | SHA-512 (12 個 salt 字符) | 86 |
使用 C 語言驗證某個用戶的密碼:
源碼如下:
#include <stdio.h>
#include <string.h>
#include <shadow.h>
#include <unistd.h>
int main(int argc, char **argv)
{
struct spwd *sp;
sp = getspnam(argv[1]);
if(sp == NULL)
{
printf("get spentry error\n");
return -1;
}
if(strcmp(sp->sp_pwdp, (char*)crypt(argv[2], sp->sp_pwdp)) == 0)
{
printf("yes\n");
}
else
{
printf("no\n");
}
return 0;
}
注意:執行的時候需要 root 權限。。