kdf_scrypt.go raw

   1  package pkcs8
   2  
   3  import (
   4  	"encoding/asn1"
   5  
   6  	"golang.org/x/crypto/scrypt"
   7  )
   8  
   9  var (
  10  	oidScrypt = asn1.ObjectIdentifier{1, 3, 6, 1, 4, 1, 11591, 4, 11}
  11  )
  12  
  13  func init() {
  14  	RegisterKDF(oidScrypt, func() KDFParameters {
  15  		return new(scryptParams)
  16  	})
  17  }
  18  
  19  type scryptParams struct {
  20  	Salt                     []byte
  21  	CostParameter            int
  22  	BlockSize                int
  23  	ParallelizationParameter int
  24  }
  25  
  26  func (p scryptParams) DeriveKey(password []byte, size int) (key []byte, err error) {
  27  	return scrypt.Key(password, p.Salt, p.CostParameter, p.BlockSize,
  28  		p.ParallelizationParameter, size)
  29  }
  30  
  31  // ScryptOpts contains options for the scrypt key derivation function.
  32  type ScryptOpts struct {
  33  	SaltSize                 int
  34  	CostParameter            int
  35  	BlockSize                int
  36  	ParallelizationParameter int
  37  }
  38  
  39  func (p ScryptOpts) DeriveKey(password, salt []byte, size int) (
  40  	key []byte, params KDFParameters, err error) {
  41  
  42  	key, err = scrypt.Key(password, salt, p.CostParameter, p.BlockSize,
  43  		p.ParallelizationParameter, size)
  44  	if err != nil {
  45  		return nil, nil, err
  46  	}
  47  	params = scryptParams{
  48  		BlockSize:                p.BlockSize,
  49  		CostParameter:            p.CostParameter,
  50  		ParallelizationParameter: p.ParallelizationParameter,
  51  		Salt:                     salt,
  52  	}
  53  	return key, params, nil
  54  }
  55  
  56  func (p ScryptOpts) GetSaltSize() int {
  57  	return p.SaltSize
  58  }
  59  
  60  func (p ScryptOpts) OID() asn1.ObjectIdentifier {
  61  	return oidScrypt
  62  }
  63