Skip to content

Commit

Permalink
feat: rsa::load_from_string() (#43)
Browse files Browse the repository at this point in the history
  • Loading branch information
onchere authored Jun 10, 2021
1 parent 0058ed0 commit b8ac560
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 5 deletions.
13 changes: 8 additions & 5 deletions include/export/jwtpp/jwtpp.hh
Original file line number Diff line number Diff line change
Expand Up @@ -655,11 +655,7 @@ public:

static sp_rsa_key load_from_file(const std::string &path, password_cb on_password = nullptr);

static sp_rsa_key load_from_string(const std::string &str) {
auto key = std::shared_ptr<RSA>(RSA_new(), ::RSA_free);

return key;
}
static sp_rsa_key load_from_string(const std::string &str, password_cb on_password = nullptr);

private:
static int password_loader(char *buf, int size, int rwflag, void *u);
Expand Down Expand Up @@ -737,6 +733,13 @@ private:
size_t _key_size;
};

class BIODeleter {
public:
inline void operator()(BIO* bio) const {
(void)BIO_free(bio);
}
};

std::string marshal(const Json::Value &json);

std::string marshal_b64(const Json::Value &json);
Expand Down
17 changes: 17 additions & 0 deletions src/rsa.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -106,6 +106,23 @@ sp_rsa_key rsa::load_from_file(const std::string &path, password_cb on_password)
return std::shared_ptr<RSA>(r, ::RSA_free);
}

sp_rsa_key rsa::load_from_string(const std::string& str, password_cb on_password) {
RSA *r;

auto bio = std::unique_ptr<BIO, BIODeleter>{BIO_new_mem_buf(str.data(), str.size())};

on_password_wrap wrap(on_password);

r = PEM_read_bio_RSAPrivateKey(bio.get(), nullptr, password_loader, &wrap);
if (wrap.required) {
throw std::runtime_error("password required");
} else if (r == nullptr) {
throw std::runtime_error("read rsa key");
}

return std::shared_ptr<RSA>(r, ::RSA_free);
}

int rsa::password_loader(char *buf, int size, int rwflag, void *u) {
auto wrap = reinterpret_cast<on_password_wrap *>(u);

Expand Down

0 comments on commit b8ac560

Please sign in to comment.