Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to use crypt( ) method in Linux?

Tags:

c

linux

unix

crypt

I just want to use crypt() to generate an encrypted password,and I write a demo which invoke the crypt() method. Here is my code

#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>

int main()
{
    printf("%s\n",crypt("abc","ab"));
    exit(0);
}

I compile it using "gcc tem.c -lcrypt' and when I run it, everything seems right, but a "segment error" shows up. so please tell me what's wrong with this simple program?

like image 237
user1198331 Avatar asked Mar 21 '13 13:03

user1198331


People also ask

How do you use the crypt function?

Use the crypt Function to Hash Passphrases for Storagecrypt takes two char* arguments passed as const qualified parameters. The first argument points to the passphrase that needs to be hashed, and the second one is the special string called setting , that should be generated using the crypt_gensalt function.

What is Linux crypt?

crypt() is the password encryption function. It is based on the Data Encryption Standard algorithm with variations intended (among other things) to discourage use of hardware implementations of a key search. key is a user's typed password. salt is a two-character string chosen from the set [a-zA-Z0-9./].

How passwords are encrypted in Linux?

Most Unicies (and Linux is no exception) primarily use a one-way encryption algorithm, called DES (Data Encryption Standard) to encrypt your passwords. This encrypted password is then stored in (typically) /etc/passwd (or less commonly) /etc/shadow.


2 Answers

If you compile with the flag -Wall you will see why.

If you read the manual page you will see that it uses #define _XOPEN_SOURCE before including <unistd.h>. It should actually be defined before including any header.

If you don't define _XOPEN_SOURCE then the crypt function will not be prototyped. Then the compiler doesn't know what the actual return type is, or the types and number of arguments. So it will assume that the function returns an int and your printf expects a string, so there will be a type mismatch that causes the crash.

like image 178
Some programmer dude Avatar answered Sep 18 '22 11:09

Some programmer dude


You need this:

#define _XOPEN_SOURCE

at the top of your source file, before any #include.

Alternatively compile with the gcc option -D_XOPEN_SOURCE.

like image 24
teppic Avatar answered Sep 19 '22 11:09

teppic