sidh-torture/csidh/ref/go-wrapper/wrapper.go

75 lines
1.7 KiB
Go
Raw Normal View History

2019-01-30 16:17:20 +00:00
package wrapper
/*
#cgo CFLAGS: -I../../ref/csidh
#cgo LDFLAGS: -L../../bin -lcsidh
#include <csidh.h>
*/
import "C"
import (
"unsafe"
csidh "github.com/henrydcase/nobs/dh/csidh"
)
const (
PrvSz = 37
PubSz = 64
SsSz = 64
)
type Ref struct {}
// Converts Golang's byte array to C's unsigned char. 'c' must
// have same size as byte
func (Ref) toBytes(c []C.uchar, b []byte) {
if len(c) != len(b) {
panic("len c!= len b")
}
for i,v := range(b) {
c[i] = C.uchar(v)
}
}
func (Ref) KeygenPrv() (prv csidh.PrivateKey) {
var buf [PrvSz]C.uchar
C.keygen_prv(&buf[0])
prv.Import(C.GoBytes(unsafe.Pointer(&buf[0]), C.int(len(buf))))
return
}
func (c Ref) KeygenPub(prv *csidh.PrivateKey) (pub csidh.PublicKey) {
var prv_c_buf [PrvSz]C.uchar
var pub_c_buf [PubSz]C.uchar
var prv_g_buf [PrvSz]byte
if !prv.Export(prv_g_buf[:]) {
panic("Can't export private key")
}
c.toBytes(prv_c_buf[:], prv_g_buf[:])
C.keygen_pub(&pub_c_buf[0], &prv_c_buf[0])
pub.Import(C.GoBytes(unsafe.Pointer(&pub_c_buf[0]), C.int(len(pub_c_buf))))
return
}
func (c Ref) Derive(ss []byte, pub *csidh.PublicKey, prv *csidh.PrivateKey) {
var prv_c_buf [PrvSz]C.uchar
var pub_c_buf [PubSz]C.uchar
var prv_g_buf [PrvSz]byte
var pub_g_buf [PubSz]byte
var ss_c_buf [SsSz]C.uchar
if !pub.Export(pub_g_buf[:]) {
panic("Can't export public key")
}
if !prv.Export(prv_g_buf[:]) {
panic("Can't export private key")
}
c.toBytes(pub_c_buf[:], pub_g_buf[:])
c.toBytes(prv_c_buf[:], prv_g_buf[:])
C.derive(&ss_c_buf[0], &pub_c_buf[0], &prv_c_buf[0])
copy(ss, C.GoBytes(unsafe.Pointer(&ss_c_buf[0]), C.int(len(ss_c_buf))))
}