59 lines
1.5 KiB
Go
59 lines
1.5 KiB
Go
package store
|
|
|
|
import (
|
|
"crypto/aes"
|
|
"crypto/cipher"
|
|
"crypto/rand"
|
|
"io"
|
|
|
|
"github.com/niko/qcc/internal/crypto"
|
|
)
|
|
|
|
var MasterKey [32]byte
|
|
|
|
func SetMasterKey(key [32]byte) {
|
|
MasterKey = key
|
|
}
|
|
|
|
func EncryptRecordPayload(plaintext []byte, key [32]byte) (nonce [12]byte, ciphertext []byte, authTag []byte, err error) {
|
|
return crypto.EncryptRecord(plaintext, key)
|
|
}
|
|
|
|
func DecryptRecordPayload(ciphertext []byte, nonce [12]byte, authTag []byte, key [32]byte) ([]byte, error) {
|
|
return crypto.DecryptRecord(ciphertext, nonce, authTag, key)
|
|
}
|
|
|
|
func EncryptIndexData(data []byte) (nonce [12]byte, ciphertext []byte, authTag []byte, err error) {
|
|
block, err := aes.NewCipher(MasterKey[:])
|
|
if err != nil {
|
|
return nonce, nil, nil, err
|
|
}
|
|
aead, err := cipher.NewGCM(block)
|
|
if err != nil {
|
|
return nonce, nil, nil, err
|
|
}
|
|
_, err = io.ReadFull(rand.Reader, nonce[:])
|
|
if err != nil {
|
|
return nonce, nil, nil, err
|
|
}
|
|
sealed := aead.Seal(nil, nonce[:], data, nil)
|
|
tagStart := len(sealed) - aead.Overhead()
|
|
ciphertext = sealed[:tagStart]
|
|
authTag = sealed[tagStart:]
|
|
return nonce, ciphertext, authTag, nil
|
|
}
|
|
|
|
func DecryptIndexData(ciphertext []byte, nonce [12]byte, authTag []byte) ([]byte, error) {
|
|
block, err := aes.NewCipher(MasterKey[:])
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
aead, err := cipher.NewGCM(block)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
sealed := make([]byte, len(ciphertext)+len(authTag))
|
|
copy(sealed, ciphertext)
|
|
copy(sealed[len(ciphertext):], authTag)
|
|
return aead.Open(nil, nonce[:], sealed, nil)
|
|
}
|