Vigenere Cipher in C: Incomplete Encryption - c

A general explanation of the Vigenere Cipher:
The Vigenere Cipher is a method of encryption that is similar to the Caesar Cipher. This Cipher takes in a word as an argument and interprets the alphabets of the word as follows- a as 0, b as 1, c as 2 and so on.
So if your input key is abc and you want something like "hi hello" to be encrypted, the output would entail h remaining the same, i shifting by 1 place, h shifting by 2 places, e again remaining the same (as it is being shifted by 0), l shifting by 1 place, the other l by 2 and so on so forth.
The basic idea is that each letter shifts by the corresponding letter in the argument and the spaces and other punctuation marks are ignored. If the argument is shorter than the message (as it is in most cases), the argument simply loops around the message.
My problem:
My message is just being encrypted by the first alphabet of the Vignere Cipher.
For example, ./vc bc ----> message: ABCDE ABCDE becomes BCDEF BCDEF. In other words, the entire message is just being shifted by the value of b when it should instead be shifted by the value of bc (+1 for the first alphabet and +2 for every other alphabet.)
I don't understand why is this happening despite being within a loop.
CODE:
# include <cs50.h>
# include <stdio.h>
# include <stdlib.h>
# include <string.h>
# include <ctype.h>
int main(int argc, string argv[])
{
string word = argv[1];
int i = 0;
int j = 0;
if (argc != 2 || isalpha(word[j]) == false)
{
printf("Please enter a valid command line argument! \n");
return 1;
}
else if (isalpha(word[j]))
{
printf("Message: ");
string message = GetString();
for (int n = strlen(message); i < n; i++)
{
int plaintext = message[i];
int ciphertext = word[j];
int uppcb = (plaintext - 65 + ciphertext - 65);
int upcipher1 = (uppcb) % 26;
int uplc = (plaintext - 65 + ciphertext - 97);
int upcipher2 = (uplc) % 26;
int lopcb = (plaintext - 97 + ciphertext - 97);
int locipher1 = (lopcb) % 26;
int lolp = (plaintext - 97 + ciphertext - 65);
int locipher2 = (lolp) % 26;
if (isupper(word[j]) && isupper(message[i]))
{
j = (j+1)%strlen(word);
int upcode = (upcipher1 + 65);
printf("%c", upcode);
}
else if (isupper(message[i]) && islower(word[j]))
{
j = (j+1)%strlen(word);
int upcode1 = (upcipher2 + 65);
printf("%c", upcode1);
}
else if (islower(message[i]) && islower(word[j]))
{
j = (j+1)%strlen(word);
int locode = (locipher1 + 97);
printf("%c", locode);
}
else if (islower(message[i]) && isupper(word[j]))
{
j = (j+1)%strlen(word);
int locode1 = (locipher2 +97);
printf("%c", locode1);
}
else
{
printf("%c", message[i]);
}
}
printf("\n");
}
}

Related

Brute force function for decrypting string in C (Caesar cipher )

