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

59 lines
1.5 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-08 12:21:33 -04:00
this := new(CryptionReader)
2015-09-12 14:36:21 -04:00
this.stream = stream
2015-09-08 12:21:33 -04:00
this.reader = reader
return this
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
log.Debug("CryptionReader: Read %d bytes", nBytes)
if nBytes > 0 {
reader.stream.XORKeyStream(blocks[:nBytes], blocks[:nBytes])
2015-09-08 12:21:33 -04:00
}
2015-09-12 14:36:21 -04:00
if err != nil {
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-08 12:21:33 -04:00
this := new(CryptionWriter)
2015-09-12 14:36:21 -04:00
this.stream = stream
2015-09-08 12:21:33 -04:00
this.writer = writer
return this
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
log.Debug("CryptionWriter writing %d bytes", len(blocks))
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
}