标签:因此 bcd key cin NPU 填充 补码 eof 而且
在项目中需要对一些关键信息进行传输,但又不能是明文,所以采用此种方式进行加密,另一端再进行解密。
AES: 算法
CBC: 模式
? 使用CBC模式,需要一个向量iv,可增加加密算法的强度
PKCS5: 补码方式
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <openssl/ssl.h>
#include <openssl/err.h>
#include <openssl/aes.h>
int base64_encode(char *in_str, int in_len, char *out_str)
{
BIO *b64, *bio;
BUF_MEM *bptr = NULL;
size_t size = 0;
if (in_str == NULL || out_str == NULL)
return -1;
b64 = BIO_new(BIO_f_base64());
bio = BIO_new(BIO_s_mem());
bio = BIO_push(b64, bio);
BIO_write(bio, in_str, in_len);
BIO_flush(bio);
BIO_get_mem_ptr(bio, &bptr);
memcpy(out_str, bptr->data, bptr->length-1);
out_str[bptr->length-1] = ‘\0‘;
size = bptr->length-1;
BIO_free_all(bio);
return size;
}
void aes_cbc_pcsk5_encrypt(char* pcInput, int nLen, char* pcOut)
{
char key[17] = "abcdefghijklmno";
char iv[17] = "1122334455667788";
char encrypt_string[1024] = { 0 };
AES_KEY aes;
int n = 0;
int nBei = nLen / AES_BLOCK_SIZE + 1;
int nTotal = nBei * AES_BLOCK_SIZE;
char *enc_s = (char*)malloc(nTotal);
int nNumber = 0;
printf("nBei=%d, nTotal=%d,nLen=%d\n",nBei, nTotal, nLen);
//KCS5Padding:填充的原则是,如果长度少于16个字节,需要补满16个字节,补(16-len)个(16-len)例如:
//"31325980"这个节符串是8个字节,16-8=8,补满后如:31325980+8个十进制的8
//如果字符串长度正好是16字节,则需要再补16个字节的十进制的16。
if (nLen % 16 > 0)
{
nNumber = nTotal - nLen;
printf("number=%d\n", nNumber);
}
else
{
nNumber = 16;
}
memset(enc_s, nNumber, nTotal);
memcpy(enc_s, pcInput, nLen);
printf("enc_s=%s\n", enc_s);
//设置加密密钥,16字节
if (AES_set_encrypt_key((unsigned char*)key, 128, &aes) < 0)
{
fprintf(stderr, "Unable to set encryption key in AES\n");
exit(-1);
}
AES_cbc_encrypt((unsigned char *)enc_s, (unsigned char*)encrypt_string, nTotal, &aes, (unsigned char*)iv, AES_ENCRYPT);
n = strlen(encrypt_string);
printf("encrypt_string n:%d, %ld\n", n, sizeof(encrypt_string));
base64_encode(encrypt_string, nTotal, pcOut);
n = strlen(pcOut);
printf("n:%d\n", n);
free(enc_s);
}
int main(int argc, char** argv)
{
char* input_string = "31325980";
char* input_string2 = "PZ884A16BB0020LA";
int nLen = strlen(input_string);
int nLen2 = strlen(input_string2);
char str2[1024] = { 0 };
char str3[1024] = { 0 };
printf("AES_BLOCK_SIZE=%d\n", AES_BLOCK_SIZE);
aes_cbc_pcsk5_encrypt(input_string, nLen, str2);
printf("%s\n", str2);
aes_cbc_pcsk5_encrypt(input_string2, nLen2, str3);
printf("%s\n", str3);
return 0;
}
void AES_cbc_encrypt(const unsigned char in, unsigned char out, size_t length, const AES_KEY key,unsigned char ivec, const int enc);
in: 表示加密前的明文;
out: 表示加密后的密文;
length: 明文的长度;
key: 加\解密密钥;
ivec:可读写的一块内存,一般长度为16字节;
? AES_cbc_encrypt在加密的过程中会修改ivec的内容,因此ivec参数不能是一个常量,而且不能在传递给加密函数后再立马传递给解密函数,必须重新赋值之后再传递给解密函数。
enc: AES_ENCRYPT表示加密,AES_DECRYPT表示解密;
标签:因此 bcd key cin NPU 填充 补码 eof 而且
原文地址:https://www.cnblogs.com/black-mamba/p/9397678.html