/** * @file encryption.h * @author syxhe (https://t.me/syxhe) * @brief A collection of all encryption related functions * @version 0.1 * @date 2025-06-09 * * @copyright Copyright (c) 2025 * */ #ifndef __VXGG_REWRITE___ENCRYPTION_H___1481879318188___ #define __VXGG_REWRITE___ENCRYPTION_H___1481879318188___ #include #include "shared.h" /// Determines whether any function that calls libsodium functions also checks to make sure libsodium is actually initialized. May /// cause unexpected issues with early exiting due to libsodium failing to initialize properly. It's recommended that you just /// manually run `sodium_init()` in some main or init function of your own so that you can deal with a potential error yourself #define ___VXGG___ALWAYS_CHECK_LIBSODIUM___ 1 /// Grants access to the `vxgg_setsodiumfailcb` function, which can be used to set a custom callback for what to do when libsodium /// fails upon initialization #define ___VXGG___USE_CLS_CALLBACK___ 1 #if ___VXGG___ALWAYS_CHECK_LIBSODIUM___ > 0 #if ___VXGG___USE_CLS_CALLBACK___ > 0 //! Definition for the callback function that fires when a call to checksodium fails typedef void (*vxgg_naclfailcb)(void*); /** * @brief Sets a callback and data pair to be ran if/when sodium fails to initialize * * @param cb The new callback to set. Must be non-null * @param data The data to be fed to the callback. May be null */ void vxgg_setsodiumfailcb(const vxgg_naclfailcb cb, void *data); #endif #endif /// Chunk size for en/decryption. I originally wanted to use st_blksize from stat(), but given that those chunks may be of different /// sizes between computers / filesystems / architectures / files, it's easier to just have this be a consistent macro #define CHUNKSIZE (1 << 9) const static char * test = "this is a test"; // Fuck reading from a file. Even if someone ran strings on the binary and got this they wouldn't be able to regenerate the key //! A list of possible words for password creation #define PASSWORD_WORDS (\ (const char * const []){\ "the", "of", "to", "and", "for", "our", "their", "has", "in", "he", "a", "them", "that", "these", "by", "have", "we", \ "us", "people", "which", "all", "is", "with", "laws", "be", "are", "his", "states", "on", "they", "right", "it", "from", \ "government", "such", "among", "powers", "most", "an", "time", "should", "new", "as", "been", "colonies", "assent", \ "large", "at", "independent", "free", "united", "when", "mankind", "hold", "rights", "governments", "consent", "its", \ "long", "themselves", "abolishing", "usurpations", "absolute", "repeated", "this", "world", "refused", "pass", "other", \ "others", "without", "justice", "peace", "power", "seas", "war", "do", "declaration", "america", "becomes", "necessary", \ "political", "equal", "declare", "causes", "separation", "men", "happiness", "any", "form", "alter", "or", "will", \ "forms", "same", "object", "off", "necessity", "history", "great", "britain", "tyranny", "over", "public", "good", \ "unless", "suspended", "so", "would", "legislature", "only", "legislative", "bodies", "purpose", "into", "dissolved", \ "state", "endeavoured", "refusing", "hither", "conditions", "establishing", "offices", "out", "armies", "legislatures", \ "render", "jurisdiction", "foreign", "acts", "pretended", "trial", "inhabitants", "cases", "transporting", "rule", \ "declaring", "here", "protection", "against", "lives", "circumstances", "ages", "totally", "friends", "brethren", "whose", \ "every", "may", "therefore", "ought", "unanimous", "thirteen", "course", "human", "events", "one", "dissolve", "bands", \ "connected", "another", "assume", "earth", "separate", "station", "nature", "natures", "god", "entitle", "decent", \ "respect", "opinions", "requires", "impel", "truths", "self", "evident", "created", "endowed", "creator", "certain", \ "unalienable", "life", "liberty", "pursuit", "secure", "instituted", "deriving", "just", "governed", "whenever", \ "destructive", "ends", "abolish", "institute", "laying", "foundation", "principles", "organizing", "shall", "seem", \ "likely", "effect", "safety", "prudence", "indeed", "dictate", "established", "not", "changed", "light", "transient", \ "accordingly", "experience", "hath", "shewn", "more", "disposed", "suffer", "while", "evils", "sufferable", "than", \ "accustomed", "but", "train", "abuses", "pursuing", "invariably", "evinces", "design", "reduce", "under", "despotism", \ "duty", "throw", "provide", "guards", "future", "security", "patient", "sufferance", "now", "constrains", "former", \ "systems", "present", "king", "injuries", "having", "direct", "establishment", "prove", "let", "facts", "submitted", \ "candid", "wholesome", "forbidden", "governors", "immediate", "pressing", "importance", "operation", "till", "obtained", \ "utterly", "neglected", "attend", "accommodation", "districts", "those", "relinquish", "representation", "inestimable", \ "formidable", "tyrants", "called", "together", "places", "unusual", "uncomfortable", "distant", "depository", "records", \ "sole", "fatiguing", "compliance", "measures", "representative", "houses", "repeatedly", "opposing", "manly", "firmness", \ "invasions", "after", "dissolutions", "cause", "elected", "whereby", "incapable", "annihilation", "returned", "exercise", \ "remaining", "mean", "exposed", "dangers", "invasion", "convulsions", "within", "prevent", "population", "obstructing", \ "naturalization", "foreigners", "encourage", "migrations", "raising", "appropriations", "lands", "obstructed", \ "administration", "judiciary", "made", "judges", "dependent", "alone", "tenure", "amount", "payment", "salaries", \ "erected", "multitude", "sent", "swarms", "officers", "harrass", "eat", "substance", "kept", "times", "standing", \ "affected", "military", "superior", "civil", "combined", "subject", "constitution", "unacknowledged", "giving", \ "legislation", "quartering", "armed", "troops", "protecting", "mock", "punishment", "murders", "commit", "cutting", \ "trade", "parts", "imposing", "taxes", "depriving", "many", "benefits", "jury", "beyond", "tried", "offences", "system", \ "english", "neighbouring", "province", "therein", "arbitrary", "enlarging", "boundaries", "once", "example", "fit", \ "instrument", "introducing", "taking", "away", "charters", "valuable", "altering", "fundamentally", "suspending", "own", \ "invested", "legislate", "whatsoever", "abdicated", "waging", "plundered", "ravaged", "coasts", "burnt", "towns", \ "destroyed", "mercenaries", "compleat", "works", "death", "desolation", "already", "begun", "cruelty", "perfidy", \ "scarcely", "paralleled", "barbarous", "unworthy", "head", "civilized", "nation", "constrained", "fellow", "citizens", \ "taken", "captive", "high", "bear", "arms", "country", "become", "executioners", "fall", "hands", "excited", "domestic", \ "insurrections", "amongst", "bring", "frontiers", "merciless", "indian", "savages", "known", "warfare", "undistinguished", \ "destruction", "sexes", "stage", "oppressions", "petitioned", "redress", "humble", "terms", "petitions", "answered", \ "injury", "prince", "character", "thus", "marked", "act", "define", "tyrant", "unfit", "ruler", "nor", "wanting", \ "attentions", "brittish", "warned", "attempts", "extend", "unwarrantable", "reminded", "emigration", "settlement", \ "appealed", "native", "magnanimity", "conjured", "ties", "common", "kindred", "disavow", "inevitably", "interrupt", \ "connections", "correspondence", "too", "deaf", "voice", "consanguinity", "must", "acquiesce", "denounces", "rest", \ "enemies", "representatives", "general", "congress", "assembled", "appealing", "supreme", "judge", "rectitude", \ "intentions", "name", "authority", "solemnly", "publish", "absolved", "allegiance", "british", "crown", "connection", \ "between", "full", "levy", "conclude", "contract", "alliances", "establish", "commerce", "things", "support", "firm", \ "reliance", "divine", "providence", "mutually", "pledge", "each", "fortunes", "sacred", "honor"\ }\ ) //! Short macro for getting the `PASSWORD_WORDS` array size #define PASSWORD_WORDS_LEN (STATIC_ARRAY_LEN(PASSWORD_WORDS)) /** * @brief open() with the flags O_TMPFILE, O_WRONLY, O_CLOEXEC, and O_SYNC. Opened with mode S_IRUSR, S_IWUSR * * @param dest The filename the new descriptor should have. Must be non-null * @retval (int)[-1,int] A new file descriptor. -1 on error */ int maketmp(const char * const dest); /** * @brief Encrypt src to dst using libsodium's xchacha encryption suite * * @param src File to encrypt * @param dst Destination to write encrypted file * @param key Key for encryption * @retval (int)[-1, 0] Returns 0 on success, sets errno and returns -1 on error */ int encrypttofile(FILE *src, FILE *dst, const unsigned char key[crypto_secretstream_xchacha20poly1305_KEYBYTES]); /** * @brief Decrypt src to dst using libsodium's xchacha encryption suite * * @param src File to decrypt * @param dst Destination to write decrypted file * @param key Key used to encrypt * @retval (int)[-1, 0] Returns 0 on success, sets errno and returns -1 on error */ int decrypttofile(FILE *src, FILE *dst, const unsigned char key[crypto_secretstream_xchacha20poly1305_KEYBYTES]); /** * @brief Encrypt file at `target` to `output` using Linux's named temp file system to do it in the background * * @param target * @param output * @param key * @retval (int)[,] */ int encryptviatmp(const char * const target, const char * const output, const unsigned char key[crypto_secretstream_xchacha20poly1305_KEYBYTES]); /** * @brief Decrypt the file at `encrypted` to `target` * * @param encrypted * @param target * @param key * @retval (int)[,] */ int decryptto(const char * const encrypted, const char * const target, const unsigned char key[crypto_secretstream_xchacha20poly1305_KEYBYTES]); /** * @brief Link a file descriptor into the filesystem * * @param target New filename the descriptor should have * @param tgfd The file descriptor to link * @retval (int)[-1, 0] 0 on success, -1 on error */ int linkto(const char * const target, int tgfd); /** * @brief Generate a password viable for use in the derivation of a key * * @param str Pointer to a string. This will be filled by a malloc'ed string of words (the password). Must be non-null * @param words The number of words to include in the password. A password of at least 20 words and probably not more than 40 is recommended * @retval (int)[-1, words] On success, returns the number of words requested. On error, returns -1 and sets errno */ int genpassword(char **str, unsigned int words); /** * @brief sodium_malloc wrapper. * * Calls `error()` or `abort()` depnding on the value of `___VXGG___XALLOC_EXIT_ON_ERROR___`. Will make sure libsodium is initialized if `___VXGG___ALWAYS_CHECK_LIBSODIUM___ > 0` * * @param size * @retval (void*) A pointer to some data allocated via `sodium_malloc()` */ void* xsodium_malloc(size_t size); #endif