Skip to content

Instantly share code, notes, and snippets.

@maxsei
Last active August 22, 2024 23:11
Show Gist options
  • Save maxsei/b52feacceaf89a7b9a02fc76cc935ace to your computer and use it in GitHub Desktop.
Save maxsei/b52feacceaf89a7b9a02fc76cc935ace to your computer and use it in GitHub Desktop.
Nice way of obfuscating database ids https://go.dev/play/p/4t9Ej8xOG5C
package main
import (
"bytes"
"encoding/base32"
"encoding/binary"
"fmt"
"io"
)
func main() {
const key = Key(1528132745924452051)
src := uint64(69420)
buf := bytes.NewBuffer(nil)
if err := key.Encode(src, buf); err != nil {
panic(err)
}
dst, err := key.Decode(buf)
if err != nil {
panic(err)
}
fmt.Printf("src = %v\ndst = %v\n", src, dst)
}
type Key uint64
func (k Key) Encode(v uint64, w io.Writer) error {
encoder := base32.NewEncoder(base32.StdEncoding, w)
if err := binary.Write(encoder, binary.LittleEndian, v^uint64(k)); err != nil {
return err
}
return encoder.Close()
}
func (k Key) Decode(r io.Reader) (uint64, error) {
var idEncrypted uint64
if err := binary.Read(base32.NewDecoder(base32.StdEncoding, r), binary.LittleEndian, &idEncrypted); err != nil {
return 0, err
}
return uint64(k) ^ idEncrypted, nil
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment