凯撒密码漏洞

Caesar Cipher Code Flaw

我编写了一个似乎在大多数测试中都有效但在少数情况下失败的凯撒密码。更多关于测试的细节是https://www.hackerrank.com/challenges/caesar-cipher-1

基本信息:密码只加密字母,符号等不加密。

在这种情况下失败:

90
!m-rB`-oN!.W`cLAcVbN/CqSoolII!SImji.!w/`Xu`uZa1TWPRq`uRBtok`xPT`lL-zPTc.BSRIhu..-!.!tcl!-U
62

其中90为n(字符串中的字符),第二行为数组s中的字符串,62为k(字母旋转量)

任何对我的代码缺陷的洞察力都将受到高度赞赏

代码:

int main(){
int n;
scanf("%d",&n);
char* s = (char *)malloc(10240 * sizeof(char));
scanf("%s",s);
int k;
scanf("%d",&k);

if (k>26) {
    k%=26;
}

int rotation;
for(int i = 0; i<n; i++) {
    if (s[i] >= 'a' && s[i] <= 'z') {
        if((s[i] + k) > 'z' ) {
            rotation = (s[i] - 26) + k;
            s[i] = rotation;
        } else {
            s[i] = s[i]+k;
        }

    } else if (s[i] >= 'A' && s[i] <= 'Z') {
        if((s[i] + k) >= 'Z' ) {
            rotation = (s[i] - 26) + k;
            s[i] = rotation;
        } else {
            s[i] = s[i]+k;
        }
    } 

}

for(int i=0; i<n; i++) {
    printf("%c", s[i]);
}

return 0;
}

好的,伙计们,我已经弄明白了。

Old Code:
 if((s[i] + k) >= 'Z' )
New Code:
 if((s[i] + k) > 'Z' )

当给定一个 P(ascii 80) 时,它搞砸了,它应该在 Z(ascii 90) 处停止,但却做了这个计算:

s[i] - 26 + k  = 64
  80 - 26 + 10 = 64 (ascii for @) and thus '@' was returned instead of Z