xref: /aosp_15_r20/external/tink/go/jwt/jwt_signer_kid.go (revision e7b1675dde1b92d52ec075b0a92829627f2c52a5)
1// Copyright 2022 Google LLC
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//      http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14//
15////////////////////////////////////////////////////////////////////////////////
16
17package jwt
18
19import (
20	"fmt"
21
22	"github.com/google/tink/go/tink"
23)
24
25type signerWithKID struct {
26	ts        tink.Signer
27	algorithm string
28	customKID *string
29}
30
31func newSignerWithKID(ts tink.Signer, algorithm string, customKID *string) (*signerWithKID, error) {
32	if ts == nil {
33		return nil, fmt.Errorf("tink signer can't be nil")
34	}
35	return &signerWithKID{
36		ts:        ts,
37		algorithm: algorithm,
38		customKID: customKID,
39	}, nil
40}
41
42// SignAndEncodeWithKID creates the header and content from a rawJWT and combines them into a unsigned token.
43// It then signs it and encodes the output using compact serialization.
44func (s *signerWithKID) SignAndEncodeWithKID(rawJWT *RawJWT, kid *string) (string, error) {
45	unsigned, err := createUnsigned(rawJWT, s.algorithm, kid, s.customKID)
46	if err != nil {
47		return "", err
48	}
49	signature, err := s.ts.Sign([]byte(unsigned))
50	if err != nil {
51		return "", err
52	}
53	return combineUnsignedAndSignature(unsigned, signature), nil
54}
55