编辑代码


function getCodes(value, fixValue, length) {
    // 创建一个长度为 length 的数组,并用 fixValue 填充
    let codes = new Array(length).fill(fixValue); 
    // 将字符串 value 转换为 UTF-8 编码的 Uint8Array
    let buffers = new TextEncoder().encode(value);

    // 将 buffers 中的值填充到 codes 数组中
    for (let i = 0; i < Math.min(buffers.length, length); i++) {
        codes[i] = buffers[i];
    }

    return codes;
}

function formatString(value, format) {
    return value.toString().padStart(format.length, '0');
}

function getCodes2(value, segmentLength) {
    let list = [];
    for (let i = 0; i < value.length; i += segmentLength) {
        let item = value.slice(i, i + segmentLength);
        list.push(item);
    }
    return list;
}

function shift(codes) {
    for (let i = 0; i < codes.length; i += 2) {
        [codes[i], codes[i + 1]] = [codes[i + 1], codes[i]];
    }
    return codes;
}


function plus(a, b) {
    let result = [];
    for (let i = 0; i < a.length; i++) {
        result.push((a[i] + b[i]) % 1000); // 假设编码范围在0-999之间
    }
    return result;
}

const TOTAL_CODES_LEN = 80;   
const original = '123';
const key = 'dsc28682266'
if (original.length > TOTAL_CODES_LEN) {
    throw new Error("Original length exceeds TOTAL_CODES_LEN");
}

// 获取原文编码,长度TOTAL_CODES_LEN,空缺用1填补
let oriValue = getCodes(original, 1, TOTAL_CODES_LEN);
// 获取秘钥编码,长度TOTAL_CODES_LEN,空缺用11填补
let keyValue = getCodes(key, 11, TOTAL_CODES_LEN);
//console.log(oriValue);
//console.log(keyValue);
let encryptValue = plus(oriValue.map(Number), keyValue.map(Number));
//console.log(encryptValue);
// 格式化编码
let encryptString = encryptValue.map(v => formatString(v, '000')).join('');
//console.log(encryptString);
// 按4个字符进行分割.
let codes = getCodes2(encryptString, 4);
// 每4个字符为单位,前后对调.
codes = shift(codes);
encryptString = codes.join('');
//console.log(encryptString);
// 按3个字符进行分割.
codes = getCodes2(encryptString, 3);
//console.log(codes);
let tempString = '';
for (let item of codes) {
    let code = parseInt(item, 10);
    // 对于65-90|| 97-122转换成字符
    if ((code >= 65 && code <= 90) || (code >= 97 && code <= 122)) {
        tempString += String.fromCharCode(code);
    } else {
        tempString += item;
    }
}

console.log(tempString);