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 "hash" 24 25 "github.com/google/tink/go/subtle" 26 "github.com/google/tink/go/tink" 27) 28 29// RSA_SSA_PKCS1_Signer is an implementation of Signer for RSA-SSA-PKCS1. 30type RSA_SSA_PKCS1_Signer struct { 31 privateKey *rsa.PrivateKey 32 hashFunc func() hash.Hash 33 hashID crypto.Hash 34} 35 36var _ (tink.Signer) = (*RSA_SSA_PKCS1_Signer)(nil) 37 38// New_RSA_SSA_PKCS1_Signer creates a new intance of RSA_SSA_PKCS1_Signer. 39func New_RSA_SSA_PKCS1_Signer(hashAlg string, privKey *rsa.PrivateKey) (*RSA_SSA_PKCS1_Signer, error) { 40 if err := validRSAPublicKey(privKey.Public().(*rsa.PublicKey)); err != nil { 41 return nil, err 42 } 43 hashFunc, hashID, err := rsaHashFunc(hashAlg) 44 if err != nil { 45 return nil, err 46 } 47 return &RSA_SSA_PKCS1_Signer{ 48 privateKey: privKey, 49 hashFunc: hashFunc, 50 hashID: hashID, 51 }, nil 52} 53 54// Sign computes a signature for the given data. 55func (s *RSA_SSA_PKCS1_Signer) Sign(data []byte) ([]byte, error) { 56 digest, err := subtle.ComputeHash(s.hashFunc, data) 57 if err != nil { 58 return nil, err 59 } 60 return rsa.SignPKCS1v15(rand.Reader, s.privateKey, s.hashID, digest) 61} 62