面试题答案
一键面试function encryptString(str) {
let encrypted = '';
for (let i = 0; i < str.length; i++) {
let charCode = str.charCodeAt(i);
let newCharCode = charCode + 10;
encrypted += String.fromCharCode(newCharCode);
}
return encrypted;
}
function decryptString(str) {
let decrypted = '';
for (let i = 0; i < str.length; i++) {
let charCode = str.charCodeAt(i);
let newCharCode = charCode - 10;
decrypted += String.fromCharCode(newCharCode);
}
return decrypted;
}
在实际混淆场景中的嵌入与还原
- 嵌入加密字符串:在混淆后的代码中,可以将加密后的字符串以字面量的形式直接嵌入。例如,将原本的字符串
'hello'
加密后变为加密字符串,然后将其作为一个变量值存储或者直接在需要使用的地方嵌入。 - 运行时还原:在运行混淆后的代码时,在需要使用原字符串的地方调用
decryptString
函数对加密字符串进行解密还原。可以在代码加载阶段或者需要使用字符串的逻辑处执行解密操作,确保使用的是原始字符串。
例如:
let encryptedStr = encryptString('hello');
// 假设在混淆代码中有如下使用
let decryptedStr = decryptString(encryptedStr);
console.log(decryptedStr);