@@ -4,10 +4,47 @@ using StaticArrays
4
4
using ChaChaCiphers. ChaCha
5
5
6
6
"""
7
- ChaChaStream
7
+ ChaChaStream <: AbstractChaChaStream
8
8
9
- A cryptographically secure pseudo-random number generator
10
- (CRNG) based on the ChaCha stream cipher.
9
+ `ChaChaStream` provides access to the keystream generated by the
10
+ ChaCha stream cipher. It can be used as a cryptographically
11
+ secure random number generator (CRNG) for Julia's random number
12
+ generation functions.
13
+
14
+ ## Examples
15
+
16
+ Create a `ChaChaStream` with a randomly-generated key and nonce:
17
+
18
+ ```@meta
19
+ DocTestSetup = quote
20
+ using ChaChaCiphers
21
+ using Random
22
+ end
23
+ ```
24
+
25
+ ```jldoctest
26
+ julia> stream = ChaCha20Stream();
27
+ ```
28
+
29
+ Create a `ChaChaStream` with a pre-specified key and nonce, and
30
+ use it to generate random data:
31
+
32
+ ```jldoctest
33
+ julia> key = UInt32.([
34
+ 0xe2e39848, 0x70bb974d, 0x845f88b4, 0xb30725e4,
35
+ 0x15c309dc, 0x72d545bb, 0x466e99e3, 0x6a759f91
36
+ ]);
37
+
38
+ julia> nonce = UInt64(1234);
39
+
40
+ julia> stream = ChaCha20Stream(key, nonce);
41
+
42
+ julia> randn(stream)
43
+ 0.7689072580509484
44
+
45
+ julia> randstring(stream, 'a':'z', 8)
46
+ "klmptewr"
47
+ ```
11
48
"""
12
49
mutable struct ChaChaStream <: AbstractChaChaStream
13
50
key :: SVector{8,UInt32}
@@ -24,7 +61,7 @@ mutable struct ChaChaStream <: AbstractChaChaStream
24
61
position = 1 ;
25
62
doublerounds = 10
26
63
)
27
- if doublerounds < 0 || ! iseven (doublerounds)
64
+ if doublerounds ≤ 0
28
65
error (" `doublerounds` must be an even positive number" )
29
66
end
30
67
@@ -39,11 +76,32 @@ mutable struct ChaChaStream <: AbstractChaChaStream
39
76
end
40
77
41
78
# Constructors
79
+
80
+ """
81
+ ChaCha20Stream(args...)
82
+
83
+ Create a keystream for a ChaCha20 stream cipher.
84
+ """
42
85
ChaCha20Stream (args... ) = ChaChaStream (args... ; doublerounds= 10 )
86
+
87
+ """
88
+ ChaCha12Stream(args...)
89
+
90
+ Create a keystream for a ChaCha12 stream cipher.
91
+ """
43
92
ChaCha12Stream (args... ) = ChaChaStream (args... ; doublerounds= 6 )
44
93
45
- Base. show (io:: IO , rng:: ChaChaStream ) =
46
- write (io, " ChaChaStream(key=$(rng. key) , nonce=$(rng. nonce) , counter=$(rng. counter) )" )
94
+ function Base. show (io:: IO , rng:: ChaChaStream )
95
+ msg = """
96
+ ChaChaStream(
97
+ key = $(key (rng))
98
+ nonce = $(nonce (rng)) ,
99
+ counter = $(counter (rng)) ,
100
+ rounds = $(2 * doublerounds (rng))
101
+ )"""
102
+
103
+ write (io, msg)
104
+ end
47
105
48
106
buffer_size (stream:: ChaChaStream ) = length (stream. buffer) - stream. position + 1
49
107
0 commit comments