-
-
Notifications
You must be signed in to change notification settings - Fork 163
/
Copy pathjwk_import_example_test.go
91 lines (82 loc) · 2.16 KB
/
jwk_import_example_test.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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
package examples_test
import (
"crypto/ecdsa"
"crypto/elliptic"
"crypto/rand"
"crypto/rsa"
"fmt"
"github.com/lestrrat-go/jwx/v3/jwk"
)
func ExampleJWK_Import() {
// First, THIS IS THE WRONG WAY TO USE jwk.Import().
//
// Assume that the file contains a JWK in JSON format
//
// buf, _ := os.ReadFile(file)
// key, _ := jwk.Import(buf)
//
// This is not right, because the jwk.Import() function determines
// the type of `jwk.Key` to create based on the TYPE of the argument.
// In this case the type of `buf` is always []byte, and therefore
// it will always create a symmetric key.
//
// What you want to do is to _parse_ `buf`.
//
// keyset, _ := jwk.Parse(buf)
// key, _ := jwk.ParseKey(buf)
//
// See other examples in examples/jwk_parse_key_example_test.go and
// examples/jwk_parse_jwks_example_test.go
// []byte -> jwk.SymmetricKey
{
raw := []byte("Lorem Ipsum")
key, err := jwk.Import(raw)
if err != nil {
fmt.Printf("failed to create symmetric key: %s\n", err)
return
}
if _, ok := key.(jwk.SymmetricKey); !ok {
fmt.Printf("expected jwk.SymmetricKey, got %T\n", key)
return
}
}
// *rsa.PrivateKey -> jwk.RSAPrivateKey
// *rsa.PublicKey -> jwk.RSAPublicKey
{
raw, err := rsa.GenerateKey(rand.Reader, 2048)
if err != nil {
fmt.Printf("failed to generate new RSA private key: %s\n", err)
return
}
key, err := jwk.Import(raw)
if err != nil {
fmt.Printf("failed to create symmetric key: %s\n", err)
return
}
if _, ok := key.(jwk.RSAPrivateKey); !ok {
fmt.Printf("expected jwk.SymmetricKey, got %T\n", key)
return
}
// PublicKey is omitted for brevity
}
// *ecdsa.PrivateKey -> jwk.ECDSAPrivateKey
// *ecdsa.PublicKey -> jwk.ECDSAPublicKey
{
raw, err := ecdsa.GenerateKey(elliptic.P384(), rand.Reader)
if err != nil {
fmt.Printf("failed to generate new ECDSA private key: %s\n", err)
return
}
key, err := jwk.Import(raw)
if err != nil {
fmt.Printf("failed to create symmetric key: %s\n", err)
return
}
if _, ok := key.(jwk.ECDSAPrivateKey); !ok {
fmt.Printf("expected jwk.SymmetricKey, got %T\n", key)
return
}
// PublicKey is omitted for brevity
}
// OUTPUT:
}