repeating key xor

This commit is contained in:
Evan Burkey 2024-04-09 10:47:34 -07:00
parent 507c690583
commit 321d1ec446
4 changed files with 42 additions and 3 deletions

View File

@ -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);
```
```
### 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);
```

View File

@ -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

View File

@ -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));
}

View File

@ -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");
}