Skip to content

Commit f7d3d82

Browse files
committed
feat: ensure valid randomness of PrivateKey
1 parent 40f1f66 commit f7d3d82

File tree

1 file changed

+8
-10
lines changed

1 file changed

+8
-10
lines changed

Sources/zkp/secp256k1.swift

+8-10
Original file line numberDiff line numberDiff line change
@@ -151,16 +151,14 @@ extension secp256k1 {
151151

152152
/// Backing initialization that creates a random secp256k1 private key for signing
153153
@usableFromInline init(format: secp256k1.Format = .compressed) throws {
154-
let privateKey = SecureBytes(count: secp256k1.ByteDetails.count)
155-
self.keyParity = 0
156-
self.format = format
157-
self.privateBytes = privateKey
158-
self.publicBytes = try PublicKeyImplementation.generate(bytes: &privateBytes, format: format)
159-
self.xonlyBytes = try XonlyKeyImplementation.generate(
160-
bytes: publicBytes,
161-
keyParity: &keyParity,
162-
format: format
163-
)
154+
for _ in 0 ..< 10 {
155+
let randomBytes = SecureBytes(count: secp256k1.ByteDetails.count)
156+
if let privateKey = try? PrivateKeyImplementation(dataRepresentation: Data(randomBytes), format: format) {
157+
self = privateKey
158+
return
159+
}
160+
}
161+
fatalError("Looped more than 10 times trying to generate a key")
164162
}
165163

166164
/// Backing initialization that creates a secp256k1 private key for signing from a data representation.

0 commit comments

Comments
 (0)