xref: /aosp_15_r20/external/tink/go/internal/signature/rsassapss_signer.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 signature
18
19import (
20	"crypto"
21	"crypto/rand"
22	"crypto/rsa"
23	"fmt"
24	"hash"
25
26	"github.com/google/tink/go/subtle"
27	"github.com/google/tink/go/tink"
28)
29
30// RSA_SSA_PSS_Signer is an implementation of Signer for RSA-SSA-PSS.
31type RSA_SSA_PSS_Signer struct {
32	privateKey *rsa.PrivateKey
33	hashFunc   func() hash.Hash
34	hashID     crypto.Hash
35	saltLength int
36}
37
38var _ tink.Signer = (*RSA_SSA_PSS_Signer)(nil)
39
40// New_RSA_SSA_PSS_Signer creates a new instance of RSA_SSA_PSS_Signer.
41func New_RSA_SSA_PSS_Signer(hashAlg string, saltLength int, privKey *rsa.PrivateKey) (*RSA_SSA_PSS_Signer, error) {
42	if err := validRSAPublicKey(&privKey.PublicKey); err != nil {
43		return nil, err
44	}
45	hashFunc, hashID, err := rsaHashFunc(hashAlg)
46	if err != nil {
47		return nil, err
48	}
49	if saltLength < 0 {
50		return nil, fmt.Errorf("invalid salt length")
51	}
52	return &RSA_SSA_PSS_Signer{
53		privateKey: privKey,
54		hashFunc:   hashFunc,
55		hashID:     hashID,
56		saltLength: saltLength,
57	}, nil
58}
59
60// Sign computes a signature for the given data.
61func (s *RSA_SSA_PSS_Signer) Sign(data []byte) ([]byte, error) {
62	digest, err := subtle.ComputeHash(s.hashFunc, data)
63	if err != nil {
64		return nil, err
65	}
66	return rsa.SignPSS(rand.Reader, s.privateKey, s.hashID, digest, &rsa.PSSOptions{SaltLength: s.saltLength})
67
68}
69