当前位置: 首页>>代码示例>>Golang>>正文


Golang pbkdf2.Key函数代码示例

本文整理汇总了Golang中code/google/com/p/go/crypto/pbkdf2.Key函数的典型用法代码示例。如果您正苦于以下问题:Golang Key函数的具体用法?Golang Key怎么用?Golang Key使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。


在下文中一共展示了Key函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。

示例1: decryptKey

func decryptKey(masterPwd []byte, encryptedKey []byte, salt []byte, iterCount int, validation []byte) ([]byte, error) {
	const keyLen = 32
	derivedKey := pbkdf2.Key(masterPwd, salt, iterCount, keyLen, sha1.New)

	aesKey := derivedKey[0:16]
	iv := derivedKey[16:32]
	decryptedKey, err := aesCbcDecrypt(aesKey, encryptedKey, iv)
	if err != nil {
		return nil, err
	}

	validationSalt, validationCipherText, err := extractSaltAndCipherText(validation)
	if err != nil {
		return nil, fmt.Errorf("Invalid validation: %v", err)
	}

	validationAesKey, validationIv := openSslKey(decryptedKey, validationSalt)
	decryptedValidation, err := aesCbcDecrypt(validationAesKey, validationCipherText, validationIv)
	if err != nil {
		return nil, fmt.Errorf("Failed to decrypt validation: %v", err)
	}

	if string(decryptedValidation) != string(decryptedKey) {
		return nil, errors.New("Validation decryption failed")
	}

	return decryptedKey, nil
}
开发者ID:gaku,项目名称:1pass,代码行数:28,代码来源:vault.go

示例2: Secret

// Generates a shared secret key between us and the given public key.
func (p *Peer) Secret(pubKey []byte, size int) ([]byte, error) {
	// Verify and unpack node's public key.
	curveSize := p.curve.Params().BitSize

	if len(pubKey) != (curveSize / 2) {
		return nil, errors.New("Malformed public key.")
	}

	bound := (curveSize / 8)
	x := big.NewInt(0)
	y := big.NewInt(0)

	x.SetBytes(pubKey[0:bound])
	y.SetBytes(pubKey[bound : bound*2])

	if !p.curve.IsOnCurve(x, y) {
		return nil, errors.New("Invalid public key.")
	}

	// Generate shared secret.
	secret, _ := p.curve.ScalarMult(x, y, p.hellman)

	// Use PDKDF2 to make uniform in 2^256.
	dk := pbkdf2.Key(secret.Bytes(), salt, 4096, size, sha256.New)

	return dk, nil
}
开发者ID:Bren2010,项目名称:go-ipfs,代码行数:28,代码来源:peer.go

示例3: Generate

// Generates a derived key based on a salt. rails default key size is 64.
func (g *KeyGenerator) Generate(salt []byte, keySize int) []byte {
	// set a default
	if g.Iterations == 0 {
		g.Iterations = 1000 // rails 4 default when setting the session.
	}
	return pbkdf2.Key([]byte(g.Secret), salt, g.Iterations, keySize, sha1.New)
}
开发者ID:alearceo,项目名称:goRailsYourself,代码行数:8,代码来源:key_generator.go

示例4: generateKey

// Create a new encryption key and encrypt it using the user-provided
// passphrase. Prints output to stdout that gives text to add to the
// ~/.skicka.config file to store the encryption key.
func generateKey() {
	passphrase := os.Getenv(passphraseEnvironmentVariable)
	if passphrase == "" {
		printErrorAndExit(fmt.Errorf(passphraseEnvironmentVariable +
			" environment variable not set."))
	}

	// Derive a 64-byte hash from the passphrase using PBKDF2 with 65536
	// rounds of SHA256.
	salt := getRandomBytes(32)
	hash := pbkdf2.Key([]byte(passphrase), salt, 65536, 64, sha256.New)
	if len(hash) != 64 {
		printErrorAndExit(fmt.Errorf("incorrect key size returned by pbkdf2 %d", len(hash)))
	}

	// We'll store the first 32 bytes of the hash to use to confirm the
	// correct passphrase is given on subsequent runs.
	passHash := hash[:32]
	// And we'll use the remaining 32 bytes as a key to encrypt the actual
	// encryption key. (These bytes are *not* stored).
	keyEncryptKey := hash[32:]

	// Generate a random encryption key and encrypt it using the key
	// derived from the passphrase.
	key := getRandomBytes(32)
	iv := getRandomBytes(16)
	encryptedKey := encryptBytes(keyEncryptKey, iv, key)

	fmt.Printf("; Add the following lines to the [encryption] section\n")
	fmt.Printf("; of your ~/.skicka.config file.\n")
	fmt.Printf("\tsalt=%s\n", hex.EncodeToString(salt))
	fmt.Printf("\tpassphrase-hash=%s\n", hex.EncodeToString(passHash))
	fmt.Printf("\tencrypted-key=%s\n", hex.EncodeToString(encryptedKey))
	fmt.Printf("\tencrypted-key-iv=%s\n", hex.EncodeToString(iv))
}
开发者ID:clonemeagain,项目名称:skicka,代码行数:38,代码来源:skicka.go

