简体   繁体   English

Caesar Cipher C程序未正确加密

[英]Caesar Cipher C program is not encrypting correctly

I've written a Caesar Cipher program for my class on C, and it doesn't seem to be encrypting correctly. 我在C上为我的班级编写了一个Caesar Cipher程序,它似乎没有正确加密。 The program takes input from a sentence "THE QUICK BROWN FOX JUMPS OVER THE LAZY DOG" and encrypts it using the Caesar Cipher method taking an enckey from the keyboard input. 该程序从句子“快速布朗的狐狸跳过懒惰狗”中获取输入,并使用Caesar Cipher方法从键盘输入中获取加密来加密它。 When it encrypts it, it does not do it correctly, and it decrypts it into nonsense. 当它加密它时,它没有正确地执行它,并且它将其解密为废话。 I looked over it and cannot figure out where I messed up to why it isn't encrypting the sentence in the proper way. 我查看它,无法弄清楚我搞砸了为什么它没有以正确的方式加密句子。

Here's the code: 这是代码:

#include <stdio.h>
#include <stdlib.h>


int  Caesar_encrypt(char *p, char *s, int enckey);
int  Caesar_decrypt(char *p, char *s, int enckey);

int main(void){
  char A[]="THE QUICK BROWN FOX JUMPS OVER THE LAZY DOG";
  char B[50], /* stores encrypted output string  */
  C[50];  /* stores decrypted output using string B as source */
  int enckey,
  statuse, statusd; /* they store return values from the functions */

  printf("Plaintext for encryption is : %s \n", A);

  printf("Input numerical key for Caesar's cypher : ");
  scanf("%d",&enckey);
  putchar('\n');
  printf("You entered encryption key %d \n", enckey);

  /* encrypt by Caesar's cypher */
  statuse= Caesar_encrypt( A, B, enckey);

  printf("Ciphertext is : %s \n", B);

 /* decrypt by Caesar's cypher */
  statusd = Caesar_decrypt( B, C, enckey);
  printf("Decrypted text is: %s \n", C); 


  exit (0);
}

int  Caesar_encrypt(char *p, char *s, int enckey){
    *s = ((*p + enckey)%26) + 65 ;
    return 0;
}

int Caesar_decrypt(char *p, char *s, int enckey){
    *s = ((*p - enckey)%26) + 65 ;
    return 0;
}

If you could help me in anyway that would be great 无论如何你可以帮助我,这将是伟大的

Thanks for your time. 谢谢你的时间。

You are en/decrypting only the first character of the string. 您只能/解密字符串的第一个字符。 You must loop through all characters of the string. 您必须循环遍历字符串的所有字符。

And there is a problem with the en/decryption of the SPACE character. 并且SPACE字符的加密/解密存在问题。 I leave this as an exercise for you. 我把这作为锻炼给你。

#include <ctype.h>

int  Caesar_encrypt(char *p, char *s, int enckey){
    for(; *p ; ++s, ++p){
        *s = isupper(*p) ? (*p - 'A' + enckey)%26 + 'A' : *p;
    }
    *s = '\0';
    return 0;//?
}

int Caesar_decrypt(char *p, char *s, int enckey){
    for(; *p ; ++s, ++p){
        *s = isupper(*p) ? (*p - 'A' + (26-enckey))%26 + 'A' : *p;
    }
    *s = '\0';
    return 0;//?
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM