Skip to content

Commit

Permalink
Ref #9: wrap RSA password check
Browse files Browse the repository at this point in the history
Change-Id: I1242bfe4992b5da17eec0faedef2ae9871111613
Signed-off-by: Artur Troian <[email protected]>
  • Loading branch information
troian committed Apr 29, 2018
1 parent fb126a4 commit da8c86a
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 12 deletions.
34 changes: 25 additions & 9 deletions include/export/josepp/crypto.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,20 @@ namespace jose {
#endif // defined(_MSC_VER) && (_MSC_VER < 1700)

class crypto {
public:
using password_cb = std::function<void(secure_string &pass, int rwflag)>;

protected:
struct on_password_wrap {
explicit on_password_wrap(password_cb cb) :
cb(cb)
, required(false)
{}

password_cb cb;
bool required;
};

public:
/**
* \brief
Expand Down Expand Up @@ -142,9 +156,6 @@ class hmac : public crypto {
};

class rsa : public crypto {
public:
using password_cb = std::function<void(secure_string &pass, int rwflag)>;

public:
explicit rsa(jose::alg alg, sp_rsa_key key);

Expand Down Expand Up @@ -177,20 +188,21 @@ class rsa : public crypto {
return key;
}

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

auto pass_loader = [](char *buf, int size, int rwflag, void *u) -> int {
auto cb = reinterpret_cast<password_cb *>(u);
auto wrap = reinterpret_cast<on_password_wrap *>(u);

if ((*cb) == nullptr) {
if (wrap->cb == nullptr) {
wrap->required = true;
return 0;
}

secure_string pass;
int pass_size = 0;
try {
(*cb)(pass, rwflag);
wrap->cb(pass, rwflag);
pass_size = pass.copy(buf, secure_string::size_type(size), 0);
} catch (...) {
pass_size = 0;
Expand All @@ -205,8 +217,12 @@ class rsa : public crypto {
throw std::runtime_error("cannot open file");
}

r = PEM_read_RSAPrivateKey(f, NULL, pass_loader, &on_password);
if (r == nullptr) {
on_password_wrap wrap(on_password);

r = PEM_read_RSAPrivateKey(f, nullptr, pass_loader, &wrap);
if (wrap.required) {
throw std::runtime_error("password required");
} else if (r == nullptr) {
throw std::runtime_error("read rsa key");
}

Expand Down
4 changes: 1 addition & 3 deletions tests/rsa.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -210,7 +210,5 @@ TEST(JosePP, load_rsa_from_file)
pass.assign("12345");
}));

EXPECT_THROW(key = jose::rsa::load_from_file("./private.pem", [](jose::secure_string &pass, int rwflag) {
pass.assign("123456");
}), std::exception);
EXPECT_THROW(key = jose::rsa::load_from_file("./private.pem"), std::exception);
}

0 comments on commit da8c86a

Please sign in to comment.