@@ -68,17 +68,19 @@ let check_sign (sign_key: string) (msg: string): string option =
68
68
69
69
(* with chacha20, encryption is the same operation as decryption (xoring with
70
70
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 =
73
72
let n = String. length msg in
73
+ assert (n > 0 && String. length cipher_key = 16 && ! stream_offs > = Int64. zero);
74
74
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
76
76
chacha20#transform src_dst 0 src_dst 0 n;
77
77
chacha20#wipe;
78
+ (* update stream offset *)
79
+ stream_offs := Int64. add ! stream_offs (Int64. of_int n);
78
80
Bytes. unsafe_to_string src_dst
79
81
80
82
(* 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 )
82
84
(rng : Cryptokit.Random.rng )
83
85
(counter : int ref )
84
86
(m : 'a ): string =
@@ -91,15 +93,16 @@ let encode (sign_key: string) (cipher_key: string)
91
93
let nonce = Nonce_store. fresh counter in
92
94
(* Log.debug "enc. nonce = %s" nonce; *)
93
95
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
95
97
(sign sign_key encrypted) ^ encrypted
96
98
97
99
(* 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 =
99
102
match check_sign sign_key s with
100
103
| None -> None
101
104
| Some encrypted ->
102
- let str = transform cipher_key encrypted in
105
+ let str = transform cipher_key stream_offs encrypted in
103
106
(* leading salt (8 first bytes) is ignored *)
104
107
(* let salt = String.sub str 0 8 in
105
108
* let salt_hex = Utils.convert `To_hexa salt in
0 commit comments