Skip to content

Instantly share code, notes, and snippets.

@tbg
Last active May 1, 2020 08:44
Show Gist options
  • Save tbg/d309874b0efdb7714cabc38ae4186d27 to your computer and use it in GitHub Desktop.
Save tbg/d309874b0efdb7714cabc38ae4186d27 to your computer and use it in GitHub Desktop.
mangle user and tenantid
package main
import (
"crypto/rand"
"encoding/base64"
"fmt"
"strconv"
"strings"
"golang.org/x/crypto/nacl/secretbox"
)
var secretKey [32]byte
func init() {
if _, err := rand.Read(secretKey[:]); err != nil {
panic(err)
}
}
func encodeUser(secretKey *[32]byte, tenantID int, sqlLogin string) string {
var nonce [24]byte
if _, err := rand.Read(nonce[:]); err != nil {
panic(err)
}
sealed := secretbox.Seal(nil, []byte(fmt.Sprintf("%s@%d", sqlLogin, tenantID)), &nonce, secretKey)
nonceSealed := append(nonce[:], sealed...)
return base64.StdEncoding.EncodeToString(nonceSealed)
}
func decodeUser(secretKey *[32]byte, sealed64 string) (tenantID int, sqlLogin string) {
nonceSealed, err := base64.StdEncoding.DecodeString(sealed64)
var nonce [24]byte
copy(nonce[:], nonceSealed[:24])
if err != nil {
panic(err)
}
b, ok := secretbox.Open(nil, nonceSealed[24:], &nonce, secretKey)
if !ok {
panic("not ok")
}
pair := strings.Split(string(b), "@")
if len(pair) != 2 {
panic(pair)
}
tenantID, err = strconv.Atoi(pair[1])
if err != nil {
panic(err)
}
return tenantID, pair[0]
}
func main() {
user := encodeUser(&secretKey, 129, "foobaruser")
fmt.Println(user)
tenantID, sqlLogin := decodeUser(&secretKey, user)
fmt.Println(tenantID, sqlLogin)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment