Created
April 3, 2018 13:05
-
-
Save Satak/5347b9354fd8581238815430a3dd587a to your computer and use it in GitHub Desktop.
This file contains hidden or 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 ( | |
"encoding/base64" | |
"fmt" | |
"math/rand" | |
"time" | |
"golang.org/x/crypto/bcrypt" | |
) | |
var bcryptCost = 12 | |
const charset = "abcdefghijklmnopqrstuvwxyz" + | |
"ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789" | |
var seededRand *rand.Rand = rand.New(rand.NewSource(time.Now().UnixNano())) | |
func stringWithCharset(length int, charset string) string { | |
b := make([]byte, length) | |
for i := range b { | |
b[i] = charset[seededRand.Intn(len(charset))] | |
} | |
return string(b) | |
} | |
func generateRandomString(length int) string { | |
return stringWithCharset(length, charset) | |
} | |
func main() { | |
// generate random string | |
plaintext := generateRandomString(15) | |
// convert string to byte array | |
byteArray := []byte(plaintext) | |
// hash the random string with the bcryptCost | |
hashedPassword, err := bcrypt.GenerateFromPassword(byteArray, bcryptCost) | |
if err != nil { | |
panic(err) | |
} | |
// base64 encode the hash | |
encoded := base64.StdEncoding.EncodeToString([]byte(hashedPassword)) | |
// print plain text and hashed/encoded result | |
fmt.Println(string(encoded)) | |
fmt.Println(string(plaintext)) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment