github.com/letsencrypt/trillian@v1.1.2-0.20180615153820-ae375a99d36a/cmd/createtree/keys/registry.go (about)

     1  // Copyright 2017 Google Inc. All Rights Reserved.
     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  package keys
    16  
    17  import (
    18  	"fmt"
    19  	"strings"
    20  
    21  	"github.com/golang/protobuf/proto"
    22  	"github.com/golang/protobuf/ptypes"
    23  	"github.com/golang/protobuf/ptypes/any"
    24  )
    25  
    26  // ProtoBuilder creates a protobuf message that describes a private key.
    27  // It may use flags to obtain the required information, e.g. file paths.
    28  type ProtoBuilder func() (proto.Message, error)
    29  
    30  // protoBuilders is a map of key types to funcs that can create protobuf
    31  // messages describing them. The "key type" is a human-friendly identifier;
    32  // it does not have to be the name of the protobuf message.
    33  var protoBuilders = make(map[string]ProtoBuilder)
    34  
    35  // RegisterType registers a func that can create protobuf messages which describe
    36  // a private key.
    37  func RegisterType(protoType string, builder ProtoBuilder) {
    38  	protoBuilders[protoType] = builder
    39  }
    40  
    41  // New returns a protobuf message of the specified type that describes a private
    42  // key. A ProtoBuilder must have been registered for this type using
    43  // RegisterType() first.
    44  func New(protoType string) (*any.Any, error) {
    45  	buildProto, ok := protoBuilders[protoType]
    46  	if !ok {
    47  		return nil, fmt.Errorf("key protobuf type must be one of: %s", strings.Join(RegisteredTypes(), ", "))
    48  	}
    49  
    50  	pb, err := buildProto()
    51  	if err != nil {
    52  		return nil, err
    53  	}
    54  
    55  	return ptypes.MarshalAny(pb)
    56  }
    57  
    58  // RegisteredTypes returns a list of protobuf message types that have been
    59  // registered using RegisterType().
    60  func RegisteredTypes() []string {
    61  	protoTypes := make([]string, 0, len(protoBuilders))
    62  	for protoType := range protoBuilders {
    63  		protoTypes = append(protoTypes, protoType)
    64  	}
    65  	return protoTypes
    66  }