xref: /aosp_15_r20/external/tink/go/internal/signature/rsassapkcs1_verifier.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/rsa"
22	"hash"
23
24	"github.com/google/tink/go/subtle"
25	"github.com/google/tink/go/tink"
26)
27
28// RSA_SSA_PKCS1_Verifier is an implementation of Verifier for RSA-SSA-PKCS1.
29type RSA_SSA_PKCS1_Verifier struct {
30	publicKey *rsa.PublicKey
31	hashFunc  func() hash.Hash
32	hashID    crypto.Hash
33}
34
35var _ tink.Verifier = (*RSA_SSA_PKCS1_Verifier)(nil)
36
37// New_RSA_SSA_PKCS1_Verifier creates a new intance of RSASSAPKCS1Verifier.
38func New_RSA_SSA_PKCS1_Verifier(hashAlg string, pubKey *rsa.PublicKey) (*RSA_SSA_PKCS1_Verifier, error) {
39	if err := validRSAPublicKey(pubKey); err != nil {
40		return nil, err
41	}
42	hashFunc, hashID, err := rsaHashFunc(hashAlg)
43	if err != nil {
44		return nil, err
45	}
46	return &RSA_SSA_PKCS1_Verifier{
47		publicKey: pubKey,
48		hashFunc:  hashFunc,
49		hashID:    hashID,
50	}, nil
51}
52
53// Verify verifies whether the given signaure is valid for the given data.
54// It returns an error if the signature is not valid; nil otherwise.
55func (v *RSA_SSA_PKCS1_Verifier) Verify(signature, data []byte) error {
56	hashed, err := subtle.ComputeHash(v.hashFunc, data)
57	if err != nil {
58		return err
59	}
60	return rsa.VerifyPKCS1v15(v.publicKey, v.hashID, hashed, signature)
61}
62