github.com/bartle-stripe/trillian@v1.2.1/cmd/createtree/pem.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 main 16 17 import ( 18 "errors" 19 "flag" 20 "fmt" 21 22 "github.com/golang/protobuf/proto" 23 "github.com/google/trillian/cmd/createtree/keys" 24 "github.com/google/trillian/crypto/keys/der" 25 "github.com/google/trillian/crypto/keys/pem" 26 "github.com/google/trillian/crypto/keyspb" 27 ) 28 29 var ( 30 pemKeyPath = flag.String("pem_key_path", "", "Path to the private key PEM file") 31 pemKeyPass = flag.String("pem_key_password", "", "Password of the private key PEM file") 32 ) 33 34 func init() { 35 keys.RegisterType("PEMKeyFile", pemKeyFileProtoFromFlags) 36 keys.RegisterType("PrivateKey", privateKeyProtoFromFlags) 37 } 38 39 func pemKeyFileProtoFromFlags() (proto.Message, error) { 40 if *pemKeyPath == "" { 41 return nil, errors.New("empty pem_key_path") 42 } 43 if *pemKeyPass == "" { 44 return nil, fmt.Errorf("empty password for PEM key file %q", *pemKeyPath) 45 } 46 47 return &keyspb.PEMKeyFile{ 48 Path: *pemKeyPath, 49 Password: *pemKeyPass, 50 }, nil 51 } 52 53 func privateKeyProtoFromFlags() (proto.Message, error) { 54 if *pemKeyPath == "" { 55 return nil, errors.New("empty pem_key_path") 56 } 57 58 key, err := pem.ReadPrivateKeyFile(*pemKeyPath, *pemKeyPass) 59 if err != nil { 60 return nil, fmt.Errorf("error reading reading private key file: %v", err) 61 } 62 63 keyDER, err := der.MarshalPrivateKey(key) 64 if err != nil { 65 return nil, fmt.Errorf("error marshaling private key as DER: %v", err) 66 } 67 68 return &keyspb.PrivateKey{Der: keyDER}, nil 69 }