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
])
36 # In-place XOR `self` with `key`
37 fun xor
(key
: CString, len
: Int, key_length
: Int, key_offset
: nullable Int) do
38 if key_offset
== null then key_offset
= 0
40 var key_pos
= key_offset
% key_length
42 for i
in [0 .. len
[ do
43 self[i
] = key
[key_pos
] ^
self[i
]
45 if key_pos
>= key_length
then key_pos
= 0
50 # Base class to modelize cryptographic ciphers
54 var ciphertext
= new Bytes.empty
is writable
57 var plaintext
= new Bytes.empty
is writable
59 # Encrypt plaintext and populate `self.ciphertext`
60 fun encrypt
is abstract
62 # Decrypt ciphertext and populate `self.plaintext`
63 fun decrypt
is abstract
67 # Simple XOR cipher where the whole plaintext is XORed with a single byte.
68 class SingleByteXorCipher
71 # Cryptographic key used in encryption and decryption.
72 var key
: Byte = 0.to_b
75 var key_bytes
= new Bytes.with_capacity
(1)
77 ciphertext
= plaintext
.xorcipher
(key_bytes
)
81 var key_bytes
= new Bytes.with_capacity
(1)
83 plaintext
= ciphertext
.xorcipher
(key_bytes
)
87 # XOR cipher where the key is repeated to match the length of the message.
88 class RepeatingKeyXorCipher
91 # Cryptographic key used in encryption and decryption.
92 var key
= new Bytes.empty
96 ciphertext
= plaintext
.xorcipher
(key
)
100 assert key
.length
> 0
101 plaintext
= ciphertext
.xorcipher
(key
)