2016-02-25 15:53:21 -05:00
|
|
|
package crypto
|
|
|
|
|
|
|
|
import (
|
|
|
|
"crypto/cipher"
|
|
|
|
"io"
|
2016-03-09 18:33:14 -05:00
|
|
|
|
2016-08-20 14:55:45 -04:00
|
|
|
"v2ray.com/core/common"
|
2016-02-25 15:53:21 -05:00
|
|
|
)
|
|
|
|
|
2016-03-09 18:33:14 -05:00
|
|
|
type CryptionReader struct {
|
2016-02-25 15:53:21 -05:00
|
|
|
stream cipher.Stream
|
|
|
|
reader io.Reader
|
|
|
|
}
|
|
|
|
|
2016-03-09 18:33:14 -05:00
|
|
|
func NewCryptionReader(stream cipher.Stream, reader io.Reader) *CryptionReader {
|
|
|
|
return &CryptionReader{
|
2016-02-25 15:53:21 -05:00
|
|
|
stream: stream,
|
|
|
|
reader: reader,
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2016-03-09 18:33:14 -05:00
|
|
|
func (this *CryptionReader) Read(data []byte) (int, error) {
|
|
|
|
if this.reader == nil {
|
2016-06-22 09:12:57 -04:00
|
|
|
return 0, common.ErrObjectReleased
|
2016-03-09 18:33:14 -05:00
|
|
|
}
|
2016-02-25 15:53:21 -05:00
|
|
|
nBytes, err := this.reader.Read(data)
|
|
|
|
if nBytes > 0 {
|
|
|
|
this.stream.XORKeyStream(data[:nBytes], data[:nBytes])
|
|
|
|
}
|
|
|
|
return nBytes, err
|
|
|
|
}
|
|
|
|
|
2016-03-09 18:33:14 -05:00
|
|
|
func (this *CryptionReader) Release() {
|
|
|
|
this.reader = nil
|
|
|
|
this.stream = nil
|
|
|
|
}
|
|
|
|
|
|
|
|
type CryptionWriter struct {
|
2016-02-25 15:53:21 -05:00
|
|
|
stream cipher.Stream
|
|
|
|
writer io.Writer
|
|
|
|
}
|
|
|
|
|
2016-03-09 18:33:14 -05:00
|
|
|
func NewCryptionWriter(stream cipher.Stream, writer io.Writer) *CryptionWriter {
|
|
|
|
return &CryptionWriter{
|
2016-02-25 15:53:21 -05:00
|
|
|
stream: stream,
|
|
|
|
writer: writer,
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2016-03-09 18:33:14 -05:00
|
|
|
func (this *CryptionWriter) Write(data []byte) (int, error) {
|
|
|
|
if this.writer == nil {
|
2016-06-22 09:12:57 -04:00
|
|
|
return 0, common.ErrObjectReleased
|
2016-03-09 18:33:14 -05:00
|
|
|
}
|
2016-02-25 15:53:21 -05:00
|
|
|
this.stream.XORKeyStream(data, data)
|
|
|
|
return this.writer.Write(data)
|
|
|
|
}
|
2016-03-09 18:33:14 -05:00
|
|
|
|
|
|
|
func (this *CryptionWriter) Release() {
|
|
|
|
this.writer = nil
|
|
|
|
this.stream = nil
|
|
|
|
}
|