#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 , 和朋友一起做了个门禁系统, 有空就放个代码和大家一起共享一下。