公私钥转换成十六进制形式

     在一些情况下,我们需要将公私钥由pem格式转换成十六进制来提供给第三方进行使用,openssl没有提供命令行的转换方式,其中实现接口如下:

私钥转换为16进制为:

bool ConvertPriPEMtoHex(const std::string& pem_private_key, std::string& HexKey)
{
  EVP_PKEY *pri_key = NULL;
  BIO *bio_private_key = NULL;

  bio_private_key = BIO_new_mem_buf((char*)pem_private_key.c_str(), pem_private_key.size());
  PEM_read_bio_PrivateKey(bio_private_key, &pri_key, NULL, NULL);

  EC_KEY *ec_key = pri_key->pkey.ec;
  if (!ec_key)
    return false;

  BIGNUM *private_key;
  private_key = BN_new();
  private_key = (BIGNUM*)EC_KEY_get0_private_key(ec_key);

  HexKey = BN_bn2hex(private_key);

  BN_free(private_key);
  BIO_free(bio_private_key);

  return true;
}


公钥转换为16进制如下:

bool ConvertPubPEMtoHex(const std::string& pem_public_key, std::string& HexKey)
{
  EVP_PKEY *pri_key = NULL;
  BIO *bio_cert = NULL;
  X509 *encrypt_cert = NULL;
  EVP_PKEY *key = NULL;

  bio_cert = BIO_new_mem_buf((char *)pem_public_key.c_str(), pem_public_key.size());
  PEM_read_bio_X509(bio_cert, &encrypt_cert, NULL, NULL);

  if (!encrypt_cert)
    return false;

  key = X509_get_pubkey(encrypt_cert);
  if (!key)
    return false;

  EC_KEY *ec_key = key->pkey.ec;
  if (!ec_key)
    return false;

  EC_POINT *pub_key;
  unsigned char pubbuf[1024] = { 0 };
  pub_key = (EC_POINT*)EC_KEY_get0_public_key(ec_key);
  EC_GROUP* group = (EC_GROUP*)EC_KEY_get0_group(ec_key);
  int buflen = EC_POINT_point2oct(group, pub_key, EC_KEY_get_conv_form(ec_key), pubbuf, sizeof(pubbuf), NULL);

  BIGNUM *pub_key_BIGNUM;
  pub_key_BIGNUM = BN_new();
  BN_bin2bn(pubbuf, buflen, pub_key_BIGNUM);
  HexKey = BN_bn2hex(pub_key_BIGNUM);

  BN_free(pub_key_BIGNUM);
  BIO_free(bio_cert);

  return true;
}



你可能感兴趣的:(公私钥转换成十六进制形式)