io.go 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. package crypto
  2. import (
  3. "crypto/cipher"
  4. "io"
  5. "github.com/v2ray/v2ray-core/common"
  6. )
  7. type CryptionReader struct {
  8. stream cipher.Stream
  9. reader io.Reader
  10. }
  11. func NewCryptionReader(stream cipher.Stream, reader io.Reader) *CryptionReader {
  12. return &CryptionReader{
  13. stream: stream,
  14. reader: reader,
  15. }
  16. }
  17. func (this *CryptionReader) Read(data []byte) (int, error) {
  18. if this.reader == nil {
  19. return 0, common.ErrObjectReleased
  20. }
  21. nBytes, err := this.reader.Read(data)
  22. if nBytes > 0 {
  23. this.stream.XORKeyStream(data[:nBytes], data[:nBytes])
  24. }
  25. return nBytes, err
  26. }
  27. func (this *CryptionReader) Release() {
  28. this.reader = nil
  29. this.stream = nil
  30. }
  31. type CryptionWriter struct {
  32. stream cipher.Stream
  33. writer io.Writer
  34. }
  35. func NewCryptionWriter(stream cipher.Stream, writer io.Writer) *CryptionWriter {
  36. return &CryptionWriter{
  37. stream: stream,
  38. writer: writer,
  39. }
  40. }
  41. func (this *CryptionWriter) Write(data []byte) (int, error) {
  42. if this.writer == nil {
  43. return 0, common.ErrObjectReleased
  44. }
  45. this.stream.XORKeyStream(data, data)
  46. return this.writer.Write(data)
  47. }
  48. func (this *CryptionWriter) Release() {
  49. this.writer = nil
  50. this.stream = nil
  51. }