https://github.com/uhthomas/seekctr
A seekable CTR stream cipher
https://github.com/uhthomas/seekctr
aes cipher ctr go seek stream
Last synced: 8 months ago
JSON representation
A seekable CTR stream cipher
- Host: GitHub
- URL: https://github.com/uhthomas/seekctr
- Owner: uhthomas
- License: gpl-3.0
- Created: 2019-01-06T02:16:26.000Z (about 7 years ago)
- Default Branch: master
- Last Pushed: 2023-12-15T14:44:36.000Z (about 2 years ago)
- Last Synced: 2025-06-19T03:13:04.759Z (8 months ago)
- Topics: aes, cipher, ctr, go, seek, stream
- Language: Go
- Size: 26.4 KB
- Stars: 3
- Watchers: 2
- Forks: 2
- Open Issues: 2
-
Metadata Files:
- Readme: README.md
- License: LICENSE
Awesome Lists containing this project
README
# seekctr [](https://godoc.org/github.com/uhthomas/seekctr)
[cipher.Stream](https://pkg.go.dev/crypto/cipher#Stream) does not implement [io.Seeker](https://pkg.go.dev/io#Seeker) despite XOR stream ciphers being seekable.
## Usage
```go
package main
import (
"fmt"
"io"
"log"
"os"
"github.com/uhthomas/seekctr"
)
func main() {
// your key and initialization vector
var key, iv []byte
// open the encrypted file or stream
f, err := os.Open("encrypted file")
if err != nil {
log.Fatal(err)
}
r, err := seekctr.NewReader(f, key, iv)
if err != nil {
log.Fatal(err)
}
// Seek past the first 1Kb
if _, err := r.Seek(1 << 10); err != nil {
log.Fatal(err)
}
// copy the remaining contents to stdout
if _, err := io.Copy(os.Stdout, r); err != nil {
log.Fatal(err)
}
}
```
## Note
Recreating the original stream cipher with a new initialization vector (where `iv += offset / block size`) and discarding the remaining bytes (`offset % block size`) may be preferrable.
```go
var key, iv [16]byte
b, err := aes.NewCipher(key[:])
if err != nil { ... }
offset := uint64(4 << 10)
// offset in chunks
chunks := uint64(int(offset) / b.BlockSize())
// iv += offset
var c uint16
for i := len(iv[:]) - 1; i >= 0; i-- {
c = uint16(iv[i]) + uint16(chunks & 0xFF) + c
iv[i], c, chunks = byte(c), c >> 8, chunks >> 8
}
// Reinitialize cipher
s := cipher.NewCTR(b, iv[:])
// Discard n bytes
d := make([]byte, int(offset) % b.BlockSize())
s.XORKeyStream(d, d)
```