凯撒密码算法移位 C

标签 c algorithm encryption

所以我正在编写一个 C 程序来使用自定义表来使用凯撒算法,我将在其中给出该表并使用该表进行移位,例如文本“abc”根据表“abc”与 key= 1 应该被加密为 bca,但是如果字母的键+索引高于此处存储的表的长度是我的代码,那么我在最后一个字符上遇到困难

void encrypt (char table[],char entext[],char text[],int key)

{


     int i,j;

     int k = strlen(table);

     //int result = (key + k);
     for (i=0;i<strlen(table);++i)
     {
         j = 0;
         if (text[i]!='\0')
         {
             while (text[i]!=table[j])
             {
                   j++;
             }
             if ((j+key)>k)
             {
                j=(j+key)%k;
                //j = (result - j);
             }
             else
                 j = j + key;

             entext[i] = table[j];
         }
     }
     entext[i+1] = '\0';
     puts(entext);
}

int main()

{    

    char table[100] , text[100] , entext[100] , c;

    int i , j , key;
    printf("Enter the text : ");
    gets(text);
    printf("Enter the table : ");
    gets(table);
    printf("Enter the key : ");
    scanf("%d",&key);
    encrypt(table,entext,text,key);
    system("pause");
    return 0;

}

最佳答案

if ((j+key)>k)

应该是

if ((j+key)>=k)

此外,由于 mod 的工作原理,此检查完全没有必要。我将冒昧地重写您的代码,使其看起来更好:

void encrypt (char table[],char entext[],char text[],int key)
{
     int i,j;
     int k = strlen(table);

     //int result = (key + k);
     for (i=0;i<strlen(table);++i)
     {
         if (text[i]!='\0')
         {
             for(j=0; text[i] != table[j] ;j++);

             entext[i] = table[(j+key)%k];
         }
     }
     entext[i+1] = '\0';
     puts(entext);
}

我相信你可以通过索引 char 本身的值来使这个“表”查找更有效,但是除非你正在处理相当大的输入,否则这不会真正产生影响。

关于凯撒密码算法移位 C,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22269827/

相关文章:

c - 如何在 C 中创建不间断 sleep ?

c++ - 在 C++ 代码中使用纯 C 库是否会导致性能下降/损失?

javascript - 如果我的字符串测试函数的输入为空,则返回 false

c - 为什么需要说明符限定符列表?

python - 在 Python 中从 A 到 B 算法切割路径所需的最小移除节点

java - 如何在 Java 中创建自己的 HashMap?

swift - 在 Swift 3 中创建 UnsafeMutablePointer<UInt8>

iphone - 如何根据公钥的指数和模数创建 SeckeyRef 并在 SecKeyEncrypt 方法中使用

objective-c - CCCrypt iOS5 和 iOS6 的区别

c - 调用 SIGINT 时终止线程 - C