github.com/yinchengtsinghua/golang-Eos-dpos-Ethereum@v0.0.0-20190121132951-92cc4225ed8e/swarm/api/encrypt.go (about) 1 2 //此源码被清华学神尹成大魔王专业翻译分析并修改 3 //尹成QQ77025077 4 //尹成微信18510341407 5 //尹成所在QQ群721929980 6 //尹成邮箱 yinc13@mails.tsinghua.edu.cn 7 //尹成毕业于清华大学,微软区块链领域全球最有价值专家 8 //https://mvp.microsoft.com/zh-cn/PublicProfile/4033620 9 // 10 // 11 // 12 // 13 // 14 // 15 // 16 // 17 // 18 // 19 // 20 // 21 // 22 // 23 // 24 25 package api 26 27 import ( 28 "encoding/binary" 29 "errors" 30 31 "github.com/ethereum/go-ethereum/crypto/sha3" 32 "github.com/ethereum/go-ethereum/swarm/storage/encryption" 33 ) 34 35 type RefEncryption struct { 36 spanEncryption encryption.Encryption 37 dataEncryption encryption.Encryption 38 span []byte 39 } 40 41 func NewRefEncryption(refSize int) *RefEncryption { 42 span := make([]byte, 8) 43 binary.LittleEndian.PutUint64(span, uint64(refSize)) 44 return &RefEncryption{ 45 spanEncryption: encryption.New(0, uint32(refSize/32), sha3.NewKeccak256), 46 dataEncryption: encryption.New(refSize, 0, sha3.NewKeccak256), 47 span: span, 48 } 49 } 50 51 func (re *RefEncryption) Encrypt(ref []byte, key []byte) ([]byte, error) { 52 encryptedSpan, err := re.spanEncryption.Encrypt(re.span, key) 53 if err != nil { 54 return nil, err 55 } 56 encryptedData, err := re.dataEncryption.Encrypt(ref, key) 57 if err != nil { 58 return nil, err 59 } 60 encryptedRef := make([]byte, len(ref)+8) 61 copy(encryptedRef[:8], encryptedSpan) 62 copy(encryptedRef[8:], encryptedData) 63 64 return encryptedRef, nil 65 } 66 67 func (re *RefEncryption) Decrypt(ref []byte, key []byte) ([]byte, error) { 68 decryptedSpan, err := re.spanEncryption.Decrypt(ref[:8], key) 69 if err != nil { 70 return nil, err 71 } 72 73 size := binary.LittleEndian.Uint64(decryptedSpan) 74 if size != uint64(len(ref)-8) { 75 return nil, errors.New("invalid span in encrypted reference") 76 } 77 78 decryptedRef, err := re.dataEncryption.Decrypt(ref[8:], key) 79 if err != nil { 80 return nil, err 81 } 82 83 return decryptedRef, nil 84 }