2017-10-22 09:10:33 +08:00
|
|
|
"use strict";
|
|
|
|
|
2017-10-29 07:55:55 +08:00
|
|
|
const crypto = require('crypto');
|
|
|
|
|
2017-10-15 11:31:44 +08:00
|
|
|
function newNoteId() {
|
2017-10-29 00:12:20 +08:00
|
|
|
return randomString(12);
|
2017-10-15 11:31:44 +08:00
|
|
|
}
|
|
|
|
|
2017-10-29 00:12:20 +08:00
|
|
|
const ALPHA_NUMERIC = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
|
|
|
|
|
2017-10-29 01:19:12 +08:00
|
|
|
function randomString(length) {
|
2017-10-15 11:31:44 +08:00
|
|
|
let result = '';
|
|
|
|
|
|
|
|
for (let i = length; i > 0; --i) {
|
2017-10-29 00:12:20 +08:00
|
|
|
result += ALPHA_NUMERIC[Math.floor(Math.random() * ALPHA_NUMERIC.length)];
|
2017-10-15 11:31:44 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
return result;
|
|
|
|
}
|
|
|
|
|
2017-10-29 07:55:55 +08:00
|
|
|
function randomSecureToken(bytes = 32) {
|
2017-10-29 23:22:41 +08:00
|
|
|
return crypto.randomBytes(bytes).toString('base64');
|
2017-10-29 07:55:55 +08:00
|
|
|
}
|
|
|
|
|
2017-10-15 11:31:44 +08:00
|
|
|
function nowTimestamp() {
|
2017-10-16 05:07:34 +08:00
|
|
|
return Math.floor(Date.now() / 1000);
|
2017-10-15 11:31:44 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
function toBase64(plainText) {
|
|
|
|
return Buffer.from(plainText).toString('base64');
|
|
|
|
}
|
|
|
|
|
|
|
|
function fromBase64(encodedText) {
|
|
|
|
return Buffer.from(encodedText, 'base64');
|
|
|
|
}
|
|
|
|
|
2017-10-30 02:55:48 +08:00
|
|
|
function hmac(secret, value) {
|
|
|
|
const hmac = crypto.createHmac('sha256', Buffer.from(secret.toString(), 'ASCII'));
|
|
|
|
hmac.update(value.toString());
|
|
|
|
return hmac.digest('base64');
|
|
|
|
}
|
|
|
|
|
2017-10-15 11:31:44 +08:00
|
|
|
module.exports = {
|
2017-10-29 07:55:55 +08:00
|
|
|
randomSecureToken,
|
2017-10-29 00:12:20 +08:00
|
|
|
randomString,
|
2017-10-15 11:31:44 +08:00
|
|
|
nowTimestamp,
|
|
|
|
newNoteId,
|
|
|
|
toBase64,
|
2017-10-30 02:55:48 +08:00
|
|
|
fromBase64,
|
|
|
|
hmac
|
2017-10-15 11:31:44 +08:00
|
|
|
};
|