Skip to content

Instantly share code, notes, and snippets.

@Satak
Created April 3, 2018 13:05
Show Gist options
  • Save Satak/5347b9354fd8581238815430a3dd587a to your computer and use it in GitHub Desktop.
Save Satak/5347b9354fd8581238815430a3dd587a to your computer and use it in GitHub Desktop.
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