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; }
附1:rsa密匙對生成
附 2:rsa秘鑰對在線格式轉換
附3:DES加解密 cbc模式 的簡單講解 && C++用openssl庫來實現的注意事項
附4:C++ 使用openssl庫實現 DES 加密——CBC模式 && RSA加密——公加私解——私加公解
