encrypt.go 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  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/crypto/sha3"
  21. "github.com/ethereum/go-ethereum/swarm/storage/encryption"
  22. )
  23. type RefEncryption struct {
  24. spanEncryption encryption.Encryption
  25. dataEncryption encryption.Encryption
  26. span []byte
  27. }
  28. func NewRefEncryption(refSize int) *RefEncryption {
  29. span := make([]byte, 8)
  30. binary.LittleEndian.PutUint64(span, uint64(refSize))
  31. return &RefEncryption{
  32. spanEncryption: encryption.New(0, uint32(refSize/32), sha3.NewKeccak256),
  33. dataEncryption: encryption.New(refSize, 0, sha3.NewKeccak256),
  34. span: span,
  35. }
  36. }
  37. func (re *RefEncryption) Encrypt(ref []byte, key []byte) ([]byte, error) {
  38. encryptedSpan, err := re.spanEncryption.Encrypt(re.span, key)
  39. if err != nil {
  40. return nil, err
  41. }
  42. encryptedData, err := re.dataEncryption.Encrypt(ref, key)
  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. decryptedSpan, err := re.spanEncryption.Decrypt(ref[:8], key)
  53. if err != nil {
  54. return nil, err
  55. }
  56. size := binary.LittleEndian.Uint64(decryptedSpan)
  57. if size != uint64(len(ref)-8) {
  58. return nil, errors.New("invalid span in encrypted reference")
  59. }
  60. decryptedRef, err := re.dataEncryption.Decrypt(ref[8:], key)
  61. if err != nil {
  62. return nil, err
  63. }
  64. return decryptedRef, nil
  65. }