EN
TypeScript - One-time Pad encryption with XOR
0 points
In this short article, we would like to show a simple TypeScript implementation of the most save encrytion that was invented by humans - One-time Pad encryption with XOR.
Used XOR formula:
xxxxxxxxxx
1
Encryption:
2
3
00110100 input byte
4
XOR 11000111 secret key
5
--------
6
11110011 encrypted byte
7
8
Decription:
9
10
11110010 encrypted byte
11
XOR 11000111 secret key
12
--------
13
11110011 decrypted byte == input byte
Quick solution:
1. single-byte encryption
xxxxxxxxxx
1
const inputByte: number = 97;
2
const secretKey: number = 238; // random byte used as secret key
3
4
const encryptedByte: number = inputByte ^ secretKey; // Encryption
5
const decryptedByte: number = encryptedByte ^ secretKey; // Decription
6
7
console.log(inputByte); // 97
8
console.log(encryptedByte); // 143
9
console.log(decryptedByte); // 97
2. multiple bytes encryption
xxxxxxxxxx
1
// Logic:
2
3
const encryptBytes = (secretKeys: number[], inputBytes: number[]): number[] => {
4
const encryptedBytes = Array(inputBytes.length);
5
for (let i = 0; i < inputBytes.length; ++i) {
6
encryptedBytes[i] = inputBytes[i] ^ secretKeys[i];
7
}
8
return encryptedBytes;
9
};
10
11
const decryptBytes = (secretKeys: number[], encryptedBytes: number[]): number[] => {
12
const decryptedBytes = Array(encryptedBytes.length);
13
for (let i = 0; i < encryptedBytes.length; ++i) {
14
decryptedBytes[i] = encryptedBytes[i] ^ secretKeys[i];
15
}
16
return decryptedBytes;
17
};
18
19
// Input:
20
21
const inputBytes: number[] = [97, 98, 99]; // what is 'abc' when we use UTF-8 bytes
22
const secretKeys: number[] = [238, 203, 230]; // 3 random bytes used as secret keys
23
24
// Encryption / Decryption:
25
26
const encryptedBytes: number[] = encryptBytes(secretKeys, inputBytes);
27
const decryptedBytes: number[] = decryptBytes(secretKeys, encryptedBytes);
28
29
// Result:
30
31
console.log(inputBytes); // [97, 98, 99]
32
console.log(encryptedBytes); // [143, 169, 133]
33
console.log(decryptedBytes); // [97, 98, 99]
The algorithm is as strong as perfectly random numbers have been used as secret keys.
The main concept of the algorithm is to:
- use XOR formula on the data units to encode and decode,
Hint: check Wikipedia reference to see other than XOR encryption formula.
- store on sender and recipient devices, secret keys composed of perfect random numbers
(the numbers from computer algorithms may be predictable, so use nature-based approaches), - never share the random numbers with others than the sender and the recipient,
- use always only part of secret keys to encrypt or decrypt some sent message (one byte encoded by one secret key),
- never use 2 times the same secret keys.