Skip to content

Commit a9aba3f

Browse files
committed
Crypto: added stream offset management
1 parent efa09f0 commit a9aba3f

File tree

1 file changed

+10
-7
lines changed

1 file changed

+10
-7
lines changed

src/crypto.ml

Lines changed: 10 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -68,17 +68,19 @@ let check_sign (sign_key: string) (msg: string): string option =
6868

6969
(* with chacha20, encryption is the same operation as decryption (xoring with
7070
a pseudo random stream) *)
71-
let transform (cipher_key: string) (msg: string): string =
72-
assert(String.length cipher_key = 16);
71+
let transform (cipher_key: string) (stream_offs: int64 ref) (msg: string): string =
7372
let n = String.length msg in
73+
assert(n > 0 && String.length cipher_key = 16 && !stream_offs >= Int64.zero);
7474
let src_dst = Bytes.of_string msg in
75-
let chacha20 = new Cryptokit.Stream.chacha20 cipher_key in
75+
let chacha20 = new Cryptokit.Stream.chacha20 ~ctr:!stream_offs cipher_key in
7676
chacha20#transform src_dst 0 src_dst 0 n;
7777
chacha20#wipe;
78+
(* update stream offset *)
79+
stream_offs := Int64.add !stream_offs (Int64.of_int n);
7880
Bytes.unsafe_to_string src_dst
7981

8082
(* encrypt-then-sign scheme *)
81-
let encode (sign_key: string) (cipher_key: string)
83+
let encode (sign_key: string) (cipher_key: string) (stream_offs: int64 ref)
8284
(rng: Cryptokit.Random.rng)
8385
(counter: int ref)
8486
(m: 'a): string =
@@ -91,15 +93,16 @@ let encode (sign_key: string) (cipher_key: string)
9193
let nonce = Nonce_store.fresh counter in
9294
(* Log.debug "enc. nonce = %s" nonce; *)
9395
let s_n_m = (Bytes.unsafe_to_string salt) ^ nonce ^ "|" ^ maybe_compressed in
94-
let encrypted = transform cipher_key s_n_m in
96+
let encrypted = transform cipher_key stream_offs s_n_m in
9597
(sign sign_key encrypted) ^ encrypted
9698

9799
(* check-sign-then-decrypt scheme *)
98-
let decode (sign_key: string) (cipher_key: string) (s: string): 'a option =
100+
let decode (sign_key: string) (cipher_key: string) (stream_offs: int64 ref)
101+
(s: string): 'a option =
99102
match check_sign sign_key s with
100103
| None -> None
101104
| Some encrypted ->
102-
let str = transform cipher_key encrypted in
105+
let str = transform cipher_key stream_offs encrypted in
103106
(* leading salt (8 first bytes) is ignored *)
104107
(* let salt = String.sub str 0 8 in
105108
* let salt_hex = Utils.convert `To_hexa salt in

0 commit comments

Comments
 (0)