Skip to content

Instantly share code, notes, and snippets.

@stvoidit
Created September 23, 2023 19:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save stvoidit/21066e35a6fd977851b61100cef85e29 to your computer and use it in GitHub Desktop.
Save stvoidit/21066e35a6fd977851b61100cef85e29 to your computer and use it in GitHub Desktop.
golang CTR encoding and decoding for big files or stream
import (
"crypto/aes"
"crypto/cipher"
"crypto/hmac"
"crypto/rand"
"crypto/sha512"
"encoding/base64"
"errors"
"hash/fnv"
"io"
"os"
)
// Cryptographer - ...
type Cryptographer struct {
key []byte
}
// NewCryptographer - ...
func NewCryptographer(key string) *Cryptographer {
h := fnv.New128a()
h.Write([]byte(key))
return &Cryptographer{key: h.Sum(nil)}
}
// Decrypt - ...
func (e Cryptographer) Decrypt(data []byte) ([]byte, error) {
block, err := aes.NewCipher(e.key)
if err != nil {
return nil, err
}
var size = block.BlockSize()
if len(data) < size {
return nil, errors.New("text is too short")
}
iv := data[:size]
data = data[size:]
cipher.NewCTR(block, iv).XORKeyStream(data, data)
return data, nil
}
// Encrypt - ...
func (e Cryptographer) Encrypt(data []byte) ([]byte, error) {
block, err := aes.NewCipher(e.key)
if err != nil {
return nil, err
}
var size = block.BlockSize()
iv := genRandomIV(size)
cipher.NewCTR(block, iv).XORKeyStream(data, data)
return append(iv, data...), nil
}
// StringHMAC - ...
func (e Cryptographer) StringHMAC(value string) string {
hash := hmac.New(sha512.New, e.key)
io.WriteString(hash, value)
return base64.StdEncoding.EncodeToString(hash.Sum(nil))
}
func genRandomIV(size int) []byte {
var iv = make([]byte, size)
rand.Read(iv)
return iv
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment