Caesar密码是传统的代替加密法
    加密公式:
    一、Caesar(凯撒)加密 - 图1
    加密核心

    1. for (int i = 0; i < s.length(); i++){
    2. if(str[i] >= 'a' && str[i] <= 'z') //小写字母
    3. str[i]=(char)((str[i]+n-97)%26+97);
    4. else
    5. str[i]=(char)((str[i]+n-65)%26+65); //大写字母
    6. }

    解密公式
    一、Caesar(凯撒)加密 - 图2
    解密核心

    1. for (int i = 0; i < s.length(); i++) {
    2. if (str[i] >= 'a' && str[i] <= 'z') //小写字母
    3. str[i] = (char) ((str[i] - 97 + 26 - n) % 26 + 97);
    4. else //大写字母
    5. str[i] = (char) ((str[i] - 65 + 26 - n) % 26 + 65);
    6. }

    完整代码:

    1. #include<bits/stdc++.h>
    2. using namespace std;
    3. // 判断 是否为字母
    4. //若均为字母,返回1 有其他字符返回 0
    5. bool isAlpha(string& str) {
    6. for (int i = 0; i < str.length(); i++)
    7. {
    8. if (!(str[i] >= 'a' && str[i] <= 'z' || str[i] >= 'A' && str[i] <= 'Z'))
    9. return false;
    10. }
    11. return true;
    12. }
    13. //输出
    14. void printStr(string& str) {
    15. for (int i = 0; i < str.length(); i++)
    16. {
    17. cout << str[i];
    18. }
    19. cout << endl;
    20. }
    21. //加密函数
    22. void encryption(string &str,int key) {
    23. //if (str[i] >= 'a' && str[i] <= 'z')
    24. //加密
    25. for (int i = 0; i < str.length(); i++) {
    26. if (str[i] >= 'a' && str[i] <= 'z') //小写字母
    27. str[i] = (str[i] + key - 97) % 26 + 97;
    28. else
    29. str[i] = (str[i] + key - 65) % 26 + 65; //大写字母
    30. }
    31. }
    32. //解密函数
    33. void decryption(string& str, int key) {
    34. //解密
    35. for (int i = 0; i < str.length(); i++) {
    36. if (str[i] >= 'a' && str[i] <= 'z') //小写字母
    37. str[i] = (str[i] - 97 + 26 - key) % 26 + 97;
    38. else //大写字母
    39. str[i] = (str[i] - 65 + 26 - key) % 26 + 65;
    40. }
    41. }
    42. int main() {
    43. string str="Hello";
    44. int n = 24;
    45. int key = n % 26; //密钥,移动key位
    46. int flag=isAlpha(str);
    47. if (flag == 0) { //若有其他字符,直接结束
    48. return -1;
    49. }
    50. printStr(str); //明文
    51. encryption(str,key);
    52. printStr(str); //密文
    53. decryption(str, key);
    54. printStr(str); //解密
    55. system("pause");
    56. return 0;
    57. }