@@ -6,6 +6,26 @@ const schnorr_lib = @import("schnorr.zig");
66
77pub const constants = @import ("constants.zig" );
88
9+ pub fn secureRandomBytes (buf : []u8 ) void {
10+ const posix = std .posix ;
11+ const fd = posix .openatZ (std .c .AT .FDCWD , "/dev/urandom" , .{ .ACCMODE = .RDONLY }, 0 ) catch | e |
12+ std .debug .panic ("cannot open /dev/urandom: {s}" , .{@errorName (e )});
13+ defer _ = std .c .close (fd );
14+ var off : usize = 0 ;
15+ while (off < buf .len ) {
16+ const n = posix .read (fd , buf [off .. ]) catch | e |
17+ std .debug .panic ("cannot read /dev/urandom: {s}" , .{@errorName (e )});
18+ if (n == 0 ) std .debug .panic ("unexpected EOF on /dev/urandom" , .{});
19+ off += n ;
20+ }
21+ }
22+
23+ pub fn defaultCsprng () std.Random.DefaultCsprng {
24+ var seed : [std .Random .DefaultCsprng .secret_seed_length ]u8 = undefined ;
25+ secureRandomBytes (& seed );
26+ return std .Random .DefaultCsprng .init (seed );
27+ }
28+
929/// The main error type for this library.
1030pub const Error = error {
1131 /// Signature failed verification.
@@ -205,7 +225,7 @@ pub const Secp256k1 = struct {
205225
206226 // Create 32 byte random seed.
207227 var seed : [32 ]u8 = undefined ;
208- crypto . random . bytes (& seed );
228+ secureRandomBytes (& seed );
209229
210230 const res = secp256k1 .secp256k1_context_randomize (ctx , & seed );
211231 std .debug .assert (res == 1 );
@@ -441,7 +461,7 @@ pub const SecretKey = struct {
441461 defer secp .deinit ();
442462
443463 var aux : [32 ]u8 = undefined ;
444- std . crypto . random . bytes (& aux );
464+ secureRandomBytes (& aux );
445465
446466 return secp .signSchnorrHelper (& hash , try KeyPair .fromSecretKey (& secp , self ), & aux );
447467 }
@@ -458,7 +478,8 @@ pub const SecretKey = struct {
458478
459479 /// Generate random [`SecretKey`] with default random
460480 pub fn generate () SecretKey {
461- return generateWithRandom (std .crypto .random );
481+ var csprng = defaultCsprng ();
482+ return generateWithRandom (csprng .random ());
462483 }
463484
464485 pub fn fromString (data : []const u8 ) (Error || ErrorParseHex )! @This () {
0 commit comments