49 lines
1.0 KiB
C
49 lines
1.0 KiB
C
/*
|
|
* 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"
|
|
|
|
// 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;
|
|
}
|
|
|
|
// Below two functions do NOT work for lower case letters (fix this!)
|
|
void caesar_encrypt(char* str, int size, int key)
|
|
{
|
|
for (int i = 0; i < size && str[i] != '\n'; i++)
|
|
if (str[i] != ' ')
|
|
{
|
|
str[i] += key - 65;
|
|
str[i] %= 26;
|
|
str[i] += 65;
|
|
}
|
|
}
|
|
|
|
|
|
void caesar_decrypt(char* str, int size, int key)
|
|
{
|
|
for (int i = 0; i < size && str[i] != '\n'; i++)
|
|
if (str[i] != ' ')
|
|
{
|
|
str[i] = str[i] - key - 65;
|
|
str[i] = mod(str[i], 26);
|
|
str[i] += 65;
|
|
}
|
|
}
|