decode.go 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. // Copyright 2017 fatedier, fatedier@gmail.com
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. package crypto
  15. import (
  16. "crypto/aes"
  17. "crypto/cipher"
  18. "crypto/sha1"
  19. "io"
  20. "golang.org/x/crypto/pbkdf2"
  21. )
  22. // NewReader returns a new Reader that decrypts bytes from r
  23. func NewReader(r io.Reader, key []byte) *Reader {
  24. key = pbkdf2.Key(key, []byte(salt), 64, aes.BlockSize, sha1.New)
  25. return &Reader{
  26. r: r,
  27. key: key,
  28. }
  29. }
  30. // Reader is an io.Reader that can read encrypted bytes.
  31. // Now it only supports aes-128-cfb.
  32. type Reader struct {
  33. r io.Reader
  34. dec *cipher.StreamReader
  35. key []byte
  36. iv []byte
  37. err error
  38. }
  39. // Read satisfies the io.Reader interface.
  40. func (r *Reader) Read(p []byte) (nRet int, errRet error) {
  41. if r.err != nil {
  42. return 0, r.err
  43. }
  44. if r.dec == nil {
  45. iv := make([]byte, aes.BlockSize)
  46. if _, errRet = io.ReadFull(r.r, iv); errRet != nil {
  47. return
  48. }
  49. r.iv = iv
  50. block, err := aes.NewCipher(r.key)
  51. if err != nil {
  52. errRet = err
  53. return
  54. }
  55. r.dec = &cipher.StreamReader{
  56. S: cipher.NewCFBDecrypter(block, iv),
  57. R: r.r,
  58. }
  59. }
  60. nRet, errRet = r.dec.Read(p)
  61. if errRet != nil {
  62. r.err = errRet
  63. }
  64. return
  65. }