cgo: how to pass an entropy source from golang to C?

83 views
Skip to first unread message

David Stainton

unread,
Oct 18, 2022, 6:33:11 PM10/18/22
to golang-nuts
Greetings cgo experts, perhaps this post might also be of some interest to cryptography people as well.

What's the best way for a C cryptography library to receive entropy from golang?

There exists a C cryptography library (CTIDH, it's a PQ NIKE)... I am collaborating with C programmers who are adding features to it. I maintain cgo bindings for this library. Thus far the cgo is straight forward and it works. However the C programmers recently added a constructor for private keys which takes a function pointer as an argument:


/*
 * generate a new private key using rng_callback and write the result to (priv).
 * (priv) is passed as (context) to the rng_callback.
 */
void csidh_private_withrng(private_key *priv, ctidh_fillrandom rng_callback);

I did get this to work with an ugly hack where the golang constructor takes an io.Reader interface object as an argument and sets an unexported module scoped global variable to the rng/io.Reader object, guarded by a mutex, gross:


But that's a really ugly hack and if called by multiple threads would result in the rng getting overwritten... which in most cases is probably fine for that to happen but seems like a bad design.




David Stainton

unread,
Oct 18, 2022, 9:50:21 PM10/18/22
to golang-nuts

Okay here I've tried a similar solution to the go-pointers library... but i had to change it a bit to fit how the C library uses the context pointer:

It builds and runs... and then panics on the "rng is nil"... not sure why. So I'm going to try another solution where I change the C api slightly.

I'm convinced there are many possible solutions to this and picking one is a matter of deciding among a few tradeoffs.

David Stainton

unread,
Oct 19, 2022, 12:41:35 PM10/19/22
to golang-nuts
I think the cleanest way to solve this problem is to use the go-pointers library and pass in the opaque pointer from the application through to the go callback.

Here's a blog post I found detailing how this is done:
Reply all
Reply to author
Forward
0 new messages