diff --git a/docs/crypto.md b/docs/crypto.md index 624d27f..5aee9fe 100644 --- a/docs/crypto.md +++ b/docs/crypto.md @@ -1,6 +1,6 @@ # crypto -Cryptographic library +Cryptographic tools ## Functions @@ -65,4 +65,21 @@ responsible for freeing the returned string. ```c const char *hex_to_str(const unsigned char *hex, size_t sz); -``` \ No newline at end of file +``` + +### repeating_key_xor + +Performs a repeating-key XOR encryption on an array of bytes. User is responsible for freeing the returned array + +```c +const unsigned char* repeating_key_xor(const unsigned char* s, size_t s_sz, const unsigned char* key, size_t k_sz); +``` + +### repeating_key_xor_s + +Performs a repeating-key XOR encryption on a string. Returns the encrypted string as an array of bytes. User is +responsible for freeing the returned array + +```c +const unsigned char *repeating_key_xor_s(const char* s, const char* key); +``` diff --git a/include/lfcrypto.h b/include/lfcrypto.h index 7ba54ec..624e776 100644 --- a/include/lfcrypto.h +++ b/include/lfcrypto.h @@ -10,4 +10,7 @@ const char *hex_encode(const unsigned char *hex, size_t sz); unsigned char *hex_decode(const char *orig, size_t *sz); const char *hex_to_str(const unsigned char *hex, size_t sz); +const unsigned char* repeating_key_xor(const unsigned char* s, size_t s_sz, const unsigned char* key, size_t k_sz); +const unsigned char *repeating_key_xor_s(const char* s, const char* key); + #endif // LIBFLINT_CRYPTO_H diff --git a/src/crypto.c b/src/crypto.c index 7c332bf..46200c3 100644 --- a/src/crypto.c +++ b/src/crypto.c @@ -236,7 +236,7 @@ const char *hex_encode(const unsigned char *hex, size_t sz) { char *pos = s; for (size_t i = 0; i < sz; ++i) { - snprintf(pos, 3, "%2X", hex[i]); + snprintf(pos, 3, "%02X", hex[i]); pos += 2; } s[ssz - 1] = '\0'; @@ -251,4 +251,17 @@ const char *hex_to_str(const unsigned char *hex, size_t sz) { } s[sz] = '\0'; return s; +} + +const unsigned char* repeating_key_xor(const unsigned char* s, size_t s_sz, const unsigned char* key, size_t k_sz) { + unsigned char* r = malloc(sizeof(unsigned char) * s_sz); + for (size_t i = 0, j = 0; i < s_sz; ++i) { + r[i] = s[i] ^ key[j]; + j = (j + 1) % k_sz; + } + return r; +} + +const unsigned char *repeating_key_xor_s(const char* s, const char* key) { + return repeating_key_xor((unsigned char*)s, strlen(s), (unsigned char*)key, strlen(key)); } \ No newline at end of file diff --git a/tests/tests.c b/tests/tests.c index bae1c5a..37ef820 100644 --- a/tests/tests.c +++ b/tests/tests.c @@ -361,6 +361,12 @@ void test_crypto() { assert(strcmp(s, "Sup?") == 0); free(s); + s = repeating_key_xor_s("TEST", "HI"); + const char *enc = hex_encode(s, 4); + assert(strcmp(enc, "1C0C1B1D") == 0); + free(enc); + free(s); + printf("Passes all crypto tests\n"); }