//------------------------------------------------------------------------------------- KBEKey::KBEKey(const std::string& pubkeyname, const std::string& prikeyname): KBE_RSA() { if(pubkeyname.size() > 0 || prikeyname.size() > 0) { KBE_ASSERT(pubkeyname.size() > 0); if(g_componentType != CLIENT_TYPE) { KBE_ASSERT(prikeyname.size() > 0); bool key1 = loadPrivate(prikeyname); bool key2 = loadPublic(pubkeyname); KBE_ASSERT(key1 == key2); if(!key1 && !key2) { bool ret = generateKey(pubkeyname, prikeyname); KBE_ASSERT(ret); key1 = loadPrivate(prikeyname); key2 = loadPublic(pubkeyname); KBE_ASSERT(key1 && key2); } } else { bool key = loadPublic(pubkeyname); KBE_ASSERT(key); } } }
//------------------------------------------------------------------------------------- bool KBE_RSA::generateKey(const std::string& pubkeyname, const std::string& prikeyname, int keySize, int e) { KBE_ASSERT(rsa_public == NULL && rsa_private == NULL); RSA* rsa = NULL; FILE *fp = NULL; if ((rsa = RSA_generate_key(keySize, e, NULL, NULL)) == NULL) { ERR_load_crypto_strings(); char err[1024]; char* errret = ERR_error_string(ERR_get_error(), err); ERROR_MSG(fmt::format("KBE_RSA::generateKey: RSA_generate_key error({} : {})\n", errret, err)); return false; } if (!RSA_check_key(rsa)) { ERROR_MSG("KBE_RSA::generateKey: invalid RSA Key.\n"); RSA_free(rsa); return false; } fp = fopen(prikeyname.c_str(), "w"); if (!fp) { RSA_free(rsa); return false; } if (!PEM_write_RSAPrivateKey(fp, static_cast<RSA*>(rsa), NULL, NULL, 0, 0, NULL)) { ERR_load_crypto_strings(); char err[1024]; char* errret = ERR_error_string(ERR_get_error(), err); ERROR_MSG(fmt::format("KBE_RSA::generateKey: PEM_write_RSAPrivateKey error({} : {})\n", errret, err)); fclose(fp); RSA_free(rsa); return false; } fclose(fp); fp = fopen(pubkeyname.c_str(), "w"); if (!fp) { RSA_free(rsa); return false; } if (!PEM_write_RSAPublicKey(fp, static_cast<RSA*>(rsa))) { ERR_load_crypto_strings(); char err[1024]; char* errret = ERR_error_string(ERR_get_error(), err); ERROR_MSG(fmt::format("KBE_RSA::generateKey: PEM_write_RSAPublicKey error({} : {})\n", errret, err)); fclose(fp); RSA_free(rsa); return false; } INFO_MSG(fmt::format("KBE_RSA::generateKey: RSA key generated. keysize({}) bits.\n", keySize)); RSA_free(rsa); fclose(fp); return loadPrivate(prikeyname) && loadPublic(pubkeyname); }