當前位置: 首頁>>代碼示例>>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;未經允許,請勿轉載。