1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89
| import crypto from 'crypto';
const algorithm = 'aes-256-cbc'; const key = crypto.randomBytes(32); const iv = crypto.randomBytes(16);
function bitwiseEncrypt(data) { let encrypted = ''; for (let i = 0; i < data.length; i++) { encrypted += String.fromCharCode(data.charCodeAt(i) ^ 0xAA); } return encrypted; }
function bitwiseDecrypt(data) { let decrypted = ''; for (let i = 0; i < data.length; i++) { decrypted += String.fromCharCode(data.charCodeAt(i) ^ 0xAA); } return decrypted; }
function encrypt(data) { const dataString = JSON.stringify(data); const bitwiseEncryptedData = bitwiseEncrypt(dataString); const cipher = crypto.createCipheriv(algorithm, Buffer.from(key), iv); let encrypted = cipher.update(bitwiseEncryptedData); encrypted = Buffer.concat([encrypted, cipher.final()]); return iv.toString('hex') + ':' + encrypted.toString('hex'); }
function decrypt(encryptedString) { try { const [ivText, encryptedText] = encryptedString.split(':'); const iv = Buffer.from(ivText, 'hex'); const encrypted = Buffer.from(encryptedText, 'hex'); const decipher = crypto.createDecipheriv(algorithm, Buffer.from(key), iv); let decrypted = decipher.update(encrypted); decrypted = Buffer.concat([decrypted, decipher.final()]); const decryptedData = decrypted.toString(); const bitwiseDecryptedData = bitwiseDecrypt(decryptedData); return JSON.parse(bitwiseDecryptedData); } catch (e) { return encryptedString; } }
function encryptOrDecrypt(data) { if (typeof data === 'string') { try { const decrypted = decrypt(data); if (decrypted !== data) { return decrypted; } } catch (e) { } } return encrypt(data); }
const originalData = { name: 'Alice', age: 25 };
const encrypted = encryptOrDecrypt(originalData); console.log('加密后的字符串:', encrypted);
const decrypted = encryptOrDecrypt(encrypted); console.log('解密后的数据:', decrypted);
const plainText = 'This is a plain text'; const encryptedPlainText = encryptOrDecrypt(plainText); console.log('加密后的普通文本:', encryptedPlainText);
const decryptedPlainText = encryptOrDecrypt(encryptedPlainText); console.log('解密后的普通文本:', decryptedPlainText);
|