github.com/grailbio/base@v0.0.11/crypto/encryption/registry.go (about) 1 // Copyright 2017 GRAIL, Inc. All rights reserved. 2 // Use of this source code is governed by the Apache-2.0 3 // license that can be found in the LICENSE file. 4 5 package encryption 6 7 import ( 8 "crypto/cipher" 9 "fmt" 10 "hash" 11 "sync" 12 ) 13 14 type db struct { 15 sync.Mutex 16 registries map[string]KeyRegistry 17 } 18 19 var registries = &db{registries: map[string]KeyRegistry{}} 20 21 // KeyRegistry represents a database of keys for a particular cipher, ie. 22 // implementations of KeyRegistry manage the keys for a particular cipher. 23 // AEAD is supported by wrapping the block ciphers provided. 24 type KeyRegistry interface { 25 GenerateKey() (ID []byte, err error) 26 BlockSize() int 27 HMACSize() int 28 NewBlock(ID []byte, opts ...interface{}) (hmac hash.Hash, block cipher.Block, err error) 29 NewGCM(block cipher.Block, opts ...interface{}) (aead cipher.AEAD, err error) 30 } 31 32 // Lookup returns the key registry, if any, named by the supplied name. 33 func Lookup(name string) (KeyRegistry, error) { 34 registries.Lock() 35 defer registries.Unlock() 36 r := registries.registries[name] 37 if r == nil { 38 return nil, fmt.Errorf("no such registry: %v", name) 39 } 40 return r, nil 41 } 42 43 // Register registers a new KeyRegistry using the supplied name. 44 func Register(name string, registry KeyRegistry) error { 45 registries.Lock() 46 defer registries.Unlock() 47 if _, present := registries.registries[name]; present { 48 return fmt.Errorf("already registered: %v", registry) 49 } 50 registries.registries[name] = registry 51 return nil 52 }