v2ray-core/common/crypto/io.go

67 lines
1.3 KiB
Go
Raw Normal View History

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