github.com/trustbloc/kms-go@v1.1.2/kms/localkms/localkms_reader.go (about)

     1  /*
     2   Copyright SecureKey Technologies Inc. All Rights Reserved.
     3  
     4   SPDX-License-Identifier: Apache-2.0
     5  */
     6  
     7  package localkms
     8  
     9  import (
    10  	"bytes"
    11  	"fmt"
    12  
    13  	"github.com/trustbloc/kms-go/spi/kms"
    14  )
    15  
    16  // newReader will create a new local storage storeReader of a keyset with ID value = keysetID
    17  // it is used internally by local kms.
    18  func newReader(store kms.Store, keysetID string) *storeReader {
    19  	return &storeReader{
    20  		storage:  store,
    21  		keysetID: keysetID,
    22  	}
    23  }
    24  
    25  // storeReader struct to load a keyset from a local storage.
    26  type storeReader struct {
    27  	buf      *bytes.Buffer
    28  	storage  kms.Store
    29  	keysetID string
    30  }
    31  
    32  // Read the keyset from local storage into p.
    33  func (l *storeReader) Read(p []byte) (int, error) {
    34  	if l.buf == nil {
    35  		if l.keysetID == "" {
    36  			return 0, fmt.Errorf("keysetID is not set")
    37  		}
    38  
    39  		data, err := l.storage.Get(l.keysetID)
    40  		if err != nil {
    41  			return 0, fmt.Errorf("cannot read data for keysetID %s: %w", l.keysetID, err)
    42  		}
    43  
    44  		l.buf = bytes.NewBuffer(data)
    45  	}
    46  
    47  	return l.buf.Read(p)
    48  }