how to use crypt( ) method in Linux?
Asked Answered
C

3

6

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?

Cerelia answered 21/3, 2013 at 13:58 Comment(0)
S
12

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.

Seel answered 21/3, 2013 at 14:7 Comment(3)
The #define has to come before any library header - it's a glibc requirement.Alchemize
No that's a POSIX requirement.Lula
@R.. Well, the glibc documentation states it as a requirement, it doesn't reference POSIX compliance in that.Alchemize
A
5

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.

Alchemize answered 21/3, 2013 at 14:4 Comment(0)
G
3

Looks like it could be related to crypto library support.

Try adding:

#include <crypt.h>

[mstanislav@pardalislabs ~]$ gcc tem.c -lcrypt
[mstanislav@pardalislabs ~]$ ./a.out  
abFZSxKKdq5s6

Looks good for me!

Glimp answered 21/3, 2013 at 14:4 Comment(3)
according to the man page crypt.h should be included for crypt_r(), just unistd.h should be enought for crypt()Ancilin
In my testing, I received the segmentation fault that you did with your code. After adding the include as above, it works. Are you stating the fix didn't fix your testing, or just that you believe it shouldn't need my solution?Glimp
A) I'm not the poster, just a casual observer. B) I'm saying, IMO, I don't like adding extra header files when they are not required, and (as stated in the documentation for crypt()) as long as you have the functional macro, then that header file is not required.Ancilin

© 2022 - 2024 — McMap. All rights reserved.