我需要加密私钥(长度为118个字节)aes-128-cbc
并使用PEM
库以OpenSSL
格式写入。
好像即将完成的那样。
加密私钥的总长度太小,看起来像:
nTrb9AN15PVFbZfqPdwKAQ
整个PEM
输出如下:
"-----BEGIN EC PRIVATE KEY-----\nProc-Type: 4,ENCRYPTED\nDEK-Info: AES-128-CBC,643CAFB443D381CC08BA709550DDCD38\n\nnTrb9AN15PVFbZfqPdwKAQ==\n-----END EC PRIVATE KEY-----\n\xad"
主要部分 - 加密私钥(nTrb9AN15PVFbZfqPdwKAQ
)应该更长,像那样:
bqYK4AY8zxun9IkYIevsC6ix/1KO6LNTpWZZEoLMK2FiaESKY6nTfBZTP5Xbw6yJ
tljlBqRXaoRA0QdlE2DyeX/Hs/tiAzcgwogV1qlGqlPu3KsSSjNmtpfAiNyKXLGI
+2xxUrAHT9a5bulabtTMI1avVP/bNUqjrJwssY2FVW8=
我用c ++代码生成pem。
//generate key from private first
void () {
EC_KEY* key = EC_KEY_new_by_curve_name(NID_secp256k1);
//set flag
EC_KEY_set_asn1_flag(key, OPENSSL_EC_NAMED_CURVE);
//generate key
generateECKeyFromPrivate(key, sourceData, sourceSize);
//define cipher
const EVP_CIPHER* evpCipher = EVP_aes_128_cbc();
//bio
BIO *bufferB = BIO_new(BIO_s_mem());
char *pemholder = static_cast<char*>(calloc(600, sizeof(char)));
BUF_MEM *buf = BUF_MEM_new();
PEM_write_bio_ECPrivateKey(bufferB, key, evpCipher, NULL, 0, NULL, userPassword);
BIO_get_mem_ptr(bufferB, &buf);
memcpy(pemholder, buf->data, 600);
}
bool generateECKeyFromPrivate(EC_KEY *key, const unsigned char *privBytes, int priveBytesLength) {
//private bignum part
BIGNUM *privPart = BN_new();
BN_bin2bn(privBytes, priveBytesLength, privPart);
bool success = false;
BN_CTX *ctx = NULL;
EC_POINT *pub_key = NULL;
const EC_GROUP *group = EC_KEY_get0_group(key);
if ((ctx = BN_CTX_new())) {
if ((pub_key = EC_POINT_new(group))) {
if (EC_POINT_mul(group, pub_key, privPart, NULL, NULL, ctx)) {
if (EC_KEY_set_private_key(key, privPart)) {
if (EC_KEY_set_public_key(key, pub_key)) {
success = true;
}
}
}
}
}
if (pub_key) EC_POINT_free(pub_key);
if (ctx) BN_CTX_free(ctx);
return success;
}
无法弄清楚如何解决这个问题。