# Thread: Put this algorithm into code

1. ## Put this algorithm into code

I am trying to put this algorithm into code for my autokey cipher program.

If (keyIsNotExhaust) Encryption = currChar + key; else Encryption = currChar + prevChar;

If (keyIsNotExhaust) decryption = currChar - key; else decryption = currChar - decryption;

This is the code I have so far:

Code:
`#include <stdio.h>`
Code:
```#include<string.h>
#include<stdlib.h>
#include<ctype.h>
#include<math.h>

char key;

unsigned int easyendecrypt(char c);

int main(void) {
int c;
while ((c = getc(stdin)) !=EOF) {
putc(easyendecrypt(c), stdout);
}
printf("\n");
return 0;
}

unsigned int easyendecrypt(char c) {
char k;

#ifdef DECRYPT
fprintf(stderr, "decrypting with %s\n",key);
k = 'A' + (c - key);
key[c] = k;
return k;
#else
fprintf(stderr,"encrypting with %s\n",key);
k = key + (c + key - 2 * 'A');
key[c]='\0';
return k;
#endif
} ``` 2. So the idea of this is fine, I guess.

> char key;
Here you declare key as an array and it's empty.

> k = 'A' + (c - key);
Then you start using the array name of the key to decrypt

> key[c] = k;
And also store the plaintext somewhere in the key?

And you do similar things when you encrypt:

> k = key + (c + key - 2 * 'A');

In pretty much all of these cases, you probably only intended to use part of the key in a loop, which right now, it doesn't look like you're attempting to do at all.

Also you really need to separate plaintext, key, and ciphertext. Each of these things need their own array, perhaps even of the same size (to start with). You cannot store plaintext in the key array without overwriting part of the key. 3. Is this how an autokey cipher would work or is there an easier way. 4. Well somewhere, you need to initialise your key string.
char key[] = "hello";

Then you need an index and a count.
int key_index = 0;
int key_count = 5;

> If (keyIsNotExhaust) Encryption = currChar + key; else Encryption = currChar + prevChar;
The first part of this being something like
if ( key_index < key_count ) Encryption = currChar + key[key_index]; key_index += 1; Popular pages Recent additions c programming, code, explain, int, interpretation 