1
0
mirror of https://github.com/v2fly/v2ray-core.git synced 2024-12-22 01:57:12 -05:00
v2fly/io/encryption.go

57 lines
1.4 KiB
Go
Raw Normal View History

2015-09-08 12:21:15 -04:00
package io
import (
2015-09-08 12:21:33 -04:00
"crypto/cipher"
"io"
2015-09-12 14:36:21 -04:00
"github.com/v2ray/v2ray-core/log"
2015-09-08 12:21:15 -04:00
)
// CryptionReader is a general purpose reader that applies
// block cipher on top of a regular reader.
type CryptionReader struct {
2015-09-12 14:36:21 -04:00
stream cipher.Stream
2015-09-08 12:21:33 -04:00
reader io.Reader
2015-09-08 12:21:15 -04:00
}
2015-09-12 14:36:21 -04:00
func NewCryptionReader(stream cipher.Stream, reader io.Reader) *CryptionReader {
2015-09-16 10:27:36 -04:00
return &CryptionReader{
stream: stream,
reader: reader,
}
2015-09-08 12:21:15 -04:00
}
// Read reads blocks from underlying reader, the length of blocks must be
// a multiply of BlockSize()
func (reader CryptionReader) Read(blocks []byte) (int, error) {
2015-09-08 12:21:33 -04:00
nBytes, err := reader.reader.Read(blocks)
2015-09-12 14:36:21 -04:00
if nBytes > 0 {
reader.stream.XORKeyStream(blocks[:nBytes], blocks[:nBytes])
2015-09-08 12:21:33 -04:00
}
2015-09-14 16:01:01 -04:00
if err != nil && err != io.EOF {
2015-09-12 14:36:21 -04:00
log.Error("Error reading blocks: %v", err)
2015-09-08 12:21:33 -04:00
}
return nBytes, err
2015-09-08 12:21:15 -04:00
}
// Cryption writer is a general purpose of byte stream writer that applies
// block cipher on top of a regular writer.
type CryptionWriter struct {
2015-09-12 14:36:21 -04:00
stream cipher.Stream
2015-09-08 12:21:33 -04:00
writer io.Writer
2015-09-08 12:21:15 -04:00
}
2015-09-12 14:36:21 -04:00
func NewCryptionWriter(stream cipher.Stream, writer io.Writer) *CryptionWriter {
2015-09-16 10:27:36 -04:00
return &CryptionWriter{
stream: stream,
writer: writer,
}
2015-09-08 12:21:15 -04:00
}
// Write writes the give blocks to underlying writer. The length of the blocks
// must be a multiply of BlockSize()
func (writer CryptionWriter) Write(blocks []byte) (int, error) {
2015-09-12 14:36:21 -04:00
writer.stream.XORKeyStream(blocks, blocks)
2015-09-08 12:21:33 -04:00
return writer.writer.Write(blocks)
2015-09-08 12:21:15 -04:00
}