Hi,
Here is what i did in Perl..It works perfect for me.See if it helps you.Try calling these Perl subroutines from your program.
-------------------------------------------------------
my $shadowFile = "/etc/shadow";
my $oldpasswdFile = "$passwdFile.old";
#write logintest11:ZCr0cYGXAmhI2:501:100:LoginUser:/home/logintest11:
sub writeToShadow {
$shParam1 = &getNumDays();
$shParam2 = 0;
$shParam3 = 99999;
$shParam4 = 7;
$shParam5 = -1;
$shParam6 = -1;
$shParam7 = 134537898;
$encryptedPasswd = &encryptmd5Passwd($password);
$tmpShadowFile = $shadowFile.".$$";
system("cp -f $shadowFile $tmpShadowFile"

;
open(SFH,$shadowFile);
open(TSFH,">>$tmpShadowFile"

;
flock(SFH,1);
if(&detectmd5()) {
$encryptedPasswd = &encryptmd5Passwd($password);
}
else {
$encryptedPasswd = &encryptedPasswd($password);
}
print TSFH "$userName:$encryptedPasswd:$shParam1:$shParam2:$shParam3:$shParam4:$shParam5:$shParam6:$shParam7\n";
close(TSFH);
close(SFH);
system("cp -f $tmpShadowFile $shadowFile"

;
system("rm -f $tmpShadowFile"

;
}
#encrypt a plain text passwd as an md5 passwd
sub encryptmd5Passwd {
local $password = $_[0];
local(@saltset)=('a'..'z','A'..'Z','0'..'9','.','/');
my $now = time;
srand ($now);
for($i=0;$i<8;$i++)
{
my $random = int(rand(65));
push(@randarr,$random);
}
for($i=0;$i<8;$i++)
{
$salt .= $saltset[$randarr[$i]];
}
return crypt($password,"\$1\$$salt\$"

;
}
#Detect if we have MD5 or not..
sub detectmd5 {
my($md5flag,$passwdFile);
$md5flag = 0;
if(-e "/etc/shadow"

{
$passwdFile ="/etc/shadow";
}
else {
$passwdFile = "/etc/passwd";
}
open(PFH,"$passwdFile"

;
flock(PFH,1);
while(<PFH>) {
if($_ =~ /\$/) {
$md5flag =1;
}
}
close(PFH);
return $md5flag;
}