- 论坛徽章:
- 0
|
这几天一直在找c++ 中openssl rsa 加密的方法,但是弄了好多,都无法对应上java 端的解密。
如下有java的加密流程:
public static String encrypt(String source, String publicKey, String input_charset)
throws Exception {
Key key = getPublicKey(publicKey);
/** 获取Cipher对象 */
Cipher cipher = Cipher.getInstance(" RSA/ECB/PKCS1Padding");
cipher.init(Cipher.ENCRYPT_MODE, key);
if (CommonUtil.isNull(input_charset)) {
input_charset = "utf-8";
}
byte[] b = source.getBytes(input_charset);
/** 加密 */
byte[] b1 = cipher.doFinal(b);
String encoded = Base64.encode(b1);
return encoded;
}
自己使用c++模拟java的加密方法:
const std::string tools::EncodeRSAKey(const std::string& strPublicKey, const std::string& strData)
{
if (strPublicKey.empty() || strData.empty())
{
assert(false);
return "";
}
std::string strRet;
RSA* pRSAPublicKey;
int p_len = strPublicKey.size();
std::string strPublicKeyTemp = strPublicKey;
for(int i = 64; i < p_len; i+=64)
{
if(strPublicKeyTemp[i] != '\n')
{
strPublicKeyTemp.insert(i, "\n");
}
i++;
}
strPublicKeyTemp.insert(0, "-----BEGIN PUBLIC KEY-----\n");
strPublicKeyTemp.append("\n-----END PUBLIC KEY-----\n");
BIO* p_bio = BIO_new_mem_buf((void*)strPublicKeyTemp.c_str(), -1);
pRSAPublicKey = PEM_read_bio_RSA_PUBKEY(p_bio, NULL, 0, NULL);
if ( pRSAPublicKey == NULL )
{
return "";
}
int nLen = RSA_size(pRSAPublicKey);
char* pEncode = new char[nLen + 1];
int ret = RSA_public_encrypt(nLen - 11, (const unsigned char*)strData.c_str(), (unsigned char*)pEncode, pRSAPublicKey, RSA_PKCS1_PADDING);
if (ret >= 0)
{
strRet = std::string(pEncode, ret);
}
delete[] pEncode;
CRYPTO_cleanup_all_ex_data();
// 进行base 64加密
string strEncodeOut;
if (!tools::b64Encode((unsigned char *)strRet.c_str(), strRet.size(), strEncodeOut))
{
RSA_free(pRSAPublicKey);
return "";
}
RSA_free(pRSAPublicKey);
return strEncodeOut;
}
自己在c++中进行解密成功,但是在java中还是无法解密,哪位大神有此类的经验,请赐教赐教!多谢了! |
|