-
Notifications
You must be signed in to change notification settings - Fork 3
/
x25519.go
45 lines (37 loc) · 898 Bytes
/
x25519.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
package jwker
import (
"crypto/ecdh"
"encoding/base64"
)
func fromECDHPublic(key *ecdh.PublicKey) *JWK {
return &JWK{
KeyType: "OKP",
Curve: "X25519",
X: base64.RawURLEncoding.EncodeToString(key.Bytes()),
}
}
func fromECDHPrivate(key *ecdh.PrivateKey) *JWK {
jwk := fromECDHPublic(key.PublicKey())
jwk.D = base64.RawURLEncoding.EncodeToString(key.Bytes())
return jwk
}
func toECDHKey(jwk *JWK) (any, bool, error) {
if jwk.KeyType != "OKP" || jwk.Curve != "X25519" {
return nil, false, nil
}
if jwk.D == "" {
x, err := base64.RawURLEncoding.DecodeString(jwk.X)
if err != nil {
return nil, false, err
}
pub, err := ecdh.X25519().NewPublicKey(x)
return pub, true, err
} else {
d, err := base64.RawURLEncoding.DecodeString(jwk.D)
if err != nil {
return nil, false, err
}
prv, err := ecdh.X25519().NewPrivateKey(d)
return prv, true, err
}
}