I had been solving the same task recently. Here is an example of C function (link with -lcrypt). Note that you need to have read permissions for files /etc/passwd and /etc/shadow.
#include <sys/types.h>
#include <pwd.h>
#include <shadow.h>
#include <crypt.h>
#include <string.h>
#include <stdio.h>
/// @return 0 - password is correct, otherwise no
int CheckPassword( const char* user, const char* password )
{
struct passwd* passwdEntry = getpwnam( user );
if ( !passwdEntry )
{
printf( "User '%s' doesn't exist\n", user );
return 1;
}
if ( 0 != strcmp( passwdEntry->pw_passwd, "x" ) )
{
return strcmp( passwdEntry->pw_passwd, crypt( password, passwdEntry->pw_passwd ) );
}
else
{
// password is in shadow file
struct spwd* shadowEntry = getspnam( user );
if ( !shadowEntry )
{
printf( "Failed to read shadow entry for user '%s'\n", user );
return 1;
}
return strcmp( shadowEntry->sp_pwdp, crypt( password, shadowEntry->sp_pwdp ) );
}
}
login
program. – Manta