贴一段代码,用的时候好找。
参数:明文数组,明文长度,密文数组,密文长度。
功能:加密。
#include "stdio.h"
#include "stdlib.h"
#include "string.h"
#include "openssl/des.h"
//des-ecb加密方式;
//8位密钥,不足8位的右补0x00;
//加密内容8位补齐,补齐方式为:少1位补一个0x01,少2位补两个0x02,...
//本身已8位对齐的,后面补八个0x08。
int desEncrypt(char *clearText,int clearTextLen,char *cipherText,int *cipherTextLen)
{
int docontinue = 1;
int data_len;
int data_rest;
unsigned char ch;
unsigned char *src = NULL;
unsigned char *cipherText1=NULL;
int len;
unsigned char tmp[8];
unsigned char in[8];
unsigned char out[8];
char *k = "liguangy";
int key_len;
#define LEN_OF_KEY 8
unsigned char key[LEN_OF_KEY];
unsigned char block_key[9];
DES_key_schedule ks;
key_len = strlen(k);
memcpy(key, k, key_len);
memset(key + key_len, 0x00, LEN_OF_KEY - key_len);
data_len = strlen(clearText);
data_rest = data_len % 8;
len = data_len + (8 - data_rest);
//ch是用来补齐的字符
ch = 8 - data_rest;
src = (unsigned char *)malloc(len);
cipherText1= (unsigned char *)malloc(128);
if (NULL == src)
{
docontinue = 0;
}
if (docontinue)
{
int count;
int i;
memset(src, 0, len);
memcpy(src, clearText, data_len);
memset(src + data_len, ch, 8 - data_rest);
memset(block_key, 0, sizeof(block_key));
memcpy(block_key, key + 0, 8);
DES_set_key_unchecked((const_DES_cblock*)block_key, &ks);
printf("before encrypt:\n");
for (i = 0; i < len; i++)
{
printf("%d ", *(src + i));
}
printf("\n");
count = len / 8;
for (i = 0; i < count; i++)
{
memset(tmp, 0, 8);
memset(in, 0, 8);
// memset(out, 0, 8);
memcpy(tmp, src + 8 * i, 8);
DES_ecb_encrypt((const_DES_cblock*)tmp, (DES_cblock*)in, &ks,DES_ENCRYPT);
memcpy(cipherText + 8 * i, in, 8);
}
*cipherTextLen=strlen(cipherText);
memcpy(cipherText1,cipherText,*cipherTextLen);
printf("after encrypt :\n");
for (i = 0; i < *cipherTextLen; i++)
{
printf("%.2X ", *(cipherText1 + i));
}
printf("\n");
}
if (NULL != src)
{
free(src);
src = NULL;
}
return 0;
}
int main(void)
{
char data[128]="123456";
int dataLen=strlen(data);
char cipherText[128]={0};
int cipherTextLen=0;
unsigned char text[128];
desEncrypt(data,dataLen,cipherText,&cipherTextLen);
memcpy(text, cipherText, cipherTextLen);
printf("%d\n",cipherTextLen);
printf("after encrypt :\n");
for (int i = 0; i < cipherTextLen; i++)
{
printf("%.2X ", *(text + i));
}
printf("\n");
return 0;
}