From fbafc98edb45bf8dfe024c2814c27a6c6d200e38 Mon Sep 17 00:00:00 2001 From: Harshavardhana Date: Wed, 28 Jan 2015 11:48:26 -0800 Subject: [PATCH] Add a new pkg/crypto/keys, first cut - provides three functions - GetRandomAlphaNumeric() - GetRandomAlphaNumericFull() - GetRandomBase64() - ValidAccessKey() --- pkg/utils/crypto/keys/common.go | 10 ++++++ pkg/utils/crypto/keys/keys.go | 62 +++++++++++++++++++++++++++++++++ 2 files changed, 72 insertions(+) create mode 100644 pkg/utils/crypto/keys/common.go create mode 100644 pkg/utils/crypto/keys/keys.go diff --git a/pkg/utils/crypto/keys/common.go b/pkg/utils/crypto/keys/common.go new file mode 100644 index 000000000..9a13a0126 --- /dev/null +++ b/pkg/utils/crypto/keys/common.go @@ -0,0 +1,10 @@ +package keys + +const ( + MINIO_ACCESS_ID = 20 + MINIO_SECRET_ID = 40 +) + +func isalnum(c byte) bool { + return '0' <= c && c <= '9' || 'A' <= c && c <= 'Z' || 'a' <= c && c <= 'z' +} diff --git a/pkg/utils/crypto/keys/keys.go b/pkg/utils/crypto/keys/keys.go new file mode 100644 index 000000000..961bcbe42 --- /dev/null +++ b/pkg/utils/crypto/keys/keys.go @@ -0,0 +1,62 @@ +package keys + +import ( + "crypto/rand" +) + +var alphaNumericTable = []byte("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ") +var alphaNumericTableFull = []byte("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789") + +func GetRandomAlphaNumeric(size int) ([]byte, error) { + alpha := make([]byte, size) + _, err := rand.Read(alpha) + if err != nil { + return nil, err + } + + for i := 0; i < size; i++ { + alpha[i] = alphaNumericTable[alpha[i]%byte(len(alphaNumericTable))] + } + return alpha, nil +} + +func GetRandomAlphaNumericFull(size int) ([]byte, error) { + alphaFull := make([]byte, size) + _, err := rand.Read(alphaFull) + if err != nil { + return nil, err + } + for i := 0; i < size; i++ { + alphaFull[i] = alphaNumericTableFull[alphaFull[i]%byte(len(alphaNumericTableFull))] + } + return alphaFull, nil +} + +func GetRandomBase64(size int) ([]byte, error) { + rb := make([]byte, size) + n, err := rand.Read(rb) + if err != nil { + return nil, err + } + dest := make([]byte, n) + base64.URLEncoding.EncodeTo(dest, rb) + return dest, nil +} + +func ValidateAccessKey(key []byte) bool { + for _, char := range key { + if isalnum(char) { + continue + } + switch char { + case '-': + case '.': + case '_': + case '~': + continue + default: + return false + } + } + return true +}