用到两个函数
void RC532setkey(RC532KEY key, int len, const unsigned char data, int rounds);
根据密钥计算密钥组 连同 轮次round 填充到key中 后面的加密解密都须要用的这个key
data:密钥 len:密钥长度 0到2040位 rounds:轮次 可选 8/12/16
void RC532ecbencrypt(const unsigned char in, unsigned char out, RC532KEY key, int enc);
in:输入 out:输出 key:RC532setkey中初始化好的 enc: 可选 RC5ENCRYPT(加密)/RC5DECRYPT(解密)
注意这个函数每次只能处理8字节的数据 加/解密时源数据顺序传入
#include <openssl/rc5.h>
#include <stdio.h>
#include <string>
#include <string.h>
int main()
{
RC5_32_KEY rckey;
unsigned char pwd[20] = {0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99, 0x10, 0xaa, 0xbb, 0xcc, 0xdd, 0xee, 0xff, 0xe1, 0xe2, 0xe3, 0xe4 };
RC5_32_set_key(&rckey, 20, pwd, RC5_8_ROUNDS);
std::string in = "accidfdsa测试dfd";
std::string strout = "";
std::string strjie = "";
char tempin[8];
char tempout[8];
// 加密
for(size_t i = 0; i < in.size(); i += 8)
{
if(i + 8 <= in.size())
memcpy(tempin, in.c_str()+i, 8);
else
{
memset(tempin, 0, 8);
memcpy(tempin, in.c_str()+i, in.size()-i);
}
RC5_32_ecb_encrypt((const unsigned char*)(tempin), (unsigned char*)tempout, &rckey, RC5_ENCRYPT);
strout.append(tempout, 8);
}
// 解密
for(size_t i = 0; i < strout.size(); i += 8)
{
if(i + 8 <= strout.size())
memcpy(tempin, strout.c_str()+i, 8);
else
{
memset(tempin, 0, 8);
memcpy(tempin, strout.c_str()+i, strout.size() - i);
}
RC5_32_ecb_encrypt((const unsigned char*)(tempin), (unsigned char*)tempout, &rckey, RC5_DECRYPT);
if(strjie.size() + 8 > in.size())
strjie.append(tempout, in.size() - strjie.size());
else
strjie.append(tempout, 8);
}
printf("-- %s", strjie.c_str());
return 0;
}
g++ -g -o main main.cpp -I/usr/include/openssl -lssl -lcrypto -L/usr/lib64
原文:http://blog.51cto.com/13611395/2085819