Skip to content

Instantly share code, notes, and snippets.

@tanema
Created July 28, 2020 00:15
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 tanema/3c68bbd75eec4b666bc23bfdcbc3ca95 to your computer and use it in GitHub Desktop.
Save tanema/3c68bbd75eec4b666bc23bfdcbc3ca95 to your computer and use it in GitHub Desktop.
If you need a displayable ID but do not want to generate an ID with uniqueness constraints and try and get it into the database without breaking everything, try just encrypting your ID so that it looks like a nice visible ID but also without your secrets it cannot be reverse engineered to the original ID. See it here https://play.golang.org/p/Em…
package main
import (
"fmt"
"strconv"
"strings"
)
const (
// These are secret random numbers that are meant to help encrypt and disguise
// our normal database IDs.
// encryption: (x + base1) ^ base2 => int to hex
// decryption: hex to int => (x ^ base2) - base1
cryptbase1 int = 9872340
cryptbase2 int = 5653098
)
// IdentToID converts a fuzz ident to an ID (look I know that ID stands for identity, don't @ me)
func IdentToID(ident string) int {
parsed, _ := strconv.ParseInt(ident, 16, 32)
return (int(parsed) ^ cryptbase2) - cryptbase1
}
// IDtoIdent will convert an integer ID from the DB to an `ident`
func IDtoIdent(id int) string {
return strings.ToUpper(strconv.FormatInt(int64((id+cryptbase1)^cryptbase2), 16))
}
func main() {
id := 42
ident := IDtoIdent(id)
fmt.Println("Fuzzy Ident: ", ident)
fmt.Println("Ident Back to ID: ", IdentToID(ident))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment