凯撒密码加密算法

运用到同余运算,考虑边界问题等
直接上代码(objc版)


//
//  main.cpp
//  ooo
//
//  Created by doushuyao on 2018/3/20.
//  Copyright © 2018年 opooc. All rights reserved.
//

#include
#include
#include
//加密
int kaisa_encrypt(const char *str1,char *str2,  int len)
{
    int i;
    if(str1 == NULL || str2 == NULL || len <= 0){
        return -1;
    }
    int m = strlen(str1);
    if(m <= 0){
        return -1;
    }
    for(i=0;iif(str1[i]>='a'&&str1[i]<='z')

        {
         // str2[i]='a'+(str1[i]-'a'+len)%26;
         //上面这种方法可以代替下面两个if,原理是 同余运算
            if (len >26) {
                len = len%26;
            }
            if ((str1[i]+len)>'z') {
                str2[i] = ((str1[i] +len)-'a')%26+'a';
            }
            else{
                str2[i] = str1[i]+len;
            }
        }

        else
            str2[i]=str1[i];
    }
    return 0;
}
//解密
int kaisa_decrypt(const char *str2,char *str3,  int len)
{
    int i;
    char all_letter[27]="abcdefghijklmnopqrstuvwxyz";
    if(str3 == NULL || str2 == NULL || len <=0){
        return -1;
    }
    int m = strlen(str2);
    if(m <= 0){
        return -1;
    }
    if (len>26) {
        len = len%26;
    }
    for(i=0;iif(str2[i]>=all_letter[len]&&str2[i]<='z')
            str3[i]=str2[i]-len;
        else if(str2[i]>='a'&&str2[i]<=all_letter[len-1])
            str3[i]=str2[i]+(26-len);
        else
            str3[i]=str2[i];
    }
    return 0;
}

int main()
{
    char str1[20]="Apooc";
    char str2_encrypt[20]="";
    char str3_decrypt[20]="";
    /***加密****/
    kaisa_encrypt(str1,str2_encrypt,400);
    printf("原文%s-->密文%s\n",str1,str2_encrypt);
    /***解密****/
    kaisa_decrypt(str2_encrypt,str3_decrypt,400);
    printf("密文%s-->原文%s\n",str2_encrypt,str3_decrypt);

    return 0;
}

你可能感兴趣的:(信息安全)