caesarcrypt/src/crypt.c

72 lines
1.5 KiB
C
Raw Normal View History

2022-07-08 18:14:21 +01:00
/*
* Filename: crypt.c
* Authors(s): Roland (r.weirhowell@gmail.com)
* Description: Perform caesar cipher cryptographic operations
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/
#include "crypt.h"
2022-11-05 10:36:25 +00:00
#include <stdbool.h>
#include <stdint.h>
2022-11-05 10:36:25 +00:00
2022-07-08 18:14:21 +01:00
2022-11-19 16:38:49 +00:00
/*
2022-11-19 16:55:05 +00:00
* For built in C mod operator (%) -1 % 26 == -1
2022-11-19 16:38:49 +00:00
* For the requirements of this algorithm -1 mod 26 == 25 is required
* The below functions accomplish this
*/
2022-11-04 11:12:30 +00:00
// Which of the two below functions is faster (find out!)
inline int mod(int a, int b)
{
return (a % b + b) % b;
}
inline int fast_mod(int a, int b)
{
const int result = a % b;
return result >= 0 ? result : result + b;
}
2022-07-08 18:14:21 +01:00
2022-11-05 10:36:25 +00:00
2022-11-19 16:38:49 +00:00
/*
2022-11-19 16:55:05 +00:00
* 65 - 90 = ASCII 'A' - 'Z'
* 97 - 122 = ASCII 'a' - 'z'
2022-11-19 16:38:49 +00:00
*/
2022-11-05 10:36:25 +00:00
inline bool isupper(char c)
{
return c >= 'A' && c <= 'Z';
}
void caesar_encrypt(char* str, int64_t size, int key)
2022-07-08 18:14:21 +01:00
{
for (int64_t i = 0; i < size && str[i] != '\n'; i++)
2022-11-04 11:12:30 +00:00
if (str[i] != ' ')
{
2022-11-05 10:36:25 +00:00
bool upper = isupper(str[i]);
2022-11-05 10:50:42 +00:00
str[i] += (char)key - (upper ? 65 : 97);
2022-11-04 11:12:30 +00:00
str[i] %= 26;
2022-11-05 10:36:25 +00:00
str[i] += (upper ? 65 : 97);
2022-11-04 11:12:30 +00:00
}
2022-07-08 18:14:21 +01:00
}
void caesar_decrypt(char* str, int64_t size, int key)
2022-07-08 18:14:21 +01:00
{
for (int64_t i = 0; i < size && str[i] != '\n'; i++)
2022-11-04 11:12:30 +00:00
if (str[i] != ' ')
{
2022-11-05 10:36:25 +00:00
bool upper = isupper(str[i]);
2022-11-05 10:50:42 +00:00
str[i] = str[i] - (char)key - (upper ? 65 : 97);
str[i] = (char)mod(str[i], 26);
2022-11-05 10:36:25 +00:00
str[i] += (upper ? 65 : 97);
2022-11-04 11:12:30 +00:00
}
2022-07-08 18:14:21 +01:00
}