示例5: decryptEncryptionKey

// Decrypts the encrypted encryption key using values from the config file
// and the user's passphrase.
func decryptEncryptionKey() []byte {
	if key != nil {
		panic("key aready decrypted!")
	}

	salt := decodeHexString(config.Encryption.Salt)
	passphraseHash := decodeHexString(config.Encryption.Passphrase_hash)
	encryptedKey := decodeHexString(config.Encryption.Encrypted_key)
	encryptedKeyIv := decodeHexString(config.Encryption.Encrypted_key_iv)

	passphrase := os.Getenv(passphraseEnvironmentVariable)
	if passphrase == "" {
		fmt.Fprintf(os.Stderr, "skicka: "+passphraseEnvironmentVariable+
			" environment variable not set")
		os.Exit(1)
	}

	derivedKey := pbkdf2.Key([]byte(passphrase), salt, 65536, 64, sha256.New)
	// Make sure the first 32 bytes of the derived key match the bytes stored
	// when we first generated the key; if they don't, the user gave us
	// the wrong passphrase.
	if !bytes.Equal(derivedKey[:32], passphraseHash) {
		fmt.Fprintf(os.Stderr, "skicka: incorrect passphrase")
		os.Exit(1)
	}

	// Use the last 32 bytes of the derived key to decrypt the actual
	// encryption key.
	keyEncryptKey := derivedKey[32:]
	return decryptBytes(keyEncryptKey, encryptedKeyIv, encryptedKey)
}
开发者ID:clonemeagain,项目名称:skicka,代码行数:33,代码来源:skicka.go

示例6: NewSession

// NewSession generates and saves a new session for the specified user, with the specified
// client name. This function also randomly generates public and private keys.
func NewSession(userID int, password string, client string) (*Session, error) {
	// Generate session
	session := &Session{
		UserID: userID,
		Client: client,
	}

	// Make session expire in one week, without use
	session.Expire = time.Now().Add(time.Duration(7 * 24 * time.Hour)).Unix()

	// Generate salts for use with PBKDF2
	saltBuf := make([]byte, 16)
	if _, err := rand.Read(saltBuf); err != nil {
		return nil, err
	}
	salt1 := saltBuf

	// Use PBKDF2 to generate a session key based off the user's password
	session.Key = fmt.Sprintf("%x", pbkdf2.Key([]byte(password), salt1, 4096, 16, sha1.New))

	// Save session
	if err := session.Save(); err != nil {
		return nil, err
	}

	return session, nil
}
开发者ID:postfix,项目名称:wavepipe,代码行数:29,代码来源:session.go

示例7: add

func add(name string, password []byte) error {
	clipboard.WriteAll(string(password))

	p := Password{}
	p.Salt = randBytes(8)

	key = pbkdf2.Key(key, p.Salt, 4096, 32, sha1.New)

	session, err := aes.NewCipher(key)
	if err != nil {
		return err
	}
	password = pad(password)

	pass_ciphered := make([]byte, aes.BlockSize+len(password))
	iv := pass_ciphered[:aes.BlockSize]
	if _, err := io.ReadFull(rand.Reader, iv); err != nil {
		return err
	}

	mode := cipher.NewCBCEncrypter(session, iv)
	mode.CryptBlocks(pass_ciphered[aes.BlockSize:], password)
	p.Pass = pass_ciphered

	logins[name] = p
	return nil
}
开发者ID:jostillmanns,项目名称:passdb,代码行数:27,代码来源:passdb.go

示例8: hashPassword

// hashPassword hashes a password using the old method (PBKDF2 + SHA512).
//
// BUG(fss): this function is deprecated, it's here for the migration phase
// (whenever a user login with the old hash, the new hash will be generated).
func hashPassword(password string) string {
	err := loadConfig()
	if err != nil {
		panic(err)
	}
	salt := []byte(salt)
	return fmt.Sprintf("%x", pbkdf2.Key([]byte(password), salt, 4096, len(salt)*8, sha512.New))
}
开发者ID:kaiquewdev,项目名称:tsuru,代码行数:12,代码来源:user.go

示例9: H

//example hash function
func H(to_hash, salt []byte) big.Int {
	var x big.Int
	dk := pbkdf2.Key(to_hash, salt, 10000, 128, sha512.New)

	x.SetBytes(dk)

	return x
}
开发者ID:japorito,项目名称:libgosrp,代码行数:9,代码来源:srpcommon.go

示例10: CalcHash

func CalcHash(pass, salt []byte) *BitBuf {
	password := pass
	fmt.Printf("Calculating hash (iters: %v, size: %v)...\n", HashIts, HashLen)
	d := pbkdf2.Key(password, salt, HashIts, HashLen, sha256.New)
	//fmt.Println(len(d))

	hbuf := bbuf(d)
	return &BitBuf{src: hbuf.Read}
}
开发者ID:Carrotman42,项目名称:otp-pwman,代码行数:9,代码来源:crypt.go

示例11: Key

// Key derives a key from the password, salt, and cost parameters, returning
// a byte slice of length keyLen that can be used as cryptographic key.
//
// N is a CPU/memory cost parameter, which must be a power of two greater than 1.
// r and p must satisfy r * p < 2³⁰. If the parameters do not satisfy the
// limits, the function returns a nil byte slice and an error.
//
// For example, you can get a derived key for e.g. AES-256 (which needs a
// 32-byte key) by doing:
//
//      dk := scrypt.Key([]byte("some password"), salt, 16384, 8, 1, 32)
//
// The recommended parameters for interactive logins as of 2009 are N=16384,
// r=8, p=1. They should be increased as memory latency and CPU parallelism
// increases. Remember to get a good random salt.
func Key(password, salt []byte, N, r, p, keyLen int) ([]byte, error) {
	if N <= 1 || N&(N-1) != 0 {
		return nil, errors.New("scrypt: N must be > 1 and a power of 2")
	}
	if uint64(r)*uint64(p) >= 1<<30 || r > maxInt/128/p || r > maxInt/256 || N > maxInt/128/r {
		return nil, errors.New("scrypt: parameters are too large")
	}

	xy := make([]uint32, 64*r)
	v := make([]uint32, 32*N*r)
	b := pbkdf2.Key(password, salt, 1, p*128*r, sha256.New)

	for i := 0; i < p; i++ {
		smix(b[i*128*r:], r, N, v, xy)
	}

	return pbkdf2.Key(password, b, 1, keyLen, sha256.New), nil
}
开发者ID:carriercomm,项目名称:api-1,代码行数:33,代码来源:scrypt.go

示例12: createUserAES

// creates the master AES key for the user based on their password.
func createUserAES(password string) ([]byte, []byte) {
	salt := make([]byte, 10) // TODO: make 10 a constant variable
	_, err := rand.Read(salt)
	if err != nil {
		fmt.Println("ERROR:", err)
	}
	key := pbkdf2.Key([]byte(password), salt, 5000, 32, sha256.New) // TODO: make 5000 a const var

	return key, salt
}
开发者ID:postfix,项目名称:secureBox,代码行数:11,代码来源:encryption.go

示例13: deriveKey

// deriveKey returns the AES key, HMAC-SHA1 key, and key hash for
// the given password, salt combination.
func deriveKey(password string, salt []byte) (aesKey, hmacKey, keyHash []byte) {
	const keySize = 16
	key := pbkdf2.Key([]byte(password), salt, 4096, 2*keySize, sha1.New)
	aesKey = key[:keySize]
	hmacKey = key[keySize:]
	h := sha1.New()
	h.Write(key)
	keyHash = h.Sum(nil)[:4]
	return
}
开发者ID:0x7cc,项目名称:rsc,代码行数:12,代码来源:crypt.go

示例14: TestCreateUserHashesThePasswordUsingPBKDF2SHA512AndSalt

func (s *S) TestCreateUserHashesThePasswordUsingPBKDF2SHA512AndSalt(c *C) {
	salt := []byte(salt)
	expectedPassword := fmt.Sprintf("%x", pbkdf2.Key([]byte("123456"), salt, 4096, len(salt)*8, sha512.New))
	u := User{Email: "[email protected]", Password: "123456"}
	err := u.Create()
	c.Assert(err, IsNil)
	var result User
	collection := db.Session.Users()
	err = collection.Find(bson.M{"email": u.Email}).One(&result)
	c.Assert(err, IsNil)
	c.Assert(result.Password, Equals, expectedPassword)
}
开发者ID:JoeyFan,项目名称:tsuru,代码行数:12,代码来源:user_test.go

示例15: VerifyCredentials

func VerifyCredentials(username, password string) (user_id int64, authenticated bool) {
	row := db.QueryRow("SELECT id, pwhash, salt FROM users WHERE login = ? LIMIT 1", username)
	var db_hash []byte
	var salt []byte

	if err := row.Scan(&user_id, &db_hash, &salt); err != nil {
		log.Printf("VerifyCredentials: %v", err)
		return 0, false
	}

	password_hash := pbkdf2.Key([]byte(password), salt, PBKDF2_ROUNDS, PBKDF2_SIZE, sha256.New)

	return user_id, bytes.Equal(password_hash, db_hash)
}
开发者ID:Gehry,项目名称:activitylog,代码行数:14,代码来源:activities.go


注:本文中的code/google/com/p/go/crypto/pbkdf2.Key函数示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。