优化
This commit is contained in:
@@ -0,0 +1,9 @@
|
||||
// Jest Snapshot v1, https://goo.gl/fbAQLP
|
||||
|
||||
exports[`des encrypt D 1`] = `"ihmnn4VBPYE="`;
|
||||
|
||||
exports[`des encrypt bar 1`] = `"p/PIC32MPm4="`;
|
||||
|
||||
exports[`des encrypt foo 1`] = `"NP3+ABhEiY4="`;
|
||||
|
||||
exports[`des encrypt 你 1`] = `"O5kF0LXzjpE="`;
|
||||
17
server/lib/crypto/__tests__/des.spec.ts
Normal file
17
server/lib/crypto/__tests__/des.spec.ts
Normal file
@@ -0,0 +1,17 @@
|
||||
import { desEncrypt, desDecrypt } from '../des';
|
||||
|
||||
describe('des', () => {
|
||||
const key = '12345678';
|
||||
|
||||
describe('encrypt', () => {
|
||||
test.each([['foo'], ['bar'], ['你'], ['D']])('%s', (input) => {
|
||||
expect(desEncrypt(input, key)).toMatchSnapshot();
|
||||
});
|
||||
});
|
||||
|
||||
describe('decrypt', () => {
|
||||
test.each([['foo'], ['bar'], ['你'], ['D']])('%s', (input) => {
|
||||
expect(desDecrypt(desEncrypt(input, key), key)).toBe(input);
|
||||
});
|
||||
});
|
||||
});
|
||||
24
server/lib/crypto/des.ts
Normal file
24
server/lib/crypto/des.ts
Normal file
@@ -0,0 +1,24 @@
|
||||
import crypto from 'crypto';
|
||||
import { config } from 'tailchat-server-sdk';
|
||||
|
||||
// DES 加密
|
||||
export function desEncrypt(message: string, key: string = config.secret) {
|
||||
key =
|
||||
key.length >= 8 ? key.slice(0, 8) : key.concat('0'.repeat(8 - key.length));
|
||||
const keyHex = new Buffer(key);
|
||||
const cipher = crypto.createCipheriv('des-cbc', keyHex, keyHex);
|
||||
let c = cipher.update(message, 'utf8', 'base64');
|
||||
c += cipher.final('base64');
|
||||
return c;
|
||||
}
|
||||
|
||||
// DES 解密
|
||||
export function desDecrypt(text: string, key: string = config.secret) {
|
||||
key =
|
||||
key.length >= 8 ? key.slice(0, 8) : key.concat('0'.repeat(8 - key.length));
|
||||
const keyHex = new Buffer(key);
|
||||
const cipher = crypto.createDecipheriv('des-cbc', keyHex, keyHex);
|
||||
let c = cipher.update(text, 'base64', 'utf8');
|
||||
c += cipher.final('utf8');
|
||||
return c;
|
||||
}
|
||||
Reference in New Issue
Block a user