encrypt函数用法详解
encrypt函数简介
- 头文件包含
#include <unistd.h>
#include <stdlib.h>
- 函数定义
void encrypt(char block [64], int edflag );
void setkey(const char * key );
#include <crypt.h>
void setkey_r(const char * key , struct crypt_data * data );
void encrypt_r(char * block , int edflag \
encrypt函数常见使用错误
- 编译错误
warning: implicit declaration of function ‘encrypt’ [-Wimplicit-function-declaration]
解决办法:包含头文件
#include <unistd.h>
#include <stdlib.h>
encrypt函数详细描述
这些函数对64位消息进行加密和解密。setkey ()函数设置encrypt ()使用的键。这里使用的key参数是一个64字节的数组,每个字节都有数值1或0。其中n=8*i-1的字节key【n】被忽略,因此有效的key长度是56位。
encrypt ()函数修改传递的缓冲区,如果edflag为0,则进行编码,如果传递的是1,则进行解码。与key参数一样,block也是编码的实际值的位向量表示。结果以相同的向量返回。
这两个函数是不可重入的,即关键数据保存在静态存储中。函数setkey_r ()和encrypt_r ()是可重入版本。它们使用以下结构来保存关键数据:
struct crypt_data {
char keysched[16 * 8];
char sb0[32768];
char sb1[32768];
char sb2[32768];
char sb3[32768];
char crypt_3_buf[14];
char current_salt[2];
long current_saltbits;
int direction;
int initialized;
};
在调用setkey_r ()之前,将data->initialized设置为零。
encrypt函数返回值
这些函数不返回任何值。
encrypt函数错误码
在调用上述函数之前,将errno设置为零。一旦成功,它是不变的。
- ENOSYS 未提供该函数。(例如,因为美国以前的出口限制。)
encrypt函数其他说明
Availability in glibc参见glibc 2.2中的crypt (3) Features in glibc,这些函数使用DES算法。
encrypt函数使用举例
#define _XOPEN_SOURCE
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <crypt.h>
int
main(void)
{
char key[64];
char orig[9] = "eggplant";
char buf[64];
char txt[9];
for (int i = 0; i < 64; i++) {
key[i] = rand() & 1;
}
for (int i = 0; i < 8; i++) {
for (int j = 0; j < 8; j++) {
buf[i * 8 + j] = orig[i] >> j & 1;
}
setkey(key);
}
printf("Before encrypting: %s\en", orig);
encrypt(buf, 0);
for (int i = 0; i < 8; i++) {
for (int j = 0, txt[i] = \(aq\e0\(aq; j < 8; j++) {
txt[i] |= buf[i * 8 + j] << j;
}
txt[8] = \(aq\e0\(aq;
}
printf("After encrypting: %s\en", txt);
encrypt(buf, 1);
for (int i = 0; i < 8; i++) {
for (int j = 0, txt[i] = \(aq\e0\(aq; j < 8; j++) {
txt[i] |= buf[i * 8 + j] << j;
}
txt[8] = \(aq\e0\(aq;
}
printf("After decrypting: %s\en", txt);
exit(EXIT_SUCCESS);
}
评论区