基于openssl的aes_ecb加解密

1 篇文章 0 订阅

aes

AES五种加密模式(CBC、ECB、CTR、OCF、CFBecb是aes加密的多种模式中的一种, 这种模式是将整个明文分成若干段相同的小段,然后对每一小段进行加密。

基于openssl的aes_ecb加密

int32_t Encrypt(const string& content, string& strOut)
{
	int len = content.length() / 16 + 1;
	byte userkey[16] = { 1, 2, 3, 4, 6, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 2};
	
	char* data = (char*)malloc(AES_BLOCK_SIZE * len);
	unsigned char* cipher = (unsigned char*)malloc(AES_BLOCK_SIZE * len + 33);
	unsigned char* plain = (unsigned char*)malloc(AES_BLOCK_SIZE * len);
	AES_KEY key;
	memset((void*)data, 0, AES_BLOCK_SIZE * len);
	memset((void*)cipher, 0, AES_BLOCK_SIZE * len + 33);
	memset((void*)plain, 0, AES_BLOCK_SIZE * len);
	strcpy_s(data, AES_BLOCK_SIZE * len, content.c_str());

	/*aes (key,content)*/
	AES_set_encrypt_key(userkey, 256, &key);
	for (int i = 0; i < len; i++) //每次加密16个字节
		AES_ecb_encrypt((byte*)(data + i * AES_BLOCK_SIZE), cipher + i * AES_BLOCK_SIZE, &key, AES_ENCRYPT);
	strOut = cipher ;
	free(data);
	free(cipher);
	free(plain);
	return 0;
}

基于openssl的aes_ecb解密

int32_t Decode(const string& strSrc, string& res)
{
	byte userkey[16] = { 1, 2, 3, 4, 6, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 2}; //解密密钥与加密密钥相同
	auto pres = new char[strSrc.length()];
	memset(pres, '\0', strSrc.length());
	AES_KEY key;
	AES_set_decrypt_key(userkey, 256, &key);
	for (int32_t i = 0; i < (strSrc.length()/16); i++)
		AES_ecb_encrypt((byte*)(strSrc.c_str() + i * AES_BLOCK_SIZE), (byte*)(pres + i * AES_BLOCK_SIZE), &key, AES_DECRYPT);
	res = string(pres);
	delete[] pres;
	return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值