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;
}

Related Posts

3 Comments

Comment September 16, 2010 by elito
PLEASE TELL ME WHERES IS THE crypt lib ???????
Comment December 2, 2011 by Tim
/usr/lib/libcrypt.so
Comment April 15, 2014 by creatorb
how do i check my password? i'm root