feat(server): 新增云端缓存与同步服务端骨架
Ultraworked with [Sisyphus](https://github.com/code-yeongyu/oh-my-openagent) Co-authored-by: Sisyphus <clio-agent@sisyphuslabs.ai>
This commit is contained in:
49
server/src/crypto.js
Normal file
49
server/src/crypto.js
Normal file
@@ -0,0 +1,49 @@
|
||||
const crypto = require('crypto');
|
||||
const config = require('./config');
|
||||
|
||||
function getKey() {
|
||||
if (!config.crypto.secret) {
|
||||
throw new Error('APP_ENCRYPTION_SECRET 未配置');
|
||||
}
|
||||
return crypto.createHash('sha256').update(String(config.crypto.secret)).digest();
|
||||
}
|
||||
|
||||
function encryptJson(value) {
|
||||
const plainText = JSON.stringify(value);
|
||||
const iv = crypto.randomBytes(12);
|
||||
const cipher = crypto.createCipheriv('aes-256-gcm', getKey(), iv);
|
||||
const encrypted = Buffer.concat([cipher.update(plainText, 'utf8'), cipher.final()]);
|
||||
const tag = cipher.getAuthTag();
|
||||
const payloadHash = crypto.createHash('sha256').update(plainText).digest('hex');
|
||||
|
||||
return {
|
||||
ciphertext: encrypted.toString('base64'),
|
||||
iv: iv.toString('base64'),
|
||||
tag: tag.toString('base64'),
|
||||
payloadHash
|
||||
};
|
||||
}
|
||||
|
||||
function decryptJson(record) {
|
||||
const decipher = crypto.createDecipheriv(
|
||||
'aes-256-gcm',
|
||||
getKey(),
|
||||
Buffer.from(record.iv, 'base64')
|
||||
);
|
||||
decipher.setAuthTag(Buffer.from(record.tag, 'base64'));
|
||||
const decrypted = Buffer.concat([
|
||||
decipher.update(Buffer.from(record.ciphertext, 'base64')),
|
||||
decipher.final()
|
||||
]);
|
||||
return JSON.parse(decrypted.toString('utf8'));
|
||||
}
|
||||
|
||||
function sha256(value) {
|
||||
return crypto.createHash('sha256').update(String(value || '')).digest('hex');
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
encryptJson,
|
||||
decryptJson,
|
||||
sha256
|
||||
};
|
||||
Reference in New Issue
Block a user