github.com/trustbloc/kms-go@v1.1.2/doc/util/kmssigner/kmssigner.go (about)

     1  /*
     2  Copyright Avast Software. All Rights Reserved.
     3  
     4  SPDX-License-Identifier: Apache-2.0
     5  */
     6  
     7  package kmssigner
     8  
     9  import (
    10  	"strings"
    11  
    12  	"github.com/trustbloc/kms-go/spi/crypto"
    13  	"github.com/trustbloc/kms-go/spi/kms"
    14  )
    15  
    16  const (
    17  	p256Alg = "ES256"
    18  	p384Alg = "ES384"
    19  	p521Alg = "ES521"
    20  	edAlg   = "EdDSA"
    21  )
    22  
    23  // KMSSigner implements JWS Signer interface using a KMS key handle and a crypto.Crypto instance.
    24  type KMSSigner struct {
    25  	KeyType   kms.KeyType
    26  	KeyHandle interface{}
    27  	Crypto    crypto.Crypto
    28  	MultiMsg  bool
    29  }
    30  
    31  // Sign signs data using KMSSigner's KeyHandle.
    32  func (s *KMSSigner) Sign(data []byte) ([]byte, error) {
    33  	if s.MultiMsg {
    34  		return s.Crypto.SignMulti(s.textToLines(string(data)), s.KeyHandle)
    35  	}
    36  
    37  	v, err := s.Crypto.Sign(data, s.KeyHandle)
    38  	if err != nil {
    39  		return nil, err
    40  	}
    41  
    42  	return v, nil
    43  }
    44  
    45  // Alg provides the JWA corresponding to the KMSSigner's KeyType.
    46  func (s *KMSSigner) Alg() string {
    47  	return KeyTypeToJWA(s.KeyType)
    48  }
    49  
    50  func (s *KMSSigner) textToLines(txt string) [][]byte {
    51  	lines := strings.Split(txt, "\n")
    52  	linesBytes := make([][]byte, 0, len(lines))
    53  
    54  	for i := range lines {
    55  		if strings.TrimSpace(lines[i]) != "" {
    56  			linesBytes = append(linesBytes, []byte(lines[i]))
    57  		}
    58  	}
    59  
    60  	return linesBytes
    61  }
    62  
    63  // KeyTypeToJWA provides the JWA corresponding to keyType.
    64  func KeyTypeToJWA(keyType kms.KeyType) string {
    65  	switch keyType {
    66  	case kms.ECDSAP256IEEEP1363, kms.ECDSAP256DER:
    67  		return p256Alg
    68  	case kms.ECDSAP384IEEEP1363, kms.ECDSAP384DER:
    69  		return p384Alg
    70  	case kms.ECDSAP521IEEEP1363, kms.ECDSAP521DER:
    71  		return p521Alg
    72  	case kms.ED25519:
    73  		return edAlg
    74  	}
    75  
    76  	return ""
    77  }