github.com/zntrio/harp/v2@v2.0.9/pkg/sdk/value/encryption/aead/helpers.go (about) 1 // Licensed to Elasticsearch B.V. under one or more contributor 2 // license agreements. See the NOTICE file distributed with 3 // this work for additional information regarding copyright 4 // ownership. Elasticsearch B.V. licenses this file to you under 5 // the Apache License, Version 2.0 (the "License"); you may 6 // not use this file except in compliance with the License. 7 // You may obtain a copy of the License at 8 // 9 // http://www.apache.org/licenses/LICENSE-2.0 10 // 11 // Unless required by applicable law or agreed to in writing, 12 // software distributed under the License is distributed on an 13 // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 14 // KIND, either express or implied. See the License for the 15 // specific language governing permissions and limitations 16 // under the License. 17 18 package aead 19 20 import ( 21 "context" 22 "crypto/cipher" 23 "crypto/rand" 24 "errors" 25 "fmt" 26 "io" 27 28 "github.com/zntrio/harp/v2/pkg/sdk/value/encryption" 29 ) 30 31 const ( 32 keyLength = 32 33 ) 34 35 func encrypt(ctx context.Context, plaintext []byte, ciph cipher.AEAD) ([]byte, error) { 36 if len(plaintext) > 64*1024*1024 { 37 return nil, errors.New("value too large") 38 } 39 nonce := make([]byte, ciph.NonceSize(), ciph.NonceSize()+ciph.Overhead()+len(plaintext)) 40 if _, err := io.ReadFull(rand.Reader, nonce); err != nil { 41 return nil, fmt.Errorf("unable to generate nonce: %w", err) 42 } 43 44 // Retrieve additional data from context 45 aad, _ := encryption.AdditionalData(ctx) 46 47 cipherText := ciph.Seal(nil, nonce, plaintext, aad) 48 49 return append(nonce, cipherText...), nil 50 } 51 52 func decrypt(ctx context.Context, ciphertext []byte, ciph cipher.AEAD) ([]byte, error) { 53 if len(ciphertext) < ciph.NonceSize() { 54 return nil, errors.New("ciphered text too short") 55 } 56 57 nonce := ciphertext[:ciph.NonceSize()] 58 text := ciphertext[ciph.NonceSize():] 59 60 // Retrieve additional data from context 61 aad, _ := encryption.AdditionalData(ctx) 62 63 clearText, err := ciph.Open(nil, nonce, text, aad) 64 if err != nil { 65 return nil, errors.New("failed to decrypt given message") 66 } 67 68 return clearText, nil 69 }