From ccbf44e3fc35dcb7cdd02e21536a81c28be704b7 Mon Sep 17 00:00:00 2001 From: khiem20tc Date: Mon, 9 Oct 2023 21:09:06 +0700 Subject: [PATCH] chore(key): add key utils --- utils/key/key.go | 46 ++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 46 insertions(+) create mode 100644 utils/key/key.go diff --git a/utils/key/key.go b/utils/key/key.go new file mode 100644 index 0000000..c14d1a0 --- /dev/null +++ b/utils/key/key.go @@ -0,0 +1,46 @@ +package key + +import ( + "crypto/rand" + "math/big" + "sync" +) + +const ( + // Define the character sets for API key and API secret. + apiKeyCharset = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789" + apiSecretCharset = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789@#$%&?" + apiKeyLength = 32 // Adjust the length as needed. + apiSecretLength = 128 // Adjust the length as needed. +) + +func GenerateAPIKey() (string, string) { + apiKey, secretKey := "", "" + wg := sync.WaitGroup{} + wg.Add(2) + go func() { + defer wg.Done() + apiKey = generateRandomString(apiKeyCharset, apiKeyLength) + }() + go func() { + defer wg.Done() + secretKey = generateRandomString(apiSecretCharset, apiSecretLength) + }() + wg.Wait() + return apiKey, secretKey +} + +func generateRandomString(charset string, length int) string { + // Calculate the maximum index in the charset. + maxIndex := big.NewInt(int64(len(charset))) + + // Generate random indices and create the string. + var result string + for i := 0; i < length; i++ { + index, _ := rand.Int(rand.Reader, maxIndex) + + result += string(charset[index.Int64()]) + } + + return result +}