Created
May 10, 2021 04:54
-
-
Save boseji/7a9972221ce2a07a6c0717d0bed6ac34 to your computer and use it in GitHub Desktop.
PBKDF2 Key Derivation
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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