使用第三方RSAEuro的开源代码RSA算法加密数据

 近期做程序,需要用到可信数据传输,进而想到了非对称加密,虽然懂得数学原理,但自己实现起来太过繁琐,且不能保证效率,所以在网上搜索成品,无奈废品太多,好在找到一个名叫RSAEuro的开源代码,包含了RSA和MD5实现,经过整理可以使用,在此做个记录。

此代码有如下特点:

1.知道解密结果是否正确(省去了在数据里加校验和)

2.知道解密后的数据大小(省去了在数据里标明大小)

3.在用公钥加密数据时用到了随机数,即每次加密相同的数据结果都不一样(省去了在数据里随机数)

4.公钥加密私钥解密,私钥加密公钥解密(一对密钥即可相互传输数据)

5.支持512/1024/2048三种级别的加密

示例代码:

生成密钥对 需要引入 #include "RSAEuro/rsaeuro.h"

[cpp] view plain copy
R_RSA_PUBLIC_KEY PubKey;
R_RSA_PRIVATE_KEY PriKey;
R_RANDOM_STRUCT RandSt;
R_RSA_PROTO_KEY ProKey;

//生成密钥对
R_RandomCreate(&RandSt);
ProKey.bits = 1024;//512 or 1024 or 2048
ProKey.useFermat4 = 1;
R_GeneratePEMKeys(&PubKey, &PriKey, &ProKey, &RandSt);

一对密钥相互加解密
[cpp] view plain copy
//公钥加密私钥解密
char *TestBuffer = "Hello!Sid!!!";
{
unsigned char EncryptBuffer[128] = {0};
unsigned char DecryptBuffer[128] = {0};
unsigned int InputLen = sizeof(EncryptBuffer);
unsigned int OutputLen = sizeof(DecryptBuffer);

R_RandomCreate(&RandSt);
RSAPublicEncrypt(EncryptBuffer, &InputLen, (unsigned char*)TestBuffer, strlen(TestBuffer), &PubKey, &RandSt);
RSAPrivateDecrypt(DecryptBuffer, &OutputLen, EncryptBuffer, InputLen, &PriKey);
printf("Test1:%s\n", DecryptBuffer);
}
//私钥加密公钥解密
{
unsigned char EncryptBuffer[128] = {0};
unsigned char DecryptBuffer[128] = {0};
unsigned int InputLen = sizeof(EncryptBuffer);
unsigned int OutputLen = sizeof(DecryptBuffer);

RSAPrivateEncrypt(EncryptBuffer, &InputLen, (unsigned char*)TestBuffer, strlen(TestBuffer), &PriKey);
RSAPublicDecrypt(DecryptBuffer, &OutputLen, EncryptBuffer, InputLen, &PubKey);
printf("Test2:%s\n", DecryptBuffer);
}

输出密钥数据到文件中
[cpp] view plain copy
if (FILE *f = fopen("pub.key", "wb"))
{
fwrite(&PubKey, sizeof(PubKey), 1, f);
fclose(f);
}
if (FILE *f = fopen("pri.key", "wb"))
{
fwrite(&PriKey, sizeof(PriKey), 1, f);
fclose(f);
}

读取key文件并做加密测试
[cpp] view plain copy
int _tmain(int argc, _TCHAR* argv[])
{
R_RSA_PUBLIC_KEY PubKey;
R_RSA_PRIVATE_KEY PriKey;

if (FILE *f = fopen("pub.key", "rb"))
{
fread(&PubKey, sizeof(PubKey), 1, f);
fclose(f);
}
if (FILE *f = fopen("pri.key", "rb"))
{
fread(&PriKey, sizeof(PriKey), 1, f);
fclose(f);
}
//
char *TestBuffer = "Hello!Sid!!!";
{
unsigned char EncryptBuffer[128] = {0};
unsigned char DecryptBuffer[128] = {0};
unsigned int InputLen = sizeof(EncryptBuffer);
unsigned int OutputLen = sizeof(DecryptBuffer);

RSAPrivateEncrypt(EncryptBuffer, &InputLen, (unsigned char*)TestBuffer, strlen(TestBuffer), &PriKey);
RSAPublicDecrypt(DecryptBuffer, &OutputLen, EncryptBuffer, InputLen, &PubKey);
printf("Test2:%s\n", DecryptBuffer);
}
getchar();
return 0;
}

也可以把这两个结构体数据以字节数组的方式写在代码中
另外我还精简出了一份代码,不使用任何os api,可以方便的移植到内核模块或者其他平台,但不能生成密钥对、不能使用公钥加密

好吧我懒了,其实就是没找到time、clock、gmtime在windows内核中的替代函数而已

需要注意的是,每次加密的数据大小不能超过(位数/8)-11字节

以1024加密为例,1024bit=128byte,每次能把不超过117字节的数据加密为128字节的数据

最后附上下载地址:

http://download.csdn.net/detail/sidyhe/7872799

发表回复

您的电子邮箱地址不会被公开。 必填项已用*标注