github.com/ethersphere/bee/v2@v2.2.0/pkg/file/pipeline/encryption/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/encryption"
     9  	"github.com/ethersphere/bee/v2/pkg/file/pipeline"
    10  )
    11  
    12  type encryptionWriter struct {
    13  	next pipeline.ChainWriter
    14  	enc  encryption.ChunkEncrypter
    15  }
    16  
    17  func NewEncryptionWriter(encrypter encryption.ChunkEncrypter, next pipeline.ChainWriter) pipeline.ChainWriter {
    18  	return &encryptionWriter{
    19  		next: next,
    20  		enc:  encrypter,
    21  	}
    22  }
    23  
    24  // Write assumes that the span is prepended to the actual data before the write !
    25  func (e *encryptionWriter) ChainWrite(p *pipeline.PipeWriteArgs) error {
    26  	key, encryptedSpan, encryptedData, err := e.enc.EncryptChunk(p.Data)
    27  	if err != nil {
    28  		return err
    29  	}
    30  	c := make([]byte, len(encryptedSpan)+len(encryptedData))
    31  	copy(c[:8], encryptedSpan)
    32  	copy(c[8:], encryptedData)
    33  	p.Data = c // replace the verbatim data with the encrypted data
    34  	p.Key = key
    35  	return e.next.ChainWrite(p)
    36  }
    37  
    38  func (e *encryptionWriter) Sum() ([]byte, error) {
    39  	return e.next.Sum()
    40  }