Created
July 28, 2020 00:15
-
-
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…
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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