mirror of
https://github.com/clearlinux/clr-installer.git
synced 2026-08-19 13:57:09 +00:00
dedda923e7
Signed-off-by: Mark D Horn <mark.d.horn@intel.com>
54 lines
1.1 KiB
Go
54 lines
1.1 KiB
Go
// Copyright © 2019 Intel Corporation
|
|
//
|
|
// SPDX-License-Identifier: GPL-3.0-only
|
|
|
|
package encrypt
|
|
|
|
import (
|
|
"crypto/rand"
|
|
"fmt"
|
|
|
|
"github.com/GehirnInc/crypt"
|
|
// package requires importing the hash method to blank
|
|
_ "github.com/GehirnInc/crypt/sha512_crypt"
|
|
)
|
|
|
|
// CreateSalt generates a random salt for encrypting user password
|
|
func CreateSalt() (string, error) {
|
|
const saltBytes int = 19
|
|
|
|
dict := "./0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
|
|
|
|
salt := make([]byte, saltBytes)
|
|
_, err := rand.Read(salt)
|
|
if err != nil {
|
|
return "", err
|
|
}
|
|
|
|
salt[0] = '$'
|
|
salt[1] = '6'
|
|
salt[2] = '$'
|
|
|
|
for i := 3; i < saltBytes; i++ {
|
|
salt[i] = dict[salt[i]%byte(len(dict))]
|
|
}
|
|
|
|
return string(salt), nil
|
|
}
|
|
|
|
// Crypt takes a password and hashes with a random salt using SHA512
|
|
func Crypt(password string) (string, error) {
|
|
salt, saltErr := CreateSalt()
|
|
if saltErr != nil {
|
|
return "", fmt.Errorf("Cannot generate salt: %v", saltErr)
|
|
}
|
|
|
|
crypt := crypt.SHA512.New()
|
|
hash, hashErr := crypt.Generate([]byte(password), []byte(salt))
|
|
if hashErr != nil {
|
|
return "", fmt.Errorf("Cannot generate salt: %v", hashErr)
|
|
}
|
|
|
|
return hash, nil
|
|
}
|