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

祁腾飞 / 2023-08-04 / 原文

 

公司业务代码在异或加密基础上又加了Base6加密和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('')
  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, API_KEY)
console.log('解密后:', decryptedText)