crypt()函数可以加密8个字节的数据,提供2字节的扰码,返回一个指向13个ASCII字符串的指针。
#include "crypt.h" //
没有此行每次计算crypt()都会返回不同的int值
#include "unistd.h"
char *crypt(const char *key, const char
*salt);
写个名为“des.c”的测试crypt()函数的文件,内容如下:
#include "stdio.h"
#include "crypt.h"
// crypt() will return
different int without this line
#include
"unistd.h"
int main()
{
printf(" * DES(%s) = %s\n", "test",
crypt("test", "test"));
return 0;
}
编译并测试:
qige@ubuntu:~$ gcc -o des
des.c -lcrypt
qige@ubuntu:~$
./des
*
DES(test) = teH0wLIpW0gyQ
qige@ubuntu:~$
改进后的“des.c”文件内容:
#include
"stdio.h"
#include
"string.h"
#include
"crypt.h"
#include
"unistd.h"
typedef unsigned char
uchar;
typedef unsigned int
uint;
void print_cli_help(char
*self);
int main()
{
uint _c, _help = 0;
uchar key[8] = { 0 }, salt[2] = { 0 },
passwd[13] = { 0 };
while((_c = getopt(argc, argv, "s:h")) != -1)
{
switch(_c)
{
case 's':
snprintf(key, sizeof(key), "%s",
optarg);
salt[0] = key[0]; salt[1] = key[1];
break;
case 'h':
default:
_help = 1;
break;
}
}
if (_help > 0 || argc
<= 1) {
print_cli_help(argv[0]);
return
0;
}
printf(" * DES(%s) = %s\n", key, crypt(key,
salt));
return 0;
}
void print_cli_help(char
*self)
{
printf("Compile: gcc -o %s *.c\n",
self);
printf(" Usage: %s [ -k
key_string] [-h]\n", self);
printf(" Typical: %s -s test\n",
self);
}
编译Makefile文件,内容如下(使用时请务必将“gcc”和“rm”前的4个空格替换为一个Tab,即“\t”):
# Qige @
2015.12.01
all: des
des: *.c
gcc -o $@ $^ -lcrypt
clean:
rm -f des
编译并测试:
qige@ubuntu:~$ make
qige@ubuntu:~$ ./des -s test
* DES(test) =
teH0wLIpW0gyQ
qige@ubuntu:~$ ./des -h
Compile: gcc -o ./des *.c
Usage: ./des [-k string]
[-h]
Typical: ./des -s test
qige@ubuntu:~$