记一次JavaScript异或算法加密 , 异或加密

 

公司业务代码在异或加密基础上又加了Base64加密和encodeURIComponet编码

const Base64 = require('base-64')
function xorEncrypt (str, key) {
  let result
  const list = []
  for (let i = 0; i < str.length; i++) {
    const charCode = str.charCodeAt(i) ^ key.charCodeAt(i % key.length)
    list.push(String.fromCharCode(charCode))
  }

  result = list.join('')
// 如果不需要base-64编码的话 在此处直接return result即可
return encodeURIComponent(Base64.encode(result)) } const encryptedText = xorEncrypt(info, API_KEY) console.log('加密后:', encryptedText)

异或加密算法

function xorEncrypt(str, key) {
  const result = [];
  for (let i = 0; i < str.length; i++) {
    const charCode = str.charCodeAt(i) ^ key.charCodeAt(i % key.length);
    result.push(String.fromCharCode(charCode));
  }
  return result.join('');
}

const plaintext = "Hello, world!";
const encryptionKey = "secret";

// 加密
const encryptedText = xorEncrypt(plaintext, encryptionKey);
console.log("加密后:", encryptedText);

// 解密
const decryptedText = xorEncrypt(encryptedText,encryptionKey)
console.log('解密后:', decryptedText)
 

 

posted @ 2023-08-04 17:54  祁腾飞  阅读(191)  评论(0编辑  收藏  举报