-
Notifications
You must be signed in to change notification settings - Fork 2
/
base64.js
89 lines (72 loc) · 2.47 KB
/
base64.js
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
'use strict';
const fs = require('fs');
const codecUtils = require('./utils/codec-utils');
const convert = require('./utils/convertion-utils');
function setCharAt(str, index, chr) {
return (index > str.length - 1) ? str : `${str.substr(0, index)}${chr}${str.substr(index + 1)}`;
}
function encodingSystem(slice) {
const sliceLength = slice.length;
let encoded = '';
// if this slice/block have 3 bytes
if (sliceLength === 3) {
encoded = codecUtils.encodingBlock(slice);
} else if (sliceLength === 2) {
slice += '\u0000';
encoded = codecUtils.encodingBlock(slice);
// add =
encoded = setCharAt(encoded, 3, '=');
} else {
slice += '\u0000\u0000';
encoded = codecUtils.encodingBlock(slice);
// add '=''='
encoded = setCharAt(encoded, 2, '=');
encoded = setCharAt(encoded, 3, '=');
}
return encoded;
}
module.exports = {
encode: function (str, type) {
// First step, divid the input bytes streams into blocks of 3 bytes.
const inputSliced = convert.stringToNCharArray(str, 3);
// encode all 3 byte blocks
const encodedText = inputSliced.map(char => encodingSystem(char)).join('');
// encoding type
return (type === 'MIME') ? codecUtils.convertToMIME(encodedText) : encodedText;
},
encodeWithKey: function (str, key) {
return this.encode(codecUtils.xorEncoding(str, key));
},
encodeFile: function (file) {
const inputData = fs.readFileSync(file, 'binary');
return this.encode(inputData);
},
decode: function (str) {
// auto detect MIME type
const inputStr = (codecUtils.isMIME(str)) ? codecUtils.decodeMIME(str) : str;
// reverse process
let decodedString = '';
// slice string into 4 byte slices
const inputSliced = convert.stringToNCharArray(inputStr, 4);
// decoding every slice except the last one
for (let i = 0, sliceLength = inputSliced.length; i < sliceLength; ++i) {
decodedString += codecUtils.decodingBlock(inputSliced[i]);
}
// last slice
if (inputStr.slice(-1) === '=') {
decodedString = decodedString.slice(0, decodedString.length - 1);
}
if (inputStr.slice(-2) === '==') {
decodedString = decodedString.slice(0, decodedString.length - 1);
}
// result
return decodedString;
},
decodeWithKey: function (str, key) {
return codecUtils.xorEncoding(this.decode(str), key);
},
decodeToFile: function (str, filePath) {
const data = this.decode(str);
fs.writeFileSync(filePath, data, 'binary');
},
};