1
0
mirror of https://github.com/v2fly/v2ray-core.git synced 2024-07-02 12:05:23 +00:00
v2fly/io/encryption.go

57 lines
1.4 KiB
Go
Raw Normal View History

2015-09-08 16:21:15 +00:00
package io
import (
2015-09-08 16:21:33 +00:00
"crypto/cipher"
"io"
2015-09-12 18:36:21 +00:00
"github.com/v2ray/v2ray-core/log"
2015-09-08 16:21:15 +00:00
)
// CryptionReader is a general purpose reader that applies
// block cipher on top of a regular reader.
type CryptionReader struct {
2015-09-12 18:36:21 +00:00
stream cipher.Stream
2015-09-08 16:21:33 +00:00
reader io.Reader
2015-09-08 16:21:15 +00:00
}
2015-09-12 18:36:21 +00:00
func NewCryptionReader(stream cipher.Stream, reader io.Reader) *CryptionReader {
2015-09-08 16:21:33 +00:00
this := new(CryptionReader)
2015-09-12 18:36:21 +00:00
this.stream = stream
2015-09-08 16:21:33 +00:00
this.reader = reader
return this
2015-09-08 16:21:15 +00: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 16:21:33 +00:00
nBytes, err := reader.reader.Read(blocks)
2015-09-12 18:36:21 +00:00
if nBytes > 0 {
reader.stream.XORKeyStream(blocks[:nBytes], blocks[:nBytes])
2015-09-08 16:21:33 +00:00
}
2015-09-14 20:01:01 +00:00
if err != nil && err != io.EOF {
2015-09-12 18:36:21 +00:00
log.Error("Error reading blocks: %v", err)
2015-09-08 16:21:33 +00:00
}
return nBytes, err
2015-09-08 16:21:15 +00: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 18:36:21 +00:00
stream cipher.Stream
2015-09-08 16:21:33 +00:00
writer io.Writer
2015-09-08 16:21:15 +00:00
}
2015-09-12 18:36:21 +00:00
func NewCryptionWriter(stream cipher.Stream, writer io.Writer) *CryptionWriter {
2015-09-08 16:21:33 +00:00
this := new(CryptionWriter)
2015-09-12 18:36:21 +00:00
this.stream = stream
2015-09-08 16:21:33 +00:00
this.writer = writer
return this
2015-09-08 16:21:15 +00: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 18:36:21 +00:00
writer.stream.XORKeyStream(blocks, blocks)
2015-09-08 16:21:33 +00:00
return writer.writer.Write(blocks)
2015-09-08 16:21:15 +00:00
}