encrypt.go 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  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. package api
  17. import (
  18. "encoding/binary"
  19. "errors"
  20. "github.com/ethereum/go-ethereum/swarm/storage/encryption"
  21. "golang.org/x/crypto/sha3"
  22. )
  23. type RefEncryption struct {
  24. refSize int
  25. span []byte
  26. }
  27. func NewRefEncryption(refSize int) *RefEncryption {
  28. span := make([]byte, 8)
  29. binary.LittleEndian.PutUint64(span, uint64(refSize))
  30. return &RefEncryption{
  31. refSize: refSize,
  32. span: span,
  33. }
  34. }
  35. func (re *RefEncryption) Encrypt(ref []byte, key []byte) ([]byte, error) {
  36. spanEncryption := encryption.New(key, 0, uint32(re.refSize/32), sha3.NewLegacyKeccak256)
  37. encryptedSpan, err := spanEncryption.Encrypt(re.span)
  38. if err != nil {
  39. return nil, err
  40. }
  41. dataEncryption := encryption.New(key, re.refSize, 0, sha3.NewLegacyKeccak256)
  42. encryptedData, err := dataEncryption.Encrypt(ref)
  43. if err != nil {
  44. return nil, err
  45. }
  46. encryptedRef := make([]byte, len(ref)+8)
  47. copy(encryptedRef[:8], encryptedSpan)
  48. copy(encryptedRef[8:], encryptedData)
  49. return encryptedRef, nil
  50. }
  51. func (re *RefEncryption) Decrypt(ref []byte, key []byte) ([]byte, error) {
  52. spanEncryption := encryption.New(key, 0, uint32(re.refSize/32), sha3.NewLegacyKeccak256)
  53. decryptedSpan, err := spanEncryption.Decrypt(ref[:8])
  54. if err != nil {
  55. return nil, err
  56. }
  57. size := binary.LittleEndian.Uint64(decryptedSpan)
  58. if size != uint64(len(ref)-8) {
  59. return nil, errors.New("invalid span in encrypted reference")
  60. }
  61. dataEncryption := encryption.New(key, re.refSize, 0, sha3.NewLegacyKeccak256)
  62. decryptedRef, err := dataEncryption.Decrypt(ref[8:])
  63. if err != nil {
  64. return nil, err
  65. }
  66. return decryptedRef, nil
  67. }