I found this problem interesting, as it is given that you need to use the alphabet as an array in C. Task is to brute force every possible K value, in basic Caesar's cipher manner.
However, code I come up with compile non-true values after K = 1. For example, a letter C is turned to Z instead of A etc. Can anyone spot what I did wrong?
#include <stdio.h>
#include <string.h>
void bruteforce (char*);
int main() {
char cyphertext[] = "kyvtrmrcipnzccrkkrtbwifdkyvefikynvjkrkeffe";
bruteforce(cyphertext);
return 0;
}
void bruteforce (char *cyphertext) {
char alphabet[26] = "abcdefghijklmnopqrstuvwxyz";
long int size = strlen(cyphertext);
for (int k = 0; k < 26; k++){
for (long int i = 0; i < size; i++){
for (int j = 0; j < 26; j++){
if (alphabet[j] == cyphertext[i]){
cyphertext[i] = alphabet[j - k];
if (k > j){
cyphertext[i] = alphabet[26 + j - k];
}
break;
}
}
}
printf("%s\n ", cyphertext);
}
}
For Caesar Cypher shifting, you don't need to use the alphabet string. You can just shift the character in ASCII code. ASCII codes of 'a' - 'z' are 97 - 122. Thus if decode with + 1. If the characters are a - z, you can just add one to each character. If after adding the shift value to the character value and the character value become larger than 122 then take the character value and subtract it to 122 then add 96 to that.
For shifting negative, if character value become smaller than 97. Take 97 subtract to character's value. Then subtract 123 to the previous equation value. Nonetheless, I built the code so that negative shift will be convert to positive shift. If the shift is negative we take 26 and add to that. Example is, shifting -1 will make a become z. So that is similar to shifting 26 + -1 = 25.
Shift value can be larger than +25 or smaller than -25. Nonetheless, if it is, it will be modulus to 26.
If you want to bruteforce all the possible combinations for a string. Just use the function below and run it in a loop from 1 to 25. But your function modify the original string. Thus, when doing bruteforce, you would have to copy the string of your function to a temporary string and let the function work on that. The examples are below.
#include <stdio.h>
#include <string.h>
void bruteforce (char *cyphertext, int shiftBy);
int main() {
char cyphertext[] = "kyvtrmrcipnzccrkkrtbwifdkyvefikynvjkrkeffe";
char cyphertext2[] = "yvccf wifd bvmze";
bruteforce(cyphertext, -17);
puts("");
bruteforce(cyphertext2, 9);
/* Bruteforce example */
puts("");
puts("Bruteforce section:");
// +9
char cyphertext3[] = "kyzjkvokzjkfsvtirtb nyrk tre kyzj sv zj zk yvccf nficu";
char temp[50];
for (int i = 1; i < 26; i++){
printf("Trying to crack by shifting %d \n", i );
strcpy(temp, cyphertext3);
bruteforce(temp, i);
puts("");
}
/* End Bruteforce example */
return 0;
}
// If there is no shift i.e 0, 26, 52, -26
// It won't print
void bruteforce (char *cyphertext, int shiftBy){
size_t size = strlen(cyphertext);
if ( shiftBy > 25){
shiftBy = shiftBy % 26;
} else if ( shiftBy < 0 ) {
shiftBy = 26 + (shiftBy % 26);
// If shiftBy is 26
// there is no need to shift.
if ( shiftBy == 26 ) return;
}
// If there is no shift return.
if ( shiftBy == 0 ) return;
for ( size_t i = 0; i < size; i++){
// 97 - 122 is a - z
// if char is a - z
if ( cyphertext[i] > 96 && cyphertext[i] < 123 ){
// add shift by
cyphertext[i] += shiftBy;
// if char > z
// then take char - z then add to the ascii code that just before 'a'.
// Since shiftBy is converted fomr negative to positive.,
// There will not be a negative shiftBy.
if ( (unsigned char)cyphertext[i] > 122 )
cyphertext[i] = ((unsigned char) cyphertext[i]) - 122 + 96;
}
// If want to do A - Z
// ASCII code are 65 - 90.
}
printf("%s\n", cyphertext);
}

C - Distinguishing Between Chars and Digits, then Handling Accordingly

