如何在 Linux 中使用 crypt() 方法?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15549591/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 22:30:21  来源:igfitidea点击:

how to use crypt( ) method in Linux?

clinuxunixcrypt

提问by user1198331

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

我只是想用来crypt()生成一个加密的密码,我写了一个调用该crypt()方法的演示。这是我的代码

#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?

我使用编译它"gcc tem.c -lcrypt',当我运行它时,一切似乎都正确,但出现了“段错误”。所以请告诉我这个简单的程序有什么问题?

采纳答案by Some programmer dude

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

如果您使用该标志进行编译,-Wall您就会明白为什么。

If you read the manual pageyou will see that it uses #define _XOPEN_SOURCEbefore including <unistd.h>. It should actually be defined before including anyheader.

如果您阅读手册页,您将看到它#define _XOPEN_SOURCE在包含<unistd.h>. 它实际上应该在包含任何标题之前定义。

If you don't define _XOPEN_SOURCEthen the cryptfunction 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 intand your printfexpects a string, so there will be a type mismatch that causes the crash.

如果您不定义,_XOPEN_SOURCE则该crypt函数将不会被原型化。然后编译器不知道实际的返回类型是什么,或者参数的类型和数量。所以它会假设函数返回一个int并且你printf期望一个字符串,所以会有一个导致崩溃的类型不匹配。

回答by teppic

You need this:

你需要这个:

#define _XOPEN_SOURCE

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

在源文件的顶部,在任何#include.

Alternatively compile with the gcc option -D_XOPEN_SOURCE.

或者使用 gcc 选项编译-D_XOPEN_SOURCE

回答by Mark Stanislav

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!

对我来说看起来不错!