package elliptic
import (
"crypto/elliptic"
"crypto/rand"
"errors"
"fmt"
"golang.org/x/crypto/curve25519"
)
var errInvalidNamedCurve = errors .New ("invalid named curve" )
type CurvePointFormat byte
const (
CurvePointFormatUncompressed CurvePointFormat = 0
)
type Keypair struct {
Curve Curve
PublicKey []byte
PrivateKey []byte
}
type CurveType byte
const (
CurveTypeNamedCurve CurveType = 0x03
)
func CurveTypes () map [CurveType ]struct {} {
return map [CurveType ]struct {}{
CurveTypeNamedCurve : {},
}
}
type Curve uint16
const (
P256 Curve = 0x0017
P384 Curve = 0x0018
X25519 Curve = 0x001d
)
func (c Curve ) String () string {
switch c {
case P256 :
return "P-256"
case P384 :
return "P-384"
case X25519 :
return "X25519"
}
return fmt .Sprintf ("%#x" , uint16 (c ))
}
func Curves () map [Curve ]bool {
return map [Curve ]bool {
X25519 : true ,
P256 : true ,
P384 : true ,
}
}
func GenerateKeypair (c Curve ) (*Keypair , error ) {
switch c {
case X25519 :
tmp := make ([]byte , 32 )
if _ , err := rand .Read (tmp ); err != nil {
return nil , err
}
var public , private [32 ]byte
copy (private [:], tmp )
curve25519 .ScalarBaseMult (&public , &private )
return &Keypair {X25519 , public [:], private [:]}, nil
case P256 :
return ellipticCurveKeypair (P256 , elliptic .P256 (), elliptic .P256 ())
case P384 :
return ellipticCurveKeypair (P384 , elliptic .P384 (), elliptic .P384 ())
default :
return nil , errInvalidNamedCurve
}
}
func ellipticCurveKeypair(nc Curve , c1 , c2 elliptic .Curve ) (*Keypair , error ) {
privateKey , x , y , err := elliptic .GenerateKey (c1 , rand .Reader )
if err != nil {
return nil , err
}
return &Keypair {nc , elliptic .Marshal (c2 , x , y ), privateKey }, nil
}
The pages are generated with Golds v0.8.2 . (GOOS=linux GOARCH=amd64)
Golds is a Go 101 project developed by Tapir Liu .
PR and bug reports are welcome and can be submitted to the issue list .
Please follow @zigo_101 (reachable from the left QR code) to get the latest news of Golds .