Skip to content

Instantly share code, notes, and snippets.

@boseji
Created May 10, 2021 04:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save boseji/7a9972221ce2a07a6c0717d0bed6ac34 to your computer and use it in GitHub Desktop.
Save boseji/7a9972221ce2a07a6c0717d0bed6ac34 to your computer and use it in GitHub Desktop.
PBKDF2 Key Derivation
// Copyright 2021 Abhijit Bose. All rights reserved.
// Use of this source code is governed by a Apache 2.0 license
package main
import (
"bytes"
"crypto/rand"
"crypto/sha256"
"encoding/hex"
"fmt"
"io"
"golang.org/x/crypto/pbkdf2"
)
func main() {
key := []byte("Test Password") // Source Key
rounds := 4096 // Number of Rounds to be used for PBKDF2
// Create the Salt
salt := make([]byte, 8)
if _, err := io.ReadFull(rand.Reader, salt); err != nil {
panic(err)
}
// Perform Key Derivation
dk := pbkdf2.Key(key, salt, rounds, sha256.Size, sha256.New)
fmt.Println("Derived Key:", hex.EncodeToString(dk))
fmt.Println("Salt:", hex.EncodeToString(salt))
fmt.Println("Rounds:", uint64(rounds))
// Compress the Data Into a Single Slice
//
// Format: Rounds[8byte] | salt[8bytes] | derivedKey[dk 32bytes SHA2-256]
//
// buf := make([]byte, 8+len(dk)+len(salt))
//
result := bytes.NewBuffer(nil) // Use Bytes Buffer for Easier assembly
// Add the Rounds
resRounds := uint64(rounds)
for i := 0; i < 8; i++ {
result.WriteByte(byte(resRounds & uint64(0x0FF)))
resRounds >>= 8
}
// Add the Other Elements
result.Write(salt)
result.Write(dk)
fmt.Println("Compressed Result: \n", hex.EncodeToString(result.Bytes()))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment