File: eddsa.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 (77 lines) | stat: -rw-r--r-- 1,995 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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
package jws

import (
	"crypto"
	"crypto/ed25519"
	"crypto/rand"
	"fmt"

	"github.com/lestrrat-go/jwx/v2/internal/keyconv"
	"github.com/lestrrat-go/jwx/v2/jwa"
)

type eddsaSigner struct{}

func newEdDSASigner() Signer {
	return &eddsaSigner{}
}

func (s eddsaSigner) Algorithm() jwa.SignatureAlgorithm {
	return jwa.EdDSA
}

func (s eddsaSigner) Sign(payload []byte, key interface{}) ([]byte, error) {
	if key == nil {
		return nil, fmt.Errorf(`missing private key while signing payload`)
	}

	// The ed25519.PrivateKey object implements crypto.Signer, so we should
	// simply accept a crypto.Signer here.
	signer, ok := key.(crypto.Signer)
	if ok {
		if !isValidEDDSAKey(key) {
			return nil, fmt.Errorf(`cannot use key of type %T to generate EdDSA based signatures`, key)
		}
	} else {
		// This fallback exists for cases when jwk.Key was passed, or
		// users gave us a pointer instead of non-pointer, etc.
		var privkey ed25519.PrivateKey
		if err := keyconv.Ed25519PrivateKey(&privkey, key); err != nil {
			return nil, fmt.Errorf(`failed to retrieve ed25519.PrivateKey out of %T: %w`, key, err)
		}
		signer = privkey
	}
	return signer.Sign(rand.Reader, payload, crypto.Hash(0))
}

type eddsaVerifier struct{}

func newEdDSAVerifier() Verifier {
	return &eddsaVerifier{}
}

func (v eddsaVerifier) Verify(payload, signature []byte, key interface{}) (err error) {
	if key == nil {
		return fmt.Errorf(`missing public key while verifying payload`)
	}

	var pubkey ed25519.PublicKey
	signer, ok := key.(crypto.Signer)
	if ok {
		v := signer.Public()
		pubkey, ok = v.(ed25519.PublicKey)
		if !ok {
			return fmt.Errorf(`expected crypto.Signer.Public() to return ed25519.PublicKey, but got %T`, v)
		}
	} else {
		if err := keyconv.Ed25519PublicKey(&pubkey, key); err != nil {
			return fmt.Errorf(`failed to retrieve ed25519.PublicKey out of %T: %w`, key, err)
		}
	}

	if !ed25519.Verify(pubkey, payload, signature) {
		return fmt.Errorf(`failed to match EdDSA signature`)
	}

	return nil
}