Skip to content
Snippets Groups Projects
kms-keystore.go 1.47 KiB
Newer Older
  • Learn to ignore specific revisions
  • package kms
    
    import (
    	"errors"
    	"fmt"
    	"log"
    	"sync"
    
    
    	"code.fbi.h-da.de/danet/proto-kms/quantumlayer"
    
    )
    
    type kmsKS interface {
    	KeyChopper256Bit(bulkKey *quantumlayer.QuantumLayerBulkKey) (err error)
    	addKey(int64, [8]byte)
    }
    
    // holds a single ready to use 256 bit key
    type kmsKSElement struct {
    	keyID string
    	key   []byte // a 256 bit key
    }
    
    type kmsKeyStore struct {
    	keyStoreMutex sync.Mutex
    
    Malte Bauch's avatar
    Malte Bauch committed
    	keyStore      map[string]*kmsKSElement
    
    }
    
    func (ks *kmsKeyStore) addKey(bulkKeyId int64, keyToadd []byte) {
    	newKeyElement := kmsKSElement{}
    
    	//generate keyID out of bulkKeyId and has of keyToadd
    
    	newKeyElement.keyID = fmt.Sprintf("%x.%x", bulkKeyId, keyToadd)
    
    	newKeyElement.key = keyToadd
    
    	ks.keyStoreMutex.Lock()
    	defer ks.keyStoreMutex.Unlock()
    	// test for collisions
    	if _, notThere := ks.keyStore[newKeyElement.keyID]; notThere {
    
    		log.Printf("Whop: addKey collission of key id %s for bulkKeyID %d", newKeyElement.keyID, bulkKeyId)
    
    		return
    	}
    	// ok to add
    
    Malte Bauch's avatar
    Malte Bauch committed
    	ks.keyStore[newKeyElement.keyID] = &newKeyElement
    
    
    }
    
    // Takes a bulk of keys and chops them in 256bit keys each
    // Any remainder is discarded
    func (ks *kmsKeyStore) KeyChopper256Bit(bulkKey *quantumlayer.QuantumLayerBulkKey) (err error) {
    	if bulkKey.BulkKeyLength != len(*bulkKey.BulkKey) {
    		err = errors.New("bulkKey length mismatch")
    		return err
    	}
    
    	// Let's chop!
    	key := *bulkKey.BulkKey
    
    Malte Bauch's avatar
    Malte Bauch committed
    	for len(key) > 32 {
    		tmpkey := key[:32]
    
    		ks.addKey(bulkKey.BulkKeyId, tmpkey)
    		// shorten the key storage
    
    Malte Bauch's avatar
    Malte Bauch committed
    		key = key[32:]