How to Check a User Password on Linux
July 18, 2004, updated August 1, 2004
This example code will check a user password to see if it is the correct password for a given user. You'll need to link with the crypt lib in order for this to work.
#include <stdlib.h> #include <stdio.h> #include <pwd.h> #include <shadow.h> /** Grab the shadow password */ struct spwd *getspuid(uid_t pw_uid) { struct spwd *shadow; struct passwd *ppasswd; if( ((ppasswd = getpwuid(pw_uid)) == NULL) || ((shadow = getspnam(ppasswd->pw_name)) == NULL)) return NULL; return shadow; } /* given a plaintext password and an encrypted password, check if * they match; returns 1 if they match, 0 otherwise. */ int check_pass(const char *plainpw, const char *cryptpw) { return strcmp(crypt(plainpw,cryptpw), cryptpw) == 0; }
3 Comments