File: jwk_comparison_example_test.go

package info (click to toggle)
golang-github-lestrrat-go-jwx 2.1.4-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 2,872 kB
  • sloc: sh: 222; makefile: 86; perl: 62
file content (53 lines) | stat: -rw-r--r-- 1,212 bytes parent folder | download
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
package examples

import (
	"crypto/rand"
	"crypto/rsa"
	"fmt"

	"github.com/lestrrat-go/jwx/v2/jwk"
)

func Example_jwk_comparison() {
	genKey := func() (jwk.Key, error) {
		raw, err := rsa.GenerateKey(rand.Reader, 2048)
		if err != nil {
			return nil, fmt.Errorf("failed to generate new RSA private key: %s", err)
		}

		key, err := jwk.FromRaw(raw)
		if err != nil {
			return nil, fmt.Errorf("failed to create RSA key: %s", err)
		}
		if _, ok := key.(jwk.RSAPrivateKey); !ok {
			return nil, fmt.Errorf("expected jwk.SymmetricKey, got %T", key)
		}

		return key, nil
	}

	k1, err := genKey()
	if err != nil {
		fmt.Printf("failed to generate key 1: %T", err)
		return
	}
	k2, err := genKey()
	if err != nil {
		fmt.Printf("failed to generate key 2: %T", err)
		return
	}

	// This comparison only compares Thumbprints of each key. It does NOT take into
	// account fields that could differ even when thumbprints match. For example,
	// it is totally possible to have a key with the same thumbprint, but different
	// Key IDs, or key usages.
	if jwk.Equal(k1, k2) {
		fmt.Printf("k1 and k2 should be different")
		return
	}

	if !jwk.Equal(k1, k1) {
		fmt.Printf("k1 and k1 should be equal")
		return
	}
}