Skip to content

[js] 第8天 写一个加密字符串的方法 #24

Open
@haizhilin2013

Description

@haizhilin2013
Collaborator

第8天 写一个加密字符串的方法

Activity

linghucq1

linghucq1 commented on May 8, 2019

@linghucq1
function strEncrypt(str) {
  return str.split('').map(s => {
    return String.fromCharCode(s.charCodeAt() + 1)
  }).join('')
}

console.log(strEncrypt('hello world')) // ifmmp!xpsme
myprelude

myprelude commented on Jun 13, 2019

@myprelude
escape("我是被简单的加密了") // "%u6211%u662F%u88AB%u7B80%u5355%u7684%u52A0%u5BC6%u4E86"
MartinsYong

MartinsYong commented on Jun 24, 2019

@MartinsYong

仅支持浏览器端:

function encode (str) {
	return btoa(encodeURIComponent(str));
}

function decode (str) {
	return decodeURIComponent(atob(str));
}

源自阮一峰《JavaScript 标准教程》

Konata9

Konata9 commented on Jul 5, 2019

@Konata9
// 利用 base64, 浏览器环境自带 btoa / atob 方法
// Node.js 需要引入相关库
const str = "abcdefg";

console.log(btoa(str));
console.log(atob(btoa(str)));

// 凯撒密码
const encodeCaesar = ({str = "", padding = 3}) =>
  !str
    ? str
    : str
        .split("")
        .map((s) => String.fromCharCode(s.charCodeAt() + padding))
        .join("");

const decodeCaesar = ({str = "", padding = 3}) =>
  !str
    ? str
    : str
        .split("")
        .map((s) => String.fromCharCode(s.charCodeAt() - padding))
        .join("");

console.log(encodeCaesar({str: "hello world"}));
console.log(decodeCaesar({str: "khoor#zruog"}));
kokokele

kokokele commented on Jul 9, 2019

@kokokele

题目应该加密和解密同时实现吧

haizhilin2013

haizhilin2013 commented on Jul 9, 2019

@haizhilin2013
CollaboratorAuthor

@kokokele 你可以同时实现出来

JJL-SH

JJL-SH commented on Sep 5, 2019

@JJL-SH
function encodeStr(str, key) {
  return str
    .split("")
    .map(item => {
      return item.charCodeAt() * key;
    })
    .join("#");
}
function decodeStr(str, key) {
  return str
    .split("#")
    .map(item => {
      return String.fromCharCode(+item / key);
    })
    .join("");
}

console.log(decodeStr(encodeStr("hello world", 665), 665));
pigPEQ

pigPEQ commented on Nov 8, 2019

@pigPEQ
//param:   method可选参数:encodeStr(加密)与decodeStr(解密)
var codeStr=(method,str)=>{
    var hit = method=='encodeStr'?'*':'/';
    return [...str].map((item)=>{
        return String.fromCharCode(eval(item.charCodeAt()+hit+10));
    }).join('');
}
console.log(codeStr('encodeStr','SDSAH'));
crazyming9528

crazyming9528 commented on Dec 20, 2019

@crazyming9528

js生成动态密文

前端生成的密文虽然谈不上安全,但是可以用于混淆文本,防止一些参数被猜到.

特点:
每次生成的密文都不一样,解密后的文本一样

原理:
加密:
将字符串中的字符拆分成数组并将其转为字符的八进制Unicode码->反序->分割字符串->在字符串中随机加入小写字母,将分割符替换为随机大写字母

这样最终生成了 由数字/小写字母/大写字母的 动态密文

解密:
去掉小写字母->将大写字母替换为一个分割符并用分割符 拆分字符串为数组->反序->将八进制Unicode码转字符串->将数组合并成字符串

使用场景:

隐藏一些不想让用户直接看见的参数, 比如 url中的 id 等参数,cookies中的信息等

生活使用:
也可将自己常用的密码加密后保存在电脑上,避免密码被直接暴露.

//加密
function encodeStr(str) {
if (!str) return;
var random = function (lower, upper) {
return Math.floor(Math.random() * (upper - lower + 1)) + lower;
};
var arr = str.toString().split("").map(function (item) {
return item.charCodeAt(0).toString(8)
});
arr.reverse();//反序数组
arr = arr.join("").split("");//暂时使用 _ 分割字符串;
var num = 0;
while (num < str.length) {
var r = String.fromCharCode(random(97, 122));//生成用于混淆的 的 小写字母
arr.splice(random(0, arr.length), 0, r);
num++;
}
return arr.join("").replace(/
/ig, function (str) {
return String.fromCharCode(random(65, 90));
});//将分割符 _ 替换为随机的 大写字母

}

//解密

function decodeStr(str) {
if (!str) return;
var temp = [];
str.split("").forEach(function (item) {
var code = item.charCodeAt(0);
if (code <= 90 && code >= 65) {
item = "";//将作为分割用的 随机大写字母 统一为 _ 以便切割
temp.push(item);
}else if (code <= 57 && code >= 48) {
temp.push(item);//提取 数字
}
});
temp = temp.join("").split("
");
temp.reverse();
var res = temp.map(function (item) {
return String.fromCharCode(parseInt(item, 8));
});
return res.join("");
}

https://www.crazyming.com/note/1704/

YeChang

YeChang commented on Dec 22, 2019

@YeChang
//第8天 写一个加密字符串的方法

function strEncrypt(str) {
  var sault = 3;
  return str
    .split("")
    .map(c => {
      return String.fromCharCode(c.charCodeAt(0) + sault);
    })
    .join("");
}
function strDecrypt(str) {
  var sault = 3;
  return str
    .split("")
    .map(c => {
      return String.fromCharCode(c.charCodeAt(0) - sault);
    })
    .join("");
}

var str = "hello, world";
console.log(strEncrypt(str));
console.log(strDecrypt(strEncrypt(str)));
susanforme

susanforme commented on Feb 4, 2020

@susanforme
var str="abcdqwa";
var newStr="";
function encrypt(str){
  for(var i=0;i<str.length;i++){
     newStr+=String.fromCharCode(str[i].charCodeAt()+10);
  };
  return newStr;
};
function decrypt(newStr){
  var char="";
  for(var i=0;i<newStr.length;i++){
     char+=String.fromCharCode(newStr[i].charCodeAt()-10);
  };
  return char;
}
giggleCYT

giggleCYT commented on Jun 1, 2020

@giggleCYT
    function fn(str) {
        return str.replace(/\w/g, (s) => {
            var code = s.charCodeAt();
            if (code <= 77) {
                return String.fromCharCode(code + 13);
            } else {
                return String.fromCharCode(code - 13);
            }
        })
    }
    console.log(fn("my family"));//`l YT`\_l
timeyo

timeyo commented on Jun 1, 2020

@timeyo
    function fn(str) {
        return str.replace(/\w/g, (s) => {
            var code = s.charCodeAt();
            if (code <= 77) {
                return String.fromCharCode(code + 13);
            } else {
                return String.fromCharCode(code - 13);
            }
        })
    }
    console.log(fn("my family"));//`l YT`\_l

这么搞你怎么解密

11 remaining items

Loading
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    jsJavaScript

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

      Development

      No branches or pull requests

        Participants

        @kokokele@haizhilin2013@JJL-SH@zebratt@Konata9

        Issue actions

          [js] 第8天 写一个加密字符串的方法 · Issue #24 · haizlin/fe-interview