github.com/ethersphere/bee/v2@v2.2.0/pkg/encryption/chunk_encryption.go (about) 1 // Copyright 2020 The Swarm Authors. All rights reserved. 2 // Use of this source code is governed by a BSD-style 3 // license that can be found in the LICENSE file. 4 5 package encryption 6 7 import ( 8 "github.com/ethersphere/bee/v2/pkg/swarm" 9 "golang.org/x/crypto/sha3" 10 ) 11 12 // ChunkEncrypter encrypts chunk data. 13 type ChunkEncrypter interface { 14 EncryptChunk([]byte) (key Key, encryptedSpan, encryptedData []byte, err error) 15 } 16 17 type chunkEncrypter struct{} 18 19 func NewChunkEncrypter() ChunkEncrypter { return &chunkEncrypter{} } 20 21 func (c *chunkEncrypter) EncryptChunk(chunkData []byte) (Key, []byte, []byte, error) { 22 key := GenerateRandomKey(KeyLength) 23 encryptedSpan, err := NewSpanEncryption(key).Encrypt(chunkData[:8]) 24 if err != nil { 25 return nil, nil, nil, err 26 } 27 encryptedData, err := NewDataEncryption(key).Encrypt(chunkData[8:]) 28 if err != nil { 29 return nil, nil, nil, err 30 } 31 return key, encryptedSpan, encryptedData, nil 32 } 33 34 func NewSpanEncryption(key Key) Interface { 35 return New(key, 0, uint32(swarm.ChunkSize/KeyLength), sha3.NewLegacyKeccak256) 36 } 37 38 func NewDataEncryption(key Key) Interface { 39 return New(key, int(swarm.ChunkSize), 0, sha3.NewLegacyKeccak256) 40 }