github.com/divan/go-ethereum@v1.8.14-0.20180820134928-1de9ada4016d/swarm/api/encrypt.go (about) 1 // Copyright 2016 The go-ethereum Authors 2 // This file is part of the go-ethereum library. 3 // 4 // The go-ethereum library is free software: you can redistribute it and/or modify 5 // it under the terms of the GNU Lesser General Public License as published by 6 // the Free Software Foundation, either version 3 of the License, or 7 // (at your option) any later version. 8 // 9 // The go-ethereum library is distributed in the hope that it will be useful, 10 // but WITHOUT ANY WARRANTY; without even the implied warranty of 11 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 // GNU Lesser General Public License for more details. 13 // 14 // You should have received a copy of the GNU Lesser General Public License 15 // along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>. 16 17 package api 18 19 import ( 20 "encoding/binary" 21 "errors" 22 23 "github.com/ethereum/go-ethereum/crypto/sha3" 24 "github.com/ethereum/go-ethereum/swarm/storage/encryption" 25 ) 26 27 type RefEncryption struct { 28 spanEncryption encryption.Encryption 29 dataEncryption encryption.Encryption 30 span []byte 31 } 32 33 func NewRefEncryption(refSize int) *RefEncryption { 34 span := make([]byte, 8) 35 binary.LittleEndian.PutUint64(span, uint64(refSize)) 36 return &RefEncryption{ 37 spanEncryption: encryption.New(0, uint32(refSize/32), sha3.NewKeccak256), 38 dataEncryption: encryption.New(refSize, 0, sha3.NewKeccak256), 39 span: span, 40 } 41 } 42 43 func (re *RefEncryption) Encrypt(ref []byte, key []byte) ([]byte, error) { 44 encryptedSpan, err := re.spanEncryption.Encrypt(re.span, key) 45 if err != nil { 46 return nil, err 47 } 48 encryptedData, err := re.dataEncryption.Encrypt(ref, key) 49 if err != nil { 50 return nil, err 51 } 52 encryptedRef := make([]byte, len(ref)+8) 53 copy(encryptedRef[:8], encryptedSpan) 54 copy(encryptedRef[8:], encryptedData) 55 56 return encryptedRef, nil 57 } 58 59 func (re *RefEncryption) Decrypt(ref []byte, key []byte) ([]byte, error) { 60 decryptedSpan, err := re.spanEncryption.Decrypt(ref[:8], key) 61 if err != nil { 62 return nil, err 63 } 64 65 size := binary.LittleEndian.Uint64(decryptedSpan) 66 if size != uint64(len(ref)-8) { 67 return nil, errors.New("invalid span in encrypted reference") 68 } 69 70 decryptedRef, err := re.dataEncryption.Decrypt(ref[8:], key) 71 if err != nil { 72 return nil, err 73 } 74 75 return decryptedRef, nil 76 }