C++调用openssl库生成的秘钥对,通过传输传出来的只有秘钥的内容,没有秘钥的格式。而我们在调用openssl库加密解密时,传入的秘钥是需要包含格式的。C++调用openssl库需要的格式为pkcs#1, java默认的格式为pkcs#8。
//pkcs#1格式的私钥 64位分行 + 首尾标志 std::string formatPrivateKeyPKCS1(std::string priKey ) { std::string strPrivateKey = priKey; { //语句块作用:读取内存里生成的秘钥对,再从内存生成rsa int nPrivateKeyLen = strPrivateKey.size(); for(int i = 64; i < nPrivateKeyLen; i+=64) { if(strPrivateKey[i] != '\n') { strPrivateKey.insert(i, "\n"); } i++; } strPrivateKey.insert(0, "-----BEGIN RSA PRIVATE KEY-----\n"); strPrivateKey.append("\n-----END RSA PRIVATE KEY-----\n"); } return strPrivateKey; } //pkcs#1格式的公钥 64位分行 + 首尾标志 std::string formatPublicKeyPKCS1(std::string pubKey ) { std::string strPublicKey = pubKey; { //语句块作用:读取内存里生成的秘钥对,再从内存生成rsa int nPublicKeyLen = strPublicKey.size(); for(int i = 64; i < nPublicKeyLen; i+=64) { if(strPublicKey[i] != '\n') { strPublicKey.insert(i, "\n"); } i++; } strPublicKey.insert(0, "-----BEGIN RSA PUBLIC KEY-----\n"); strPublicKey.append("\n-----END RSA PUBLIC KEY-----\n"); } return strPublicKey; }