1
0
mirror of https://github.com/v2fly/v2ray-core.git synced 2024-09-28 14:56:33 -04:00
v2fly/common/io/encryption.go

55 lines
1.6 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-08 12:21:15 -04:00
)
2015-09-21 05:44:53 -04:00
// CryptionReader is a general purpose reader that applies a stream cipher on top of a regular reader.
2015-09-08 12:21:15 -04:00
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-21 05:44:53 -04:00
// NewCryptionReader creates a new CryptionReader instance from given stream cipher and reader.
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
}
2015-09-21 05:44:53 -04:00
// Read reads blocks from underlying reader, and crypt it. The content of blocks is modified in place.
2015-09-08 12:21:15 -04:00
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
}
return nBytes, err
2015-09-08 12:21:15 -04:00
}
2015-09-21 05:44:53 -04:00
// Cryption writer is a general purpose of byte stream writer that applies a stream cipher on top of a regular writer.
2015-09-08 12:21:15 -04:00
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-21 05:44:53 -04:00
// NewCryptionWriter creates a new CryptionWriter from given stream cipher and writer.
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
}
2015-09-21 05:44:53 -04:00
// Crypt crypts the content of blocks without writing them into the underlying writer.
func (writer CryptionWriter) Crypt(blocks []byte) {
writer.stream.XORKeyStream(blocks, blocks)
}
2015-09-21 05:44:53 -04:00
// Write crypts the content of blocks in place, and then writes the give blocks to underlying writer.
2015-09-08 12:21:15 -04:00
func (writer CryptionWriter) Write(blocks []byte) (int, error) {
writer.Crypt(blocks)
2015-09-08 12:21:33 -04:00
return writer.writer.Write(blocks)
2015-09-08 12:21:15 -04:00
}