#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <shadow.h>
#include <errno.h>
void error_quit(char *msg)
{
perror(msg);
exit(-2);
}
void get_salt(char *salt,char *passwd)
{
int i,j;
//取出salt,i記錄密碼字符下標,j記錄$出現次數
for(i=0,j=0;passwd[i] && j != 3;++i)
{
if(passwd[i] == '$')
++j;
}
strncpy(salt,passwd,i-1);
}
int main(int argc,char **argv)
{
struct spwd *sp;
char passwd[100]={0};
char salt[512]={0};
FILE *fp ;
int i = 0 ;
if((fp=fopen("./pass","r")) == NULL)
printf(" open file wrong!") ;
if((sp=getspnam("username")) == NULL)
error_quit("獲取用戶名和密碼");
//得到salt,用得到的密碼作參數
get_salt(salt,sp->sp_pwdp);
for( ; i < 10; i++)
{
fgets(passwd , 10, fp) ;
if(passwd == NULL)
break;
int length = strlen(passwd) ;
passwd[length-1]='\0' ;
if(strcmp(sp->sp_pwdp,crypt(passwd,salt)) == 0)
{
printf("passwd is %s\n" ,passwd);
break ;
}
else
printf("驗證失敗!\n");
}
return 0;
}
大致流程就是去讀shadow文件的內容, 然後根據salt ,和字典裏的密碼 進行crypt進行加密,如果加密結果和shadow 文件裏的一樣,那麼密碼就是對的。
這兩天參加hackathon , 和朋友一起做了個門禁系統, 有空就放個代碼和大家一起共享一下。