#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/types.h>
#include <pwd.h>
#include <shadow.h>
#include <string.h>
#define _XOPEN_SOURCE //using crypt function,we need define this
// The passwd structure is defined in <pwd.h> as follows:
//
// struct passwd {
// char *pw_name; /* username */
// char *pw_passwd; /* user password */
// uid_t pw_uid; /* user ID */
// gid_t pw_gid; /* group ID */
// char *pw_gecos; /* user information */
// char *pw_dir; /* home directory */
// char *pw_shell; /* shell program */
// };
// The shadow password structure is defined in <shadow.h> as follows:
//
// struct spwd {
// char *sp_namp; /* Login name */
// char *sp_pwdp; /* Encrypted password */
// long sp_lstchg; /* Date of last change
// (measured in days since
// 1970-01-01 00:00:00 +0000 (UTC)) */
// long sp_min; /* Min # of days between changes */
// long sp_max; /* Max # of days between changes */
// long sp_warn; /* # of days before password expires
// to warn user to change it */
// long sp_inact; /* # of days after password expires
// until account is disabled */
// long sp_expire; /* Date when account expires
// (measured in days since
// 1970-01-01 00:00:00 +0000 (UTC)) */
// unsigned long sp_flag; /* Reserved */
// };
int main(int argc, char *argv[])
{
char *user = NULL;
char *passwd_unencrypted = NULL;
int retval = 0;
while ((retval = getopt(argc, argv, "u:p:")) != -1)
{
switch (retval)
{
case 'u':user = strdup(optarg);break;
case 'p':passwd_unencrypted = strdup(optarg);break;
default:
printf("Usage:%s -u user -p passwd\n", argv[0]);
exit(EXIT_FAILURE);//diffent with _exit
}
}
if (user == NULL || passwd_unencrypted == NULL)
{
printf("Usage:%s -u user -p passwd\n", argv[0]);
exit(EXIT_FAILURE);
}
char *passwd = NULL;
char *key = passwd_unencrypted;
struct passwd *etc_passwd = getpwnam(user);//from /etc/passwd
if (etc_passwd)
{
if (etc_passwd->pw_passwd)
printf("pw_passwd: %s\n", etc_passwd->pw_passwd);
passwd = crypt(key, etc_passwd->pw_passwd);
if (passwd)
{
printf("password: %s\n", passwd);
if (strcmp(passwd, etc_passwd->pw_passwd) == 0)
printf("check password success\n");
}
}
struct spwd *shd = getspnam(user);//from /etc/shadow
if (shd)
{
printf("sp_pwdp: %s\n", shd->sp_pwdp);
passwd = crypt(key, shd->sp_pwdp);
if (passwd)
{
printf("password: %s\n", passwd);
if (strcmp(passwd, shd->sp_pwdp) == 0)
printf("check password success\n");
}
}
exit(EXIT_SUCCESS);
}
Linux下如何校验用户名和密码(使用crypt函数)
最新推荐文章于 2023-04-05 17:12:56 发布