diff --git a/crypto.cpp b/crypto.cpp index e1a8594..25c9ae0 100644 --- a/crypto.cpp +++ b/crypto.cpp @@ -28,8 +28,8 @@ * as that of the covered work. */ -#define _BSD_SOURCE #include "crypto.hpp" +#include "util.hpp" #include #include #include @@ -38,7 +38,6 @@ #include #include #include -#include void load_keys (const char* filepath, keys_t* keys) { @@ -82,9 +81,9 @@ void aes_ctr_state::process (const AES_KEY* key, const uint8_t* in, uint8_t* out // first 12 bytes - nonce // last 4 bytes - block number (sequentially increasing with each block) uint8_t ctr[16]; - uint32_t blockno = htonl(byte_counter / 16); + uint32_t blockno = byte_counter / 16; memcpy(ctr, nonce, 12); - memcpy(ctr + 12, &blockno, 4); + store_be32(ctr + 12, blockno); AES_encrypt(ctr, otp, key); } diff --git a/util.cpp b/util.cpp index 575d616..e37d7cc 100644 --- a/util.cpp +++ b/util.cpp @@ -126,3 +126,37 @@ std::string escape_shell_arg (const std::string& str) return new_str; } +uint32_t load_be32 (const unsigned char* p) +{ + return (static_cast(p[3]) << 0) | + (static_cast(p[2]) << 8) | + (static_cast(p[1]) << 16) | + (static_cast(p[0]) << 24); +} + +void store_be32 (unsigned char* p, uint32_t i) +{ + p[3] = i; i >>= 8; + p[2] = i; i >>= 8; + p[1] = i; i >>= 8; + p[0] = i; +} + +bool read_be32 (std::istream& in, uint32_t& i) +{ + unsigned char buffer[4]; + in.read(reinterpret_cast(buffer), 4); + if (in.gcount() != 4) { + return false; + } + i = load_be32(buffer); + return true; +} + +void write_be32 (std::ostream& out, uint32_t i) +{ + unsigned char buffer[4]; + store_be32(buffer, i); + out.write(reinterpret_cast(buffer), 4); +} + diff --git a/util.hpp b/util.hpp index aa76982..2bd7356 100644 --- a/util.hpp +++ b/util.hpp @@ -34,11 +34,16 @@ #include #include #include +#include int exec_command (const char* command, std::ostream& output); std::string resolve_path (const char* path); void open_tempfile (std::fstream&, std::ios_base::openmode); std::string escape_shell_arg (const std::string&); +uint32_t load_be32 (const unsigned char*); +void store_be32 (unsigned char*, uint32_t); +bool read_be32 (std::istream& in, uint32_t&); +void write_be32 (std::ostream& out, uint32_t); #endif