update: so I don't like this base64 lib anymore. It has no error handling.

main
_ 2021-01-17 09:52:38 -06:00
parent 1b2e5adc84
commit 0f0e59029f
1 changed files with 122 additions and 2 deletions

View File

@ -19,6 +19,28 @@ using nlohmann::json;
const int64_t about_3_months = (int64_t)105 * 86400;
// Not sure why the Base64 lib fails to provide this API
string b64_encode (const vector <uint8_t> & v) {
string s;
s.resize (Base64::EncodedLength (v.size ()));
Base64::Encode ((const char *)v.data (), v.size (), s.data (), s.size ());
return s;
}
optional <vector <uint8_t>> b64_decode (const string & s) {
vector <uint8_t> v;
v.resize (Base64::DecodedLength (s.data (), s.size ()));
if (! Base64::Decode (s.data (), s.size (), (char *)v.data (), v.size ()))
{
return nullopt;
}
return v;
}
struct ExpiringSignature {
string cert_s;
vector <uint8_t> sig;
@ -47,6 +69,69 @@ void try_sodium_init () {
}
}
struct VerifiedData {
vector <uint8_t> payload;
string purpose;
};
optional <VerifiedData> try_verify_signed_data (
const ExpiringSignature & sig,
int64_t now,
const vector <uint8_t> & pubkey
) {
try_sodium_init ();
if (pubkey.size () != crypto_sign_PUBLICKEYBYTES) {
return nullopt;
}
if (crypto_sign_verify_detached (
sig.sig.data (),
(const uint8_t *)sig.cert_s.data (),
sig.cert_s.size (),
pubkey.data ()
) != 0) {
return nullopt;
}
const json j = json::parse (sig.cert_s);
const int64_t not_before = j ["not_before"];
const int64_t not_after = j ["not_after"];
if (now < not_before) {
return nullopt;
}
if (now > not_after) {
return nullopt;
}
const string purpose = j ["purpose"];
const string payload_b64 = j ["payload_b64"];
string payload_s;
Base64::Decode (payload_b64, &payload_s);
const vector <uint8_t> payload;
return VerifiedData {
payload,
purpose
};
}
optional <VerifiedData> verify_signed_data (
const ExpiringSignature & sig,
int64_t now,
const vector <uint8_t> & pubkey
) {
try {
return try_verify_signed_data (sig, now, pubkey);
}
catch (json::exception &) {
return nullopt;
}
}
string to_base64 (const vector <uint8_t> & v) {
const string s ((const char *)v.data (), v.size ());
string b64;
@ -132,7 +217,39 @@ int check_real_time () {
return 0;
}
int check_base64 () {
vector <uint8_t> v {1, 2, 3, 4, 5, 6};
const auto s = b64_encode (v);
if (s != "AQIDBAUG") {
cerr << "Base64 encoding failed" << endl;
return 1;
}
// Trivial decode
const auto v2 = std::move (*b64_decode (s));
if (v2 != v) {
cerr << "Base64 trivial decode failed" << endl;
return 1;
}
// Decode should fail
const auto v3 = b64_decode ("AQIDBAUG.");
if (v3 != nullopt) {
cerr << "Base64 decode should have failed" << endl;
return 1;
}
return 0;
}
int main () {
if (check_base64 () != 0) {
return 1;
}
// Suppose we generate a root key and keep it somewhere safe
// (not a server)
SigningKey root_key;
@ -188,8 +305,11 @@ int main () {
return 1;
}
{
const json j = json::parse (cert.cert_s);
cerr << "not_before: " << (int64_t)j ["not_before"] << endl;
}
cerr << "Done." << endl;
return 0;