Skip to content

Commit 0ed7483

Browse files
committed
Added cipher
1 parent 960b544 commit 0ed7483

File tree

2 files changed

+122
-0
lines changed

2 files changed

+122
-0
lines changed

cipher.js

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
const { Transform, TransformCallback } = require('stream');
2+
3+
class CeaserCipherTransform extends Transform {
4+
5+
/**
6+
* @param {number} key
7+
*/
8+
set key(key) {
9+
this._key = key;
10+
}
11+
12+
/**
13+
*
14+
* @param {Buffer} chunk
15+
* @param {BufferEncoding} encoding
16+
* @param {TransformCallback} callback
17+
*/
18+
_transform(chunk, _, callback) {
19+
this.push(cipher(chunk, this._key));
20+
callback();
21+
}
22+
}
23+
24+
function cipher(chunk, key) {
25+
return chunk.map(byte => byte + (key % 26));
26+
}
27+
28+
module.exports = { CeaserCipherTransform };

index.js

Lines changed: 94 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,94 @@
1+
"use strict";
2+
3+
const { CeaserCipherTransform } = require("./cipher");
4+
5+
/**
6+
* Encrypt a string using Caesar Cipher
7+
*
8+
* @param {string} str
9+
* @param {number} key
10+
* @returns string
11+
*/
12+
function encryptString(str, key) {
13+
return str
14+
.split("")
15+
.map((s) => s.charCodeAt(0) + (key % 26))
16+
.map((v) => String.fromCharCode(v))
17+
.join("");
18+
}
19+
20+
/**
21+
* Decrypt a string using Caesar Cipher
22+
*
23+
* @param {string} str
24+
* @param {number} key
25+
* @returns string
26+
*/
27+
function decryptString(str, key) {
28+
return str
29+
.split("")
30+
.map((s) => s.charCodeAt(0) - (key % 26))
31+
.map((v) => String.fromCharCode(v))
32+
.join("");
33+
}
34+
35+
/**
36+
* Encrypt a buffer array using Caesar Cipher
37+
*
38+
* @param {Buffer} buffer
39+
* @param {number} key
40+
* @returns buffer
41+
*/
42+
function encrypt(buffer, key) {
43+
return buffer
44+
.map((byte) => byte + (key % 26));
45+
}
46+
47+
/**
48+
* Decrypt a buffer array using Caesar Cipher
49+
*
50+
* @param {Buffer} buffer
51+
* @param {number} key
52+
* @returns buffer
53+
*/
54+
function decrypt(buffer, key) {
55+
return buffer
56+
.map((byte) => byte - (key % 26));
57+
}
58+
59+
60+
class EncryptTransform extends CeaserCipherTransform {
61+
62+
/**
63+
* Transform stream for encryption using Caesar Cipher
64+
*
65+
* @param {number} key Encryption key
66+
*/
67+
constructor(key) {
68+
super();
69+
this.key = key;
70+
}
71+
}
72+
73+
class DecryptTransform extends CeaserCipherTransform {
74+
75+
/**
76+
* Transform stream for decryption using Caesar Cipher
77+
*
78+
* @param {number} key Decryption key
79+
*/
80+
constructor(key) {
81+
super();
82+
this.key = -key;
83+
}
84+
}
85+
86+
module.exports = {
87+
encrypt,
88+
decrypt,
89+
encryptString,
90+
decryptString,
91+
EncryptTransform,
92+
DecryptTransform
93+
}
94+

0 commit comments

Comments
 (0)