I am writing a program that converts user input to either
ASCII values or binary values. If the string contains letters,
each letter should be converted to ASCII. Strings of numbers will
be converted to binary value of entire string. If both letters and
numbers are entered, each letter will be converted to ASCII and the numbers can/will only be separated by letters, for example "32" will print the binary value "00100000", but "3a2" should be converted to "00000011", "97", "00000010".
The way the program is currently written, strings of numbers convert to binary perfectly. However, strings of letters add a decimal "0" to the end. The output converts each letter to its ASCII value, then converts the "0" to binary. I am unsure as to where this "0" is coming from. Additionally, strings beginning
and ending with digits (for example "6j3") will print the ASCII value of j, then the binary value of "6", skipping the "3" entirely and printing the "j" before the "6". I would like to print each ASCII/binary value in the exact order of the user input.
I am posting my entire code for any necessary clarification, but I believe the issue is in the determineChars() function. I am also looking to use the char* letters and char* numbers functions to efficiently handle the appropriate data and store the final num[] and let[] arrays, but I am unsure of how to do this.
I am quite a beginner to C, so excuse the messiness. Corrections, as well as any further optimizations would be greatly appreciated.
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <unistd.h>
#include <string.h>
#define EIGHT_BITS 255
#define SIXTEEN_BITS 65535
#define THIRTY_TWO_BITS 4294967295UL
#define SIXTY_FOUR_BITS 18446744073709551615ULL
// defined in case of booleans
typedef enum { false, true } bool;
// GET # OF ELEMENTS IN STRING
size_t getSize(char* input) {
size_t size;
size = strlen(input);
printf("Number of Characters..... %d", size);
//printf("\n----------------------------------");
return size;
}
// DETERMINE NUMBER OF BITS TO OUTPUT
int getBitLength(unsigned long long d) {
int l;
if (d <= EIGHT_BITS) {
l = 8;
}
else if (d > EIGHT_BITS && d <= SIXTEEN_BITS) {
l = 16;
}
else if (d > SIXTEEN_BITS && d <= THIRTY_TWO_BITS) {
l = 32;
}
else if (d > THIRTY_TWO_BITS && d <= SIXTY_FOUR_BITS) {
l = 64;
}
printf("\nBits..................... %d", l);
return l;
}
// CONVERT INPUT TO BINARY VALUE
void convertToBinary(char* input) {
static int b[64];
int i, j, length, r;
unsigned long long decimal;
char* pEnd;
// converts input to ull
decimal = strtoull(input, &pEnd, 0);
printf("\n\n---------------- %I64u ------------------", decimal);
printf("\nULL...................... %I64u", decimal);
length = getBitLength(decimal);
// creates array
for (i = 0; i < length; i++) {
r = decimal % 2;
decimal /= 2;
b[i] = r;
}
// reverses array for binary value
printf("\nBinary Value............. ");
for (j = length - 1; j >= 0; j--) {
printf("%d", b[j]);
}
}
char* numbers(char* input) {
char* num = (char*) malloc(sizeof(char) * 25);
return num;
}
char* letters(char* input) {
char* let = (char*) malloc(sizeof(char) * 25);
return let;
}
void determineChars(char* input) {
int i;
char* num = numbers(input);
char* let = letters(input);
size_t inputSize = getSize(input);
// FOR EACH CHARACTER IN INPUT
for (i = 0; i < inputSize; i++) {
if (isdigit(input[i])) {
// stores number values from input into separate array
num[i] = input[i];
printf("\nNumbers: %c", num[i]);
}
if (!isdigit(input[i])) {
// stores letter values from input into separate array
let[i] = input[i];
printf("\nLetters: %c", let[i]);
// prints separator line + ASCII value
printf("\n\n---------------- %c ------------------", let[i]);
printf("\nASCII Value of %c......... %d", let[i], let[i]);
// removes char from input array
input[i] = ' ';
}
}
// char array must consist of digits only
convertToBinary(num);
}
int main() {
// GET INPUT
char input[50];
scanf("%s", input);
determineChars(input);
return 0;
}
I would like to print each ASCII/binary value in the exact order of the user input.
In that case, you would have to restructure your code a bit. This is because if the input contains only digits you will have to print binary and alternate being chars and digits if the string contains both. I have tried to do this with the following code, cleaned it up a bit, removed the warnings and memory leaks.
See if this is what you want:
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <unistd.h>
#include <string.h>
#define EIGHT_BITS 255
#define SIXTEEN_BITS 65535
#define THIRTY_TWO_BITS 4294967295UL
#define SIXTY_FOUR_BITS 18446744073709551615ULL
// GET # OF ELEMENTS IN STRING
size_t getSize(char* input) {
size_t size;
size = strlen(input);
printf("Number of Characters..... %d\n", size);
//printf("\n----------------------------------");
return size;
}
// DETERMINE NUMBER OF BITS TO OUTPUT
int getBitLength(unsigned long long d) {
int l;
if (d <= EIGHT_BITS) {
l = 8;
}
else if (d > EIGHT_BITS && d <= SIXTEEN_BITS) {
l = 16;
}
else if (d > SIXTEEN_BITS && d <= THIRTY_TWO_BITS) {
l = 32;
}
else if (d > THIRTY_TWO_BITS && d <= SIXTY_FOUR_BITS) {
l = 64;
}
printf("\nBits..................... %d", l);
return l;
}
// CONVERT INPUT TO BINARY VALUE
void convertToBinary(char* input) {
static int b[64];
int i, j, length, r;
unsigned long long decimal;
char* pEnd;
// converts input to ull
decimal = strtoull(input, &pEnd, 0);
printf("\n---------------- %I64u ------------------", decimal);
printf("\nULL...................... %I64u", decimal);
length = getBitLength(decimal);
// creates array
for (i = 0; i < length; i++) {
r = decimal % 2;
decimal /= 2;
b[i] = r;
}
// reverses array for binary value
printf("\nBinary Value............. ");
for (j = length - 1; j >= 0; j--) {
printf("%d", b[j]);
}
printf("\n");
}
void determineChars(char* input) {
int i;
long ret;
char* ptr;
char c;
size_t inputSize = getSize(input);
ret = strtol(input, &ptr, 10);
if((ret == 0) || ((strlen(ptr) != 0) && (strlen(input) != strlen(ptr))))
{
for (i = 0; i < inputSize; i++) {
if (isdigit(input[i])) {
c = input[i];
printf("\nNumber: %c", c);
convertToBinary(&c);
}
if (!isdigit(input[i])) {
// stores letter values from input into separate array
printf("\nLetter: %c", input[i]);
// prints separator line + ASCII value
printf("\n---------------- %c ------------------\n", input[i]);
printf("ASCII Value of %c......... %d\n", input[i], input[i]);
// removes char from input array
}
}
}
else
convertToBinary(input);
}
int main() {
// GET INPUT
char input[50];
scanf("%s", input);
determineChars(input);
}
I also tried out the test cases you mentioned in the question along with few others and it seems to work fine.
32
Number of Characters..... 2
---------------- 32 ------------------
ULL...................... 32
Bits..................... 8
Binary Value............. 00100000
3a2
Number of Characters..... 3
Number: 3
---------------- 3 ------------------
ULL...................... 3
Bits..................... 8
Binary Value............. 00000011
Letter: a
---------------- a ------------------
ASCII Value of a......... 97
Number: 2
---------------- 2 ------------------
ULL...................... 2
Bits..................... 8
Binary Value............. 00000010
6j3
Number of Characters..... 3
Number: 6
---------------- 6 ------------------
ULL...................... 6
Bits..................... 8
Binary Value............. 00000110
Letter: j
---------------- j ------------------
ASCII Value of j......... 106
Number: 3
---------------- 3 ------------------
ULL...................... 3
Bits..................... 8
Binary Value............. 00000011

Coordinates of cell in Excel

I'm trying to get coordinates from Excel cell-numbers like A5, AC8, AAA8, and DADFAF145.
I read input from the user like this:
while( ( c = getchar() ) != EOF )
In the cycle I have a condition
if( c >= 48 && c <= 57 )
{
ungetc( c, stdin );
scanf( "%d\n", &column ); }
It check if c is a number 0-9, returns c to the buffer and read the number. The number is the y coordinate.
My problem is that I don't know how to get the X coordinate from the characters. I can't figure out an algorithm.
Index of A = 0, Z = 25, total 26 chars. If there is one char, it's ok. I dont' know how to solve if there are more chars.
Some examples:
A5
=> [5,0]
Z8
=> [8,25]
AAA2345
=> [2345,702] (26+26*26)
PA12
=> [12,416] (26+15*26)
AC23
=> [23,28]
NBFA349
=> [349,247572]
These letter combinations are actually base-26, however the digits are not from 0 to 25, but 1 to 26 instead (and are represented by letters from A to Z). So you can move from the end of the string to the beginning, multiply the digit (str[i]-'A'+1 where str[i] is the i-th character of the string str, i runs from strlen(str) to 0) to the corresponding power of 26. Like that:
int c = 1, s = 0;
for(int i = strlen(str)-1; i>=0; i--) {
s += (str[i]-'A'+1)*c; c*=26;
}
You must move from right to left, because, for example, number 28 is written as AB (and not BA)
The following might help. It defines a function which returns the column number of a string like "ADX". It coincides with what you will see if you enter the function =Column() in a cell in that column in an Excel spreadsheet:
#include <stdio.h>
#include <string.h>
long col_num(char* col);
int main(void){
char test1[] = "Z";
char test2[] = "AA";
char test3[] = "BZA";
printf("Column %s is column number %ld\n",test1,col_num(test1));
printf("Column %s is column number %ld\n",test2,col_num(test2));
printf("Column %s is column number %ld\n",test3,col_num(test3));
return 0;
}
long col_num(char* col){
long sum, i, n, p, val;
char letter;
n = strlen(col);
sum = 0;
p = 1;
for(i = n-1; i >= 0; i--){
letter = col[i];
val = letter - 'A' + 1;
sum += p*val;
p *= 26;
}
return sum;
}
I almost forgot. Output:
Column Z is column number 26
Column AA is column number 27
Column BZA is column number 2029
//"A" => 1, "Z" -> 26, "AAA" => 703, "NBFA" => 247573
int colToNum (const char *s){
int n = 0;
for(int i = 0; s[i] ; ++i)
n = n * 26 + (s[i] - 'A' + 1);
return n;//To zero origin : return n-1;
}

Vigenere Cipher Black Hawk Down

I cannot figure out why this thing doesn't scramble correctly. I read some other posts on this cipher and as far as I can tell I'm using the exact same algorithm as they are...
The areas commented out are tests I tried to make sure everything was passing through correctly. I believe it all goes through correctly then fails in the algorithm.
#include <stdio.h>
#include <cs50.h>
#include <string.h>
#include <ctype.h>
#include <stdlib.h>
string get_message(void);
string scramble(string key, string message);
int main(int argc, string argv[])
{
if(argc == 2)
{
string key;
string message;
key = argv[1];
//printf("KEY: %s<<",key);
message = get_message();
scramble(key, message);
}
else
{
printf("Please enter 2 arguments.\n");
return 1;
}
}
string get_message(void)
{
string message = "";
do
{
message = GetString();
}
while(strlen(message) < 1);
return message;
}
string scramble(string key,string message)
{
for(int i = 0, len = strlen(message), key_len = strlen(key); i < len; i++)
{
int letter = message[i];
//int Tkey = atoi(key[i % key_len]);
//printf("KEY: %d<<\n",Tkey);
if(islower(letter))
{
//printf("KEY(%d)",(key[i % key_len]-97));
letter = (((letter - 97) + (key[i % key_len])) % 26 + 97);
//printf("(%d)",(letter - 97) + (key[i % key_len])%26);
printf("%c",letter);
}
else if(isupper(letter))
{
//printf("(%d)", key[i]);
//printf("(%c)",letter); WE HAVE CORRECT LETTER
letter = (((letter - 65) + (key[i % key_len])) % 26 + 65);
printf("%c",letter);
}
}
printf("\n");
return 0;
}
I think your calculation is wrong:
You currently have
encryptedLetter = (letter - firstLetterOffset) + key[position % keyLength] % 26 + firstLetterOffset
by check the C operator precedence table we notice that % is evaluated before - or +, meaning that your code actually mean :
encryptedLetter = (letter - firstLetterOffset) + ( key[position % keyLength] % 26 ) + firstLetterOffset
Where you wanted :
encryptedLetter = ( (letter - firstLetterOffset) + key[position % keyLength] ) % 26 + firstLetterOffset
Conclusion : you need to put more parenthese to specify in which order you which to evaluate your expression.
In addition you took the letter number for the text character but not for the key !
Correct expression
encryptedLetter = ( (letter - firstLetterOffset) + key[position % keyLength] - firstLetterOffset ) % 26 + firstLetterOffset
Demonstration in javascript

I need to add string characters in C. A + B must = C. Literally

I am writing a program that is due tonight at midnight, and I am utterly stuck. The program is written in C, and takes input from the user in the form SOS where S = a string of characters, O = an operator (I.E. '+', '-', '*', '/'). The example input and output in the book is the following:
Input> abc+aab
Output: abc + aab => bce
And that's literally, not variable. Like, a + a must = b.
What is the code to do this operation? I will post the code I have so far, however all it does is take the input and divide it between each part.
#include <stdio.h>
#include <string.h>
int main() {
system("clear");
char in[20], s1[10], s2[10], o[2], ans[15];
while(1) {
printf("\nInput> ");
scanf("%s", in);
if (in[0] == 'q' && in[1] == 'u' && in[2] == 'i' && in[3] == 't') {
system("clear");
return 0;
}
int i, hold, breakNum;
for (i = 0; i < 20; i++) {
if (in[i] == '+' || in[i] == '-' || in[i] == '/' || in[i] == '*') {
hold = i;
}
if (in[i] == '\0') {
breakNum = i;
}
}
int j;
for (j = 0; j < hold; j++) {
s1[j] = in[j];
}
s1[hold] = '\0';
o[0] = in[hold];
o[1] = '\0';
int k;
int l = 0;
for (k = (hold + 1); k < breakNum; k++) {
s2[l] = in[k];
l++;
}
s2[breakNum] = '\0';
printf("%s %s %s =>\n", s1, o, s2);
}
}
Since this is homework, let's focus on how to solve this, rather than providing a bunch of code which I suspect your instructor would frown upon.
First, don't do everything from within the main() function. Break it up into smaller functions each of which do part of the task.
Second, break the task into its component pieces and write out the pseudocode:
while ( 1 )
{
// read input "abc + def"
// convert input into tokens "abc", "+", "def"
// evaluate tokens 1 and 3 as operands ("abc" -> 123, "def" -> 456)
// perform the operation indicated by token 2
// format the result as a series of characters (579 -> "egi")
}
Finally, write each of the functions. Of course, if you stumble upon roadblocks along the way, be sure to come back to ask your specific questions.
Based on your examples, it appears “a” acts like 1, “b” acts like 2, and so on. Given this, you can perform the arithmetic on individual characters like this:
// Map character from first string to an integer.
int c1 = s1[j] - 'a' + 1;
// Map character from second string to an integer.
int c2 = s2[j] - 'a' + 1;
// Perform operation.
int result = c1 + c2;
// Map result to a character.
char c = result - 1 + 'a';
There are some things you have to add to this:
You have to put this in a loop, to do it for each character in the strings.
You have to vary the operation according to the operator specified in the input.
You have to do something with each result, likely printing it.
You have to do something about results that extended beyond the alphabet, like “y+y”, “a-b”, or “a/b”.
If we assume, from your example answer, that a is going to be the representation of 1, then you can find the representation values of all the other values and subtract the value representation of a from it.
for (i = 0; i < str_len; i++) {
int s1Int = (int)s1[i];
int s2Int = (int)s1[i];
int addAmount = 1 + abs((int)'a' - s2Int);
output[i] = (char)(s1Int + addAmount)
}
Steps
1) For the length of the s1 or s2
2) Retrieve the decimal value of the first char
3) Retrieve the decimal value of the second char
4) Find the difference between the letter a (97) and the second char + 1 <-- assuming a is the representation of 1
5) Add the difference to the s1 char and convert the decimal representation back to a character.
Example 1:
if S1 char is a, S2 char is b:
s1Int = 97
s2Int = 98
addAmount = abs((int)'a' - s2Int)) = 1 + abs(97 - 98) = 2
output = s1Int + addAmount = 97 + 2 = 99 = c
Example 2:
if S1 char is c, S2 char is a:
s1Int = 99
s2Int = 97
addAmount = abs((int)'a' - s2Int)) = 1 + abs(97 - 97) = 1
output = s1Int + addAmount = 99 + 1 = 100 = d

Resources