在C++下,我使用OPENSSL库生成了RSA的公私钥对与DES加密之用的会话密钥,并将这三者及加密结果写入文件以备在Java环境下使用。
在C++程序中,我使用使用公钥来加密了DES的会话密钥,然后在Java下使用私钥来解密会话密钥;在运算结果中,我未做其它方面的码制转换,即按密钥的初始格式DER编码,数学运算结果也是按DER编码来实现。
在Java程序中,我从之前所存储的几个文件中取得密钥与加密结果来做解密。我使用了BC的JCE,即bcprov-jdk14-119.jar,在使用之前,需要先安装此JCE:
假设JDK:jdk1.4\jre\
把BC包放到JRE下的ext:jdk1.4\jre\lib\ext
修改文件jdk1.4\jre\lib\security\java.security:
#
# List of providers and their preference orders (see above):
#
security.provider.1=sun.security.provider.Sun
security.provider.2=com.sun.net.ssl.internal.ssl.Provider
security.provider.3=com.sun.rsajca.Provider
security.provider.4=com.sun.crypto.provider.SunJCE
security.provider.5=sun.security.jgss.SunProvider
security.provider.6=org.bouncycastle.jce.provider.BouncyCastleProvider
======================================================================
C++程序源码:
#include
#include
#include
//#define _RSA_KEY_PAIR_GENERATE_//密钥是否要生成 只需要在第一次运行时打开此宏
#define _RSA_KEY_PAIR_TOFILE_//密钥对是否要写入文件
#define MAX_RSA_KEY_LENGTH 512 //密钥的最大长度是512字节
#define PUBKEY_ENCRYPT
#define PRIKEY_DECRYPT
#pragma comment(lib, "../lib/libeay32.lib")
static const char * PUBLIC_KEY_FILE = "pubkey.key";
static const char * PRIVATE_KEY_FILE = "prikey.key";
int RsaKeyPairGen(void)
{
RSA *rsa = NULL;
#ifdef _RSA_KEY_PAIR_GENERATE_
//生成RSA密钥对:
rsa = RSA_new();
rsa = RSA_generate_key(1024, 0x10001, NULL, NULL);
#endif
//把密钥对写入文件,以后从文件里读取
#ifdef _RSA_KEY_PAIR_TOFILE_
unsigned char ucPubKey[MAX_RSA_KEY_LENGTH] = {0}, ucPriKey[MAX_RSA_KEY_LENGTH] = {0};
int len = i2d_RSAPublicKey(rsa,NULL);
unsigned char* pt = ucPubKey;
len = i2d_RSAPublicKey(rsa, &pt);
FILE *fpubkey = NULL;
fpubkey = fopen(PUBLIC_KEY_FILE, "wb");
if(fpubkey == NULL)
{
cout << "fopen pubkey.key failed!" << endl;
return 0x01;
}
fwrite(ucPubKey, 1, len, fpubkey);
fclose(fpubkey);
len = i2d_RSAPrivateKey(rsa,NULL);
unsigned char* pt2 = ucPriKey;
len = i2d_RSAPrivateKey(rsa,&pt2);
FILE *fprikey = NULL;
fprikey = fopen(PRIVATE_KEY_FILE, "wb");
if(fprikey == NULL)
{
cout << "fopen prikey.key failed!" << endl;
return 0x02;
}
fwrite(ucPriKey, 1, len, fprikey);
fclose(fprikey);
#endif
if(rsa != NULL)
{
RSA_free(rsa);
rsa = NULL;
}
return 0;
}
//从文件里读取私钥的数据,取得RSA格式的私钥:
int GetPriKey(unsigned char *pucPriKeyData, unsigned long KeyDataLen, RSA* *priRsa)
{
unsigned char *Pt = pucPriKeyData;
*priRsa = d2i_RSAPrivateKey(NULL, &Pt,