1
0
mirror of https://github.com/v2fly/v2ray-core.git synced 2024-11-15 16:56:08 -05:00
v2fly/common/crypto/io.go

67 lines
1.3 KiB
Go
Raw Normal View History

package crypto
import (
"crypto/cipher"
"io"
2017-04-16 16:30:29 -04:00
"v2ray.com/core/common/buf"
)
2016-03-09 18:33:14 -05:00
type CryptionReader struct {
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{
stream: stream,
reader: reader,
}
}
2017-04-16 16:30:29 -04:00
func (r *CryptionReader) Read(data []byte) (int, error) {
nBytes, err := r.reader.Read(data)
if nBytes > 0 {
2017-04-16 16:30:29 -04:00
r.stream.XORKeyStream(data[:nBytes], data[:nBytes])
}
return nBytes, err
}
2017-04-23 07:41:52 -04:00
var (
2017-11-09 16:33:15 -05:00
_ buf.Writer = (*CryptionWriter)(nil)
2017-04-23 07:41:52 -04:00
)
2016-03-09 18:33:14 -05:00
type CryptionWriter struct {
2018-08-17 05:51:59 -04:00
stream cipher.Stream
writer io.Writer
bufWriter buf.Writer
}
2016-12-27 18:53:29 -05:00
// NewCryptionWriter creates a new CryptionWriter.
2016-03-09 18:33:14 -05:00
func NewCryptionWriter(stream cipher.Stream, writer io.Writer) *CryptionWriter {
return &CryptionWriter{
2018-08-17 05:51:59 -04:00
stream: stream,
writer: writer,
bufWriter: buf.NewWriter(writer),
}
}
2016-12-27 18:53:29 -05:00
// Write implements io.Writer.Write().
2017-04-16 16:30:29 -04:00
func (w *CryptionWriter) Write(data []byte) (int, error) {
w.stream.XORKeyStream(data, data)
2018-08-17 05:51:59 -04:00
if err := buf.WriteAllBytes(w.writer, data); err != nil {
return 0, err
}
return len(data), nil
2017-04-16 16:30:29 -04:00
}
2018-04-11 10:15:29 -04:00
// WriteMultiBuffer implements buf.Writer.
2017-04-23 07:41:52 -04:00
func (w *CryptionWriter) WriteMultiBuffer(mb buf.MultiBuffer) error {
2018-08-17 05:51:59 -04:00
for _, b := range mb {
w.stream.XORKeyStream(b.Bytes(), b.Bytes())
2017-04-16 16:30:29 -04:00
}
2018-07-27 17:44:22 -04:00
2018-08-17 05:51:59 -04:00
return w.bufWriter.WriteMultiBuffer(mb)
}