| 86 | } |
| 87 | |
| 88 | Bytes decryptRaw(const Bytes& input, const Bytes& key, const Bytes& nonce) { |
| 89 | if (key.size() != EncryptionType::keyLength()) { |
| 90 | throw std::invalid_argument{"Expected key of " + std::to_string(EncryptionType::keyLength()) + |
| 91 | " bytes, but got " + std::to_string(key.size()) + " bytes during decryption"}; |
| 92 | } |
| 93 | if (nonce.size() != EncryptionType::nonceLength()) { |
| 94 | throw std::invalid_argument{"Expected a nonce of " + std::to_string(EncryptionType::nonceLength()) + |
| 95 | " bytes, but got " + std::to_string(nonce.size()) + " bytes during decryption"}; |
| 96 | } |
| 97 | if (input.size() < EncryptionType::macLength()) { |
| 98 | throw std::invalid_argument{"Input is too short: expected at least " + std::to_string(EncryptionType::macLength()) + |
| 99 | " bytes, but got " + std::to_string(input.size()) + " bytes during decryption"}; |
| 100 | } |
| 101 | |
| 102 | Bytes plaintext(input.size() - EncryptionType::macLength()); |
| 103 | if (crypto_secretbox_open_easy(plaintext.data(), input.data(), input.size(), nonce.data(), key.data())) { |
| 104 | throw std::runtime_error{"Decryption failed; the input may be forged!"}; |
| 105 | } |
| 106 | return plaintext; |
| 107 | } |
| 108 | |
| 109 | std::string decrypt(const std::string& input, const Bytes& key) { |
| 110 | auto data = parseEncrypted(input); |
no test coverage detected