本文整理汇总了Golang中golang.org/x/crypto/scrypt.Key函数的典型用法代码示例。如果您正苦于以下问题:Golang Key函数的具体用法?Golang Key怎么用?Golang Key使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了Key函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。
示例1: verifyAdminPwd
func (d *Daemon) verifyAdminPwd(password string) bool {
value, err := dbPasswordGet(d.db)
if err != nil {
shared.Debugf("verifyAdminPwd: %s", err)
return false
}
buff, err := hex.DecodeString(value)
if err != nil {
shared.Debugf("hex decode failed")
return false
}
salt := buff[0:PW_SALT_BYTES]
hash, err := scrypt.Key([]byte(password), salt, 1<<14, 8, 1, PW_HASH_BYTES)
if err != nil {
shared.Debugf("failed to create hash to check")
return false
}
if !bytes.Equal(hash, buff[PW_SALT_BYTES:]) {
shared.Debugf("Bad password received")
return false
}
shared.Debugf("Verified the admin password")
return true
}
示例2: Run
// Run starts the engine.
func (e *PaperKeyGen) Run(ctx *Context) error {
// make the passphrase stream
key, err := scrypt.Key(e.arg.Passphrase.Bytes(), nil,
libkb.PaperKeyScryptCost, libkb.PaperKeyScryptR, libkb.PaperKeyScryptP, libkb.PaperKeyScryptKeylen)
if err != nil {
return err
}
ppStream := libkb.NewPassphraseStream(key)
// make keys for the paper device
if err := e.makeSigKey(ppStream.EdDSASeed()); err != nil {
return err
}
if err := e.makeEncKey(ppStream.DHSeed()); err != nil {
return err
}
// push everything to the server
if err := e.push(ctx); err != nil {
return err
}
// no need to notify if key wasn't pushed to server
// (e.g. in the case of using this engine to verify a key)
if e.arg.SkipPush {
return nil
}
e.G().NotifyRouter.HandleKeyfamilyChanged(e.arg.Me.GetUID())
// Remove this after kbfs notification change complete
e.G().NotifyRouter.HandleUserChanged(e.arg.Me.GetUID())
return nil
}
示例3: PasswordSet
// PasswordSet sets the password to the new value.
func (d *Daemon) PasswordSet(password string) error {
shared.Log.Info("Setting new https password")
var value = password
if password != "" {
buf := make([]byte, pwSaltBytes)
_, err := io.ReadFull(rand.Reader, buf)
if err != nil {
return err
}
hash, err := scrypt.Key([]byte(password), buf, 1<<14, 8, 1, pwHashBytes)
if err != nil {
return err
}
buf = append(buf, hash...)
value = hex.EncodeToString(buf)
}
err := d.ConfigValueSet("core.trust_password", value)
if err != nil {
return err
}
return nil
}
示例4: Decrypt
// Decrypt decrypts an encrypted message and returns it (plaintext).
// If you have enabled compression, it wil detect it and decompress
// the msg after decrypting it.
func (c SaltSecret) Decrypt(msg []byte) ([]byte, error) {
if len(msg) < nonceSize+secretbox.Overhead {
return nil, errors.New("encrypted message length too short")
}
nonce := new([nonceSize]byte)
copy(nonce[:], msg[:nonceSize])
key, err := scrypt.Key(c.key, nonce[:], 2<<c.NPow, 8, 1, keySize)
if err != nil {
return nil, err
}
naclKey := new([keySize]byte)
copy(naclKey[:], key)
out, ok := secretbox.Open(nil, msg[nonceSize:], nonce, naclKey)
if !ok {
return nil, errors.New("could not decrypt message")
}
if nonce[23]&compressBit == compressBit {
r, err := zlib.NewReader(bytes.NewReader(out))
if err != nil {
return nil, err
}
r.Close()
out, err = ioutil.ReadAll(r)
if err != nil {
return nil, err
}
}
return out, nil
}
示例5: setTrustPassword
func setTrustPassword(d *Daemon, password string) error {
shared.Debugf("setting new password")
var value = password
if password != "" {
buf := make([]byte, PW_SALT_BYTES)
_, err := io.ReadFull(rand.Reader, buf)
if err != nil {
return err
}
hash, err := scrypt.Key([]byte(password), buf, 1<<14, 8, 1, PW_HASH_BYTES)
if err != nil {
return err
}
buf = append(buf, hash...)
value = hex.EncodeToString(buf)
}
err := setServerConfig(d, "core.trust_password", value)
if err != nil {
return err
}
return nil
}
示例6: DecryptKey
func DecryptKey(ks keyStorePassphrase, keyAddr []byte, auth string) (keyBytes []byte, keyId []byte, err error) {
fileContent, err := GetKeyFile(ks.keysDirPath, keyAddr)
if err != nil {
return nil, nil, err
}
keyProtected := new(encryptedKeyJSON)
err = json.Unmarshal(fileContent, keyProtected)
keyId = keyProtected.Id
salt := keyProtected.Crypto.Salt
iv := keyProtected.Crypto.IV
cipherText := keyProtected.Crypto.CipherText
authArray := []byte(auth)
derivedKey, err := scrypt.Key(authArray, salt, scryptN, scryptr, scryptp, scryptdkLen)
if err != nil {
return nil, nil, err
}
plainText, err := aesCBCDecrypt(derivedKey, cipherText, iv)
if err != nil {
return nil, nil, err
}
keyBytes = plainText[:len(plainText)-32]
keyBytesHash := plainText[len(plainText)-32:]
if !bytes.Equal(Sha3(keyBytes), keyBytesHash) {
err = errors.New("Decryption failed: checksum mismatch")
return nil, nil, err
}
return keyBytes, keyId, err
}
示例7: EncodePassword
func EncodePassword(rawPwd string, salt string) string {
pwd, err := scrypt.Key([]byte(rawPwd), []byte(salt), 16384, 8, 1, 64)
if err != nil {
log.Println("EncodePassword error: %s", err)
}
return hex.EncodeToString(pwd)
}
示例8: CalculatePassword
// Calculate the password based on a key derived from the master password and the account name
// The key derivation is implemented by the popular "scrypt" algorithm.
func CalculatePassword(accountName string, masterPassword string, salt string) string {
derivedKey, err := scrypt.Key([]byte(masterPassword), []byte(salt+accountName), 16384, 8, 1, 128)
if err != nil {
panic(err)
}
return ComputeHmac256(accountName, string(derivedKey))[:32]
}
示例9: GenerateFromPassword
/**
* Creates an encoded sequence of bytes containing all of the parameters passed to
* scrypt and the hash itself. Presented with a very similar interface to that of
* golang.org/x/crypto/bcrypt.
*/
func GenerateFromPassword(password []byte, parameters HashConfiguration) ([]byte, error) {
// Do an extra check on the input to make sure it meets our standards.
paramErr := verifyParameterValidity(parameters)
if paramErr != nil {
return nil, paramErr
}
// Pull some random bytes to use as a salt and make sure we got as much as expected.
salt := make([]byte, parameters.SaltLen)
bytesRead, randSrcErr := rand.Read(salt)
if HashParameter(bytesRead) != parameters.SaltLen {
return nil, ErrInsufficientRandomData
}
if randSrcErr != nil {
return nil, randSrcErr
}
// Invoke the scrypt library and augment the hashed value with the hash parameters.
hashedValue, hashErr := scrypt.Key(
password,
salt,
int(parameters.N),
int(parameters.R),
int(parameters.P),
int(parameters.KeyLen))
if hashErr != nil {
return nil, hashErr
}
return encodeParameters(hashedValue, salt, parameters), nil
}
示例10: encryptToken
func encryptToken(key []byte, j *JobToken) ([]byte, error) {
jsonData := j.JSON()
ciphertext := make([]byte, aes.BlockSize+len(jsonData))
iv := ciphertext[:aes.BlockSize]
if _, err := io.ReadFull(rand.Reader, iv); err != nil {
return nil, err
}
sKey, serr := scrypt.Key(key, iv, scrypt_n, scrypt_r, scrypt_p, scrypt_keyLen)
if serr != nil {
return nil, serr
}
block, berr := aes.NewCipher(sKey)
if berr != nil {
return nil, berr
}
cfb := cipher.NewCFBEncrypter(block, iv)
cfb.XORKeyStream(ciphertext[aes.BlockSize:], jsonData)
return ciphertext, nil
}
示例11: decryptToken
func decryptToken(key, ciphertext []byte) ([]byte, error) {
// The IV needs to be unique, but not secure. Therefore it's common to
// include it at the beginning of the ciphertext.
if len(ciphertext) < aes.BlockSize {
return nil, errors.New("ciphertext too short")
}
iv := ciphertext[:aes.BlockSize]
ciphertext = ciphertext[aes.BlockSize:]
sKey, serr := scrypt.Key(key, iv, scrypt_n, scrypt_r, scrypt_p, scrypt_keyLen)
if serr != nil {
return nil, serr
}
block, err := aes.NewCipher(sKey)
if err != nil {
return nil, err
}
stream := cipher.NewCFBDecrypter(block, iv)
// XORKeyStream can work in-place if the two arguments are the same.
stream.XORKeyStream(ciphertext, ciphertext)
return ciphertext, nil
}
示例12: handleLoginPass
func handleLoginPass(world World, c net.Conn, playerName string) {
playerName = strings.ToLower(playerName)
c.Write([]byte("Please enter your password.\r\n"))
pass, err := getBytesSecure(c)
defer func() {
for i := range pass {
pass[i] = 0
}
}()
if err != nil {
return
}
player, exists := world.players.GetByName(playerName)
if !exists {
return // we just validated the player exists, so this shouldn't happen
}
hashedPass, err := scrypt.Key([]byte(pass), player.passthesalt, 16384, 8, 1, 32)
if err != nil {
fmt.Printf("Error creating hashed pass: %v\n", err)
c.Close()
return
}
if !bytes.Equal(hashedPass, player.pass) {
c.Write([]byte("Invalid password.\r\n"))
c.Close()
return
}
world.players.ChangeById(player.Id(), func(p *Player) {
p.connection = c
})
go handlePlayer(world, player.Id())
}
示例13: CreateUser
// CreateUser creates a new user record
func CreateUser(ctx context.Context, email, password string) error {
if email == "" {
return fmt.Errorf("invalid email")
}
if password == "" {
return fmt.Errorf("invalid password")
}
key := datastore.NewKey(ctx, "User", email, 0, nil)
var user User
err := datastore.Get(ctx, key, &user)
if err == nil {
return fmt.Errorf("user already exists")
}
salt := make([]byte, 16)
rand.Read(salt)
hash, err := scrypt.Key([]byte(password), salt, scryptN, scryptR, scryptP, scryptKeyLen)
if err != nil {
return err
}
user = User{
Email: email,
PasswordSalt: salt,
PasswordHash: hash,
}
_, err = datastore.Put(ctx, key, &user)
return err
}
示例14: DeriveKey
// DeriveKey returns a new key from a supplied password.
func (s *ScryptKDF) DeriveKey(pw string) []byte {
k, err := scrypt.Key([]byte(pw), s.Salt, s.N, s.R, s.P, s.KeyLen)
if err != nil {
log.Panicf("DeriveKey failed: %v", err)
}
return k
}
示例15: Compare
// Compare compares a plaintext password to a hashed password.
// password is a plaintext password.
// hpass is hashed password string in $s0$ format.
// returns true if passwords match, false otherwise.
func Compare(password, hpass string) bool {
seg := strings.Split(hpass, "$")
if len(seg) != 5 || seg[1] != "s0" {
return false
}
values, _ := strconv.ParseInt(seg[2], 10, 64)
salt, _ := base64.RawStdEncoding.DecodeString(seg[3])
hashed1, _ := base64.RawStdEncoding.DecodeString(seg[4])
N := int(math.Pow(2, float64(values>>16&0xffff)))
r := int(values) >> 8 & 0xff
p := int(values) & 0xff
hashed2, _ := scrypt.Key([]byte(password), salt, N, r, p, KeyLen)
len1 := len(hashed1)
if len1 != len(hashed2) {
return false
}
var comp int
for i := 0; i < len1; i++ {
comp |= int(hashed1[i] ^ hashed2[i])
}
return comp == 0
}