You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
v2ray-core/io/encryption.go

59 lines
1.5 KiB

package io
import (
9 years ago
"crypto/cipher"
"io"
"github.com/v2ray/v2ray-core/log"
)
// CryptionReader is a general purpose reader that applies
// block cipher on top of a regular reader.
type CryptionReader struct {
stream cipher.Stream
9 years ago
reader io.Reader
}
func NewCryptionReader(stream cipher.Stream, reader io.Reader) *CryptionReader {
9 years ago
this := new(CryptionReader)
this.stream = stream
9 years ago
this.reader = reader
return this
}
// Read reads blocks from underlying reader, the length of blocks must be
// a multiply of BlockSize()
func (reader CryptionReader) Read(blocks []byte) (int, error) {
9 years ago
nBytes, err := reader.reader.Read(blocks)
log.Debug("CryptionReader: Read %d bytes", nBytes)
if nBytes > 0 {
reader.stream.XORKeyStream(blocks[:nBytes], blocks[:nBytes])
9 years ago
}
if err != nil {
log.Error("Error reading blocks: %v", err)
9 years ago
}
return nBytes, err
}
// Cryption writer is a general purpose of byte stream writer that applies
// block cipher on top of a regular writer.
type CryptionWriter struct {
stream cipher.Stream
9 years ago
writer io.Writer
}
func NewCryptionWriter(stream cipher.Stream, writer io.Writer) *CryptionWriter {
9 years ago
this := new(CryptionWriter)
this.stream = stream
9 years ago
this.writer = writer
return this
}
// 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) {
log.Debug("CryptionWriter writing %d bytes", len(blocks))
writer.stream.XORKeyStream(blocks, blocks)
9 years ago
return writer.writer.Write(blocks)
}