JavaScript实现恺撒密码加密/解密

//仅限英文

// 加密
function encrypt(str, num) {
  var outStr = "";
  //循环处理字符串每一个字母
  for (let i = 0; i < str.length; i++) {
    //判断如果是大写字母
    if (str.charCodeAt(i) >= 65 && str.charCodeAt(i) <= 90) {
      //获取该字母的ASCII码,做相应处理后再次转换为字母添加入字符串
      outStr += String.fromCharCode((str.charCodeAt(i) - 65 + num + 26) % 26 + 65)
    }
    //判断如果是小写字母
    else if (str.charCodeAt(i) >= 97 && str.charCodeAt(i) <= 122) {
      //获取该字母的ASCII码,做相应处理后再次转换为字母添加入字符串
      outStr += String.fromCharCode((str.charCodeAt(i) - 97 + num + 26) % 26 + 97)
    }
    //其他类型的字符不做处理
    else outStr += String.fromCharCode(str.charCodeAt(i));
  }
  //返回加密后的字符串
  return outStr;
}

  // 解密
function decrypt(str, num) {
  var outStr = "";
  //循环处理字符串每一个字母
  for (let i = 0; i < str.length; i++) {
    //判断如果是大写字母
    if (str.charCodeAt(i) >= 65 && str.charCodeAt(i) <= 90) {
      //获取该字母的ASCII码,做相应处理后再次转换为字母添加入字符串
      outStr += String.fromCharCode((str.charCodeAt(i) - 65 - num + 26) % 26 + 65)
    }
    //判断如果是小写字母
    else if (str.charCodeAt(i) >= 97 && str.charCodeAt(i) <= 122) {
      //获取该字母的ASCII码,做相应处理后再次转换为字母添加入字符串
      outStr += String.fromCharCode((str.charCodeAt(i) - 97 - num + 26) % 26 + 97)
    }
    //其他类型的字符不做处理
    else outStr += String.fromCharCode(str.charCodeAt(i));
  }
  //返回解密后的字符串
  return outStr;
}

//调用

var result1 = encrypt("Hello!", 3);
var result2 = decrypt(result1, 3);
console.log(result1);
console.log(result2);

//输出结果

猜你喜欢

转载自blog.csdn.net/BYZY1314/article/details/128096505