// Sign creates a JWT using the signing key. func (k Keys) Sign(payload []byte) (jws string, err error) { if k.SigningKey == nil { return "", fmt.Errorf("no key to sign payload with") } signingKey := jose.SigningKey{Key: k.SigningKey} switch key := k.SigningKey.Key.(type) { case *rsa.PrivateKey: // TODO(ericchiang): Allow different cryptographic hashes. signingKey.Algorithm = jose.RS256 case *ecdsa.PrivateKey: switch key.Params() { case elliptic.P256().Params(): signingKey.Algorithm = jose.ES256 case elliptic.P384().Params(): signingKey.Algorithm = jose.ES384 case elliptic.P521().Params(): signingKey.Algorithm = jose.ES512 default: return "", errors.New("unsupported ecdsa curve") } } signer, err := jose.NewSigner(signingKey, &jose.SignerOptions{}) if err != nil { return "", fmt.Errorf("new signier: %v", err) } signature, err := signer.Sign(payload) if err != nil { return "", fmt.Errorf("signing payload: %v", err) } return signature.CompactSerialize() }
func (v verificationTest) run(t *testing.T) { payload, err := json.Marshal(v.idToken) if err != nil { t.Fatal(err) } signingAlg := v.signAlg if signingAlg == "" { signingAlg = algForKey(t, v.signKey) } signer, err := jose.NewSigner(jose.SigningKey{ Algorithm: jose.SignatureAlgorithm(signingAlg), Key: &v.signKey, }, nil) if err != nil { t.Fatal(err) } jws, err := signer.Sign(payload) if err != nil { t.Fatal(err) } token, err := jws.CompactSerialize() if err != nil { t.Fatal(err) } t0 := time.Now() now := func() time.Time { return t0 } ctx, cancel := context.WithCancel(context.Background()) defer cancel() server := httptest.NewServer(newKeyServer(v.pubKeys...)) defer server.Close() verifier := newVerifier(newRemoteKeySet(ctx, server.URL, now), &v.config) if _, err := verifier.Verify(ctx, token); err != nil { if !v.wantErr { t.Errorf("%s: verify %v", v.name, err) } } else { if v.wantErr { t.Errorf("%s: expected error", v.name) } } }