shad-go/otp/cipher.go

59 lines
899 B
Go
Raw Permalink Normal View History

2022-02-10 22:06:57 +00:00
//go:build !solution
2020-02-28 17:26:29 +00:00
package otp
import (
"io"
)
2024-06-04 22:34:01 +00:00
type cipherReader struct {
r io.Reader
prng io.Reader
}
type cipherWriter struct {
w io.Writer
prng io.Reader
}
func (c *cipherReader) Read(p []byte) (n int, err error) {
n, err = c.r.Read(p)
if err != nil {
if err == io.EOF {
p = p[:n]
} else {
return
}
}
rand := make([]byte, n)
_, rngErr := c.prng.Read(rand)
if rngErr != nil {
return
}
for i := 0; i < n; i++ {
p[i] ^= rand[i]
}
return
}
func (c *cipherWriter) Write(p []byte) (n int, err error) {
data := make([]byte, len(p))
_, err = c.prng.Read(data)
if err != nil {
return
}
for i := 0; i < len(p); i++ {
data[i] ^= p[i]
}
n, err = c.w.Write(data)
return
}
2020-02-28 17:26:29 +00:00
func NewReader(r io.Reader, prng io.Reader) io.Reader {
2024-06-04 22:34:01 +00:00
return &cipherReader{r, prng}
2020-02-28 17:26:29 +00:00
}
func NewWriter(w io.Writer, prng io.Reader) io.Writer {
2024-06-04 22:34:01 +00:00
return &cipherWriter{w, prng}
2020-02-28 17:26:29 +00:00
}