v / vlib / crypto / cipher / xor_generic.v
33 lines · 30 sloc · 1.03 KB · 763f94388b1ceff59c3e68ebda2c9f57197f32a4
Raw
1// Copyright (c) 2019-2024 Alexander Medvednikov. All rights reserved.
2// Use of this source code is governed by an MIT license
3// that can be found in the LICENSE file.
4module cipher
5
6// NOTE: Implement other versions (joe-c)
7// xor_bytes xors the bytes in a and b. The destination should have enough
8// space, otherwise xor_bytes will panic. Returns the number of bytes xor'd.
9pub fn xor_bytes(mut dst []u8, a []u8, b []u8) int {
10 mut n := a.len
11 if b.len < n {
12 n = b.len
13 }
14 if n == 0 {
15 return 0
16 }
17 safe_xor_bytes(mut dst, a, b, n)
18 return n
19}
20
21// safe_xor_bytes XORs the bytes in `a` and `b` into `dst` it does so `n` times.
22// Please note: `n` needs to be smaller or equal than the length of `a` and `b`.
23pub fn safe_xor_bytes(mut dst []u8, a []u8, b []u8, n int) {
24 for i in 0 .. n {
25 dst[i] = a[i] ^ b[i]
26 }
27}
28
29// xor_words XORs multiples of 4 or 8 bytes (depending on architecture.)
30// The slice arguments `a` and `b` are assumed to be of equal length.
31pub fn xor_words(mut dst []u8, a []u8, b []u8) {
32 safe_xor_bytes(mut dst, a, b, b.len)
33}
34