github.com/lestrrat-go/jwx/v2@v2.0.21/jws/signer_test.go (about) 1 package jws_test 2 3 import ( 4 "strings" 5 "testing" 6 7 "github.com/lestrrat-go/jwx/v2/internal/jwxtest" 8 "github.com/lestrrat-go/jwx/v2/jwa" 9 "github.com/lestrrat-go/jwx/v2/jws" 10 "github.com/stretchr/testify/assert" 11 ) 12 13 func TestSign(t *testing.T) { 14 t.Parallel() 15 t.Run("Bad algorithm", func(t *testing.T) { 16 t.Parallel() 17 _, err := jws.Sign([]byte(nil), jws.WithKey(jwa.SignatureAlgorithm("FooBar"), nil)) 18 if !assert.Error(t, err, "Unknown algorithm should return error") { 19 return 20 } 21 }) 22 t.Run("No private key", func(t *testing.T) { 23 t.Parallel() 24 _, err := jws.Sign([]byte{'a', 'b', 'c'}, jws.WithKey(jwa.RS256, nil)) 25 if !assert.Error(t, err, "Sign with no private key should return error") { 26 return 27 } 28 }) 29 t.Run("RSA verify with no public key", func(t *testing.T) { 30 t.Parallel() 31 _, err := jws.Verify([]byte(nil), jws.WithKey(jwa.RS256, nil)) 32 if !assert.Error(t, err, "Verify with no private key should return error") { 33 return 34 } 35 }) 36 t.Run("RSA roundtrip", func(t *testing.T) { 37 t.Parallel() 38 rsakey, err := jwxtest.GenerateRsaKey() 39 if !assert.NoError(t, err, "RSA key generated") { 40 return 41 } 42 43 signer, err := jws.NewSigner(jwa.RS256) 44 if !assert.NoError(t, err, `creating a signer should succeed`) { 45 return 46 } 47 48 payload := []byte("Hello, world") 49 50 signed, err := signer.Sign(payload, rsakey) 51 if !assert.NoError(t, err, "Payload signed") { 52 return 53 } 54 55 verifier, err := jws.NewVerifier(jwa.RS256) 56 if !assert.NoError(t, err, "creating a verifier should succeed") { 57 return 58 } 59 60 if !assert.NoError(t, verifier.Verify(payload, signed, &rsakey.PublicKey), "Payload verified") { 61 return 62 } 63 }) 64 } 65 66 func TestSignMulti(t *testing.T) { 67 rsakey, err := jwxtest.GenerateRsaKey() 68 if !assert.NoError(t, err, "RSA key generated") { 69 return 70 } 71 72 dsakey, err := jwxtest.GenerateEcdsaKey(jwa.P521) 73 if !assert.NoError(t, err, "ECDSA key generated") { 74 return 75 } 76 77 s1hdr := jws.NewHeaders() 78 s1hdr.Set(jws.KeyIDKey, "2010-12-29") 79 80 s2hdr := jws.NewHeaders() 81 s2hdr.Set(jws.KeyIDKey, "e9bc097a-ce51-4036-9562-d2ade882db0d") 82 83 v := strings.Join([]string{`{"iss":"joe",`, ` "exp":1300819380,`, ` "http://example.com/is_root":true}`}, "\r\n") 84 m, err := jws.Sign([]byte(v), 85 jws.WithJSON(), 86 jws.WithKey(jwa.RS256, rsakey, jws.WithPublicHeaders(s1hdr)), 87 jws.WithKey(jwa.ES256, dsakey, jws.WithPublicHeaders(s2hdr)), 88 ) 89 if !assert.NoError(t, err, "jws.SignMulti should succeed") { 90 return 91 } 92 93 t.Logf("%s", m) 94 }