1 # This file is part of NIT ( http://www.nitlanguage.org ).
3 # Licensed under the Apache License, Version 2.0 (the "License");
4 # you may not use this file except in compliance with the License.
5 # You may obtain a copy of the License at
7 # http://www.apache.org/licenses/LICENSE-2.0
9 # Unless required by applicable law or agreed to in writing, software
10 # distributed under the License is distributed on an "AS IS" BASIS,
11 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 # See the License for the specific language governing permissions and
13 # limitations under the License.
15 # XOR oriented cryptographic ciphers and utilities.
19 # Returns `self` xored with `key`
21 # The key is cycled through until the `self` has been completely xored.
23 # assert "goodmorning".to_bytes.xorcipher(" ".to_bytes) == "GOODMORNING".bytes
24 fun xorcipher
(key
: Bytes): Bytes do
25 var xored
= new Bytes.with_capacity
(self.length
)
27 for i
in self.length
.times
do
28 xored
.add
(self[i
] ^ key
[i
% key
.length
])
35 # Base class to modelize cryptographic ciphers
39 var ciphertext
= new Bytes.empty
is writable
42 var plaintext
= new Bytes.empty
is writable
44 # Encrypt plaintext and populate `self.ciphertext`
45 fun encrypt
is abstract
47 # Decrypt ciphertext and populate `self.plaintext`
48 fun decrypt
is abstract
52 # Simple XOR cipher where the whole plaintext is XORed with a single byte.
53 class SingleByteXorCipher
56 # Cryptographic key used in encryption and decryption.
57 var key
: Byte = 0.to_b
60 var key_bytes
= new Bytes.with_capacity
(1)
62 ciphertext
= plaintext
.xorcipher
(key_bytes
)
66 var key_bytes
= new Bytes.with_capacity
(1)
68 plaintext
= ciphertext
.xorcipher
(key_bytes
)
72 # XOR cipher where the key is repeated to match the length of the message.
73 class RepeatingKeyXorCipher
76 # Cryptographic key used in encryption and decryption.
77 var key
= new Bytes.empty
81 ciphertext
= plaintext
.xorcipher
(key
)
86 plaintext
= ciphertext
.xorcipher
(key
)