1 // Copyright 2023 Google LLC. 2 // Licensed under the Apache License, Version 2.0 (the "License"); 3 // you may not use this file except in compliance with the License. 4 // You may obtain a copy of the License at 5 // 6 // https://www.apache.org/licenses/LICENSE-2.0 7 // 8 // Unless required by applicable law or agreed to in writing, software 9 // distributed under the License is distributed on an "AS IS" BASIS, 10 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 11 // See the License for the specific language governing permissions and 12 // limitations under the License. 13 14 // Package linux contains a linux-specific client for accessing the PKCS#11 APIs directly, 15 // bypassing the RPC-mechanism of the universal client. 16 package linux 17 18 import ( 19 "crypto" 20 "io" 21 22 "github.com/googleapis/enterprise-certificate-proxy/internal/signer/linux/pkcs11" 23 ) 24 25 // SecureKey is a public wrapper for the internal PKCS#11 implementation. 26 type SecureKey struct { 27 key *pkcs11.Key 28 } 29 30 // CertificateChain returns the SecureKey's raw X509 cert chain. This contains the public key. 31 func (sk *SecureKey) CertificateChain() [][]byte { 32 return sk.key.CertificateChain() 33 } 34 35 // Public returns the public key for this SecureKey. 36 func (sk *SecureKey) Public() crypto.PublicKey { 37 return sk.key.Public() 38 } 39 40 // Sign signs a message digest, using the specified signer opts. Implements crypto.Signer interface. 41 func (sk *SecureKey) Sign(_ io.Reader, digest []byte, opts crypto.SignerOpts) (signed []byte, err error) { 42 return sk.key.Sign(nil, digest, opts) 43 } 44 45 // Encrypt encrypts a plaintext msg into ciphertext, using the specified encrypt opts. 46 func (sk *SecureKey) Encrypt(_ io.Reader, msg []byte, opts any) (ciphertext []byte, err error) { 47 return sk.key.Encrypt(msg, opts) 48 } 49 50 // Decrypt decrypts a ciphertext msg into plaintext, using the specified decrypter opts. Implements crypto.Decrypter interface. 51 func (sk *SecureKey) Decrypt(_ io.Reader, msg []byte, opts crypto.DecrypterOpts) (plaintext []byte, err error) { 52 return sk.key.Decrypt(msg, opts) 53 } 54 55 // Close frees up resources associated with the underlying key. 56 func (sk *SecureKey) Close() { 57 sk.key.Close() 58 } 59 60 // NewSecureKey returns a handle to the first available certificate and private key pair in 61 // the specified PKCS#11 Module matching the filters. 62 func NewSecureKey(pkcs11Module string, slotUint32Str string, label string, userPin string) (*SecureKey, error) { 63 k, err := pkcs11.Cred(pkcs11Module, slotUint32Str, label, userPin) 64 if err != nil { 65 return nil, err 66 } 67 return &SecureKey{key: k}, nil 68 } 69