DES_ECB模式加密C++實現
阿新 • • 發佈:2019-01-25
貼一段程式碼,用的時候好找。
引數:明文陣列,明文長度,密文陣列,密文長度。
功能:加密。
#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;
}