| 1 |
package s2k |
| 2 |
|
| 3 |
// Cache stores keys derived with s2k functions from one passphrase |
| 4 |
// to avoid recomputation if multiple items are encrypted with |
| 5 |
// the same parameters. |
| 6 |
type Cache map[Params][]byte |
| 7 |
|
| 8 |
// GetOrComputeDerivedKey tries to retrieve the key |
| 9 |
// for the given s2k parameters from the cache. |
| 10 |
// If there is no hit, it derives the key with the s2k function from the passphrase, |
| 11 |
// updates the cache, and returns the key. |
| 12 |
func (c *Cache) GetOrComputeDerivedKey(passphrase []byte, params *Params, expectedKeySize int) ([]byte, error) { |
| 13 |
key, found := (*c)[*params] |
| 14 |
if !found || len(key) != expectedKeySize { |
| 15 |
var err error |
| 16 |
derivedKey := make([]byte, expectedKeySize) |
| 17 |
s2k, err := params.Function() |
| 18 |
if err != nil { |
| 19 |
return nil, err |
| 20 |
} |
| 21 |
s2k(derivedKey, passphrase) |
| 22 |
(*c)[*params] = key |
| 23 |
return derivedKey, nil |
| 24 |
} |
| 25 |
return key, nil |
| 26 |
} |