#include "openssl/evp.h"
#include "openssl/pem.h"
bool Key::readDataFromPEMFile(const std::string& filePath)
{
ifstream fin(filePath, std::fstream::in | std::fstream::binary);
if (!fin.is_open()) {
cout << "open file " << filePath << "error." << endl;
return false;
}
unsigned char keyData[1024 * 3] = { 0 };
unsigned char buf = 0;
unsigned long totalSize = 0;
while (fin.read((char*)&buf, 1)) {
// int cnt_bytes = fin.gcount(); //查看刚才读取了多少字节
memcpy(keyData + totalSize, &buf, 1);
totalSize += 1;
}
fin.close();
std::shared_ptr<EC_KEY> ecKey;
std::shared_ptr<BIO> bioMem(BIO_new(BIO_s_mem()), [&](BIO* p) { BIO_free(p); });
BIO_write(bioMem.get(), keyData, totalSize);
std::shared_ptr<EVP_PKEY> evpPKey(PEM_read_bio_PrivateKey(bioMem.get(), NULL, NULL, NULL), [](EVP_PKEY* p) { EVP_PKEY_free(p); });
if (!evpPKey) {
cout << "init evpkey failed." << endl;
return false;
}
ecKey.reset(EVP_PKEY_get1_EC_KEY(evpPKey.get()), [](EC_KEY* p) { EC_KEY_free(p); });
//私钥数据
std::shared_ptr<const BIGNUM> ecPrivateKey(EC_KEY_get0_private_key(ecKey.get()), [](const BIGNUM*) {});
unsigned char priOctet[32] = { 0 };
BN_bn2bin(ecPrivateKey.get(), priOctet);
//公钥数据
std::shared_ptr<const EC_GROUP> ecGroup(EC_KEY_get0_group(ecKey.get()), [](const EC_GROUP*) {});
std::shared_ptr<const EC_POINT> ecPubKey(EC_KEY_get0_public_key(ecKey.get()), [](const EC_POINT*) {});
unsigned char pubOctet[65] = { 0 };
EC_POINT_point2oct(ecGroup.get(), ecPubKey.get(), POINT_CONVERSION_UNCOMPRESSED, pubOctet, sizeof(pubOctet), nullptr);
m_privateKey = std::shared_ptr<const vector<unsigned char>>(new const vector<unsigned char>((unsigned char*)priOctet, (unsigned char*)priOctet + sizeof(priOctet)));
m_publicKey = std::make_shared<const std::vector<unsigned char>>((unsigned char*)pubOctet + 1, (unsigned char*)pubOctet + sizeof(pubOctet));
return true;
}
使用openssl读取pem文件解析得到公私钥的二进制格式数据
最新推荐文章于 2024-06-03 19:47:07 发布