Address pull request comments

* Simplify scrypt constants with const block
* Add key store constructors and make their types private
* Simplify key store and file namings to be less Java Enterprise™
* Change test error logging to use t.Error(err)
* Reduce number of naked returns (just like my ex-gf)
* Simplify file reading path code
This commit is contained in:
Gustav Simonsson 2015-01-07 16:06:26 +01:00
parent 945798f913
commit a1c2749380
4 changed files with 91 additions and 84 deletions

View File

@ -49,7 +49,7 @@ type Key struct {
PrivateKey *ecdsa.PrivateKey PrivateKey *ecdsa.PrivateKey
} }
type KeyPlainJSON struct { type PlainKeyJSON struct {
Id string Id string
Flags string Flags string
PrivateKey string PrivateKey string
@ -61,7 +61,7 @@ type CipherJSON struct {
CipherText string CipherText string
} }
type KeyProtectedJSON struct { type EncryptedKeyJSON struct {
Id string Id string
Flags string Flags string
Crypto CipherJSON Crypto CipherJSON
@ -73,44 +73,44 @@ func (k *Key) Address() []byte {
} }
func (k *Key) MarshalJSON() (j []byte, err error) { func (k *Key) MarshalJSON() (j []byte, err error) {
stringStruct := KeyPlainJSON{ stringStruct := PlainKeyJSON{
k.Id.String(), k.Id.String(),
hex.EncodeToString(k.Flags[:]), hex.EncodeToString(k.Flags[:]),
hex.EncodeToString(FromECDSA(k.PrivateKey)), hex.EncodeToString(FromECDSA(k.PrivateKey)),
} }
j, _ = json.Marshal(stringStruct) j, err = json.Marshal(stringStruct)
return return j, err
} }
func (k *Key) UnmarshalJSON(j []byte) (err error) { func (k *Key) UnmarshalJSON(j []byte) (err error) {
keyJSON := new(KeyPlainJSON) keyJSON := new(PlainKeyJSON)
err = json.Unmarshal(j, &keyJSON) err = json.Unmarshal(j, &keyJSON)
if err != nil { if err != nil {
return return err
} }
u := new(uuid.UUID) u := new(uuid.UUID)
*u = uuid.Parse(keyJSON.Id) *u = uuid.Parse(keyJSON.Id)
if *u == nil { if *u == nil {
err = errors.New("UUID parsing failed") err = errors.New("UUID parsing failed")
return return err
} }
k.Id = u k.Id = u
flagsBytes, err := hex.DecodeString(keyJSON.Flags) flagsBytes, err := hex.DecodeString(keyJSON.Flags)
if err != nil { if err != nil {
return return err
} }
PrivateKeyBytes, err := hex.DecodeString(keyJSON.PrivateKey) PrivateKeyBytes, err := hex.DecodeString(keyJSON.PrivateKey)
if err != nil { if err != nil {
return return err
} }
copy(k.Flags[:], flagsBytes[0:4]) copy(k.Flags[:], flagsBytes[0:4])
k.PrivateKey = ToECDSA(PrivateKeyBytes) k.PrivateKey = ToECDSA(PrivateKeyBytes)
return return err
} }
func NewKey() *Key { func NewKey() *Key {

View File

@ -76,35 +76,46 @@ import (
"path" "path"
) )
const scryptN int = 262144 // 2^18 const (
const scryptr int = 8 // 2^18 / 8 / 1 uses 256MB memory and approx 1s CPU time on a modern CPU.
const scryptp int = 1 scryptN = 1 << 18
const scryptdkLen int = 32 scryptr = 8
scryptp = 1
scryptdkLen = 32
)
type KeyStorePassphrase struct { type keyStorePassphrase struct {
keysDirPath string keysDirPath string
} }
func (ks KeyStorePassphrase) GenerateNewKey(auth string) (key *Key, err error) { func NewKeyStorePassphrase(path string) KeyStore2 {
key, err = GenerateNewKeyDefault(ks, auth) ks := new(keyStorePassphrase)
return ks.keysDirPath = path
return ks
} }
func (ks KeyStorePassphrase) GetKey(keyId *uuid.UUID, auth string) (key *Key, err error) { func (ks keyStorePassphrase) GenerateNewKey(auth string) (key *Key, err error) {
return GenerateNewKeyDefault(ks, auth)
}
func (ks keyStorePassphrase) GetKey(keyId *uuid.UUID, auth string) (key *Key, err error) {
keyBytes, flags, err := DecryptKey(ks, keyId, auth) keyBytes, flags, err := DecryptKey(ks, keyId, auth)
if err != nil {
return nil, err
}
key = new(Key) key = new(Key)
key.Id = keyId key.Id = keyId
copy(key.Flags[:], flags[0:4]) copy(key.Flags[:], flags[0:4])
key.PrivateKey = ToECDSA(keyBytes) key.PrivateKey = ToECDSA(keyBytes)
return return key, err
} }
func (ks KeyStorePassphrase) StoreKey(key *Key, auth string) (err error) { func (ks keyStorePassphrase) StoreKey(key *Key, auth string) (err error) {
authArray := []byte(auth) authArray := []byte(auth)
salt := GetEntropyCSPRNG(32) salt := GetEntropyCSPRNG(32)
derivedKey, err := scrypt.Key(authArray, salt, scryptN, scryptr, scryptp, scryptdkLen) derivedKey, err := scrypt.Key(authArray, salt, scryptN, scryptr, scryptp, scryptdkLen)
if err != nil { if err != nil {
return return err
} }
keyBytes := FromECDSA(key.PrivateKey) keyBytes := FromECDSA(key.PrivateKey)
@ -113,7 +124,7 @@ func (ks KeyStorePassphrase) StoreKey(key *Key, auth string) (err error) {
AES256Block, err := aes.NewCipher(derivedKey) AES256Block, err := aes.NewCipher(derivedKey)
if err != nil { if err != nil {
return return err
} }
iv := GetEntropyCSPRNG(aes.BlockSize) // 16 iv := GetEntropyCSPRNG(aes.BlockSize) // 16
@ -126,70 +137,68 @@ func (ks KeyStorePassphrase) StoreKey(key *Key, auth string) (err error) {
hex.EncodeToString(iv), hex.EncodeToString(iv),
hex.EncodeToString(cipherText), hex.EncodeToString(cipherText),
} }
keyStruct := KeyProtectedJSON{ keyStruct := EncryptedKeyJSON{
key.Id.String(), key.Id.String(),
hex.EncodeToString(key.Flags[:]), hex.EncodeToString(key.Flags[:]),
cipherStruct, cipherStruct,
} }
keyJSON, err := json.Marshal(keyStruct) keyJSON, err := json.Marshal(keyStruct)
if err != nil { if err != nil {
return return err
} }
err = WriteKeyFile(key.Id.String(), ks.keysDirPath, keyJSON) return WriteKeyFile(key.Id.String(), ks.keysDirPath, keyJSON)
return
} }
func (ks KeyStorePassphrase) DeleteKey(keyId *uuid.UUID, auth string) (err error) { func (ks keyStorePassphrase) DeleteKey(keyId *uuid.UUID, auth string) (err error) {
// only delete if correct passphrase is given // only delete if correct passphrase is given
_, _, err = DecryptKey(ks, keyId, auth) _, _, err = DecryptKey(ks, keyId, auth)
if err != nil { if err != nil {
return return err
} }
keyDirPath := path.Join(ks.keysDirPath, keyId.String()) keyDirPath := path.Join(ks.keysDirPath, keyId.String())
err = os.RemoveAll(keyDirPath) return os.RemoveAll(keyDirPath)
return
} }
func DecryptKey(ks KeyStorePassphrase, keyId *uuid.UUID, auth string) (keyBytes []byte, flags []byte, err error) { func DecryptKey(ks keyStorePassphrase, keyId *uuid.UUID, auth string) (keyBytes []byte, flags []byte, err error) {
fileContent, err := GetKeyFile(ks.keysDirPath, keyId) fileContent, err := GetKeyFile(ks.keysDirPath, keyId)
if err != nil { if err != nil {
return return nil, nil, err
} }
keyProtected := new(KeyProtectedJSON) keyProtected := new(EncryptedKeyJSON)
err = json.Unmarshal(fileContent, keyProtected) err = json.Unmarshal(fileContent, keyProtected)
flags, err = hex.DecodeString(keyProtected.Flags) flags, err = hex.DecodeString(keyProtected.Flags)
if err != nil { if err != nil {
return return nil, nil, err
} }
salt, err := hex.DecodeString(keyProtected.Crypto.Salt) salt, err := hex.DecodeString(keyProtected.Crypto.Salt)
if err != nil { if err != nil {
return return nil, nil, err
} }
iv, err := hex.DecodeString(keyProtected.Crypto.IV) iv, err := hex.DecodeString(keyProtected.Crypto.IV)
if err != nil { if err != nil {
return return nil, nil, err
} }
cipherText, err := hex.DecodeString(keyProtected.Crypto.CipherText) cipherText, err := hex.DecodeString(keyProtected.Crypto.CipherText)
if err != nil { if err != nil {
return return nil, nil, err
} }
authArray := []byte(auth) authArray := []byte(auth)
derivedKey, err := scrypt.Key(authArray, salt, scryptN, scryptr, scryptp, scryptdkLen) derivedKey, err := scrypt.Key(authArray, salt, scryptN, scryptr, scryptp, scryptdkLen)
if err != nil { if err != nil {
return return nil, nil, err
} }
AES256Block, err := aes.NewCipher(derivedKey) AES256Block, err := aes.NewCipher(derivedKey)
if err != nil { if err != nil {
return return nil, nil, err
} }
AES256CBCDecrypter := cipher.NewCBCDecrypter(AES256Block, iv) AES256CBCDecrypter := cipher.NewCBCDecrypter(AES256Block, iv)
@ -199,14 +208,14 @@ func DecryptKey(ks KeyStorePassphrase, keyId *uuid.UUID, auth string) (keyBytes
plainText := PKCS7Unpad(paddedPlainText) plainText := PKCS7Unpad(paddedPlainText)
if plainText == nil { if plainText == nil {
err = errors.New("Decryption failed: PKCS7Unpad failed after decryption") err = errors.New("Decryption failed: PKCS7Unpad failed after decryption")
return return nil, nil, err
} }
keyBytes = plainText[:len(plainText)-32] keyBytes = plainText[:len(plainText)-32]
keyBytesHash := plainText[len(plainText)-32:] keyBytesHash := plainText[len(plainText)-32:]
if !bytes.Equal(Sha3(keyBytes), keyBytesHash) { if !bytes.Equal(Sha3(keyBytes), keyBytesHash) {
err = errors.New("Decryption failed: checksum mismatch") err = errors.New("Decryption failed: checksum mismatch")
return return nil, nil, err
} }
return keyBytes, flags, err return keyBytes, flags, err
} }

View File

@ -41,7 +41,7 @@ type KeyStore2 interface {
DeleteKey(*uuid.UUID, string) error // delete key by id and auth string DeleteKey(*uuid.UUID, string) error // delete key by id and auth string
} }
type KeyStorePlaintext struct { type keyStorePlain struct {
keysDirPath string keysDirPath string
} }
@ -51,9 +51,14 @@ func DefaultDataDir() string {
return path.Join(usr.HomeDir, ".ethereum") return path.Join(usr.HomeDir, ".ethereum")
} }
func (ks KeyStorePlaintext) GenerateNewKey(auth string) (key *Key, err error) { func NewKeyStorePlain(path string) KeyStore2 {
key, err = GenerateNewKeyDefault(ks, auth) ks := new(keyStorePlain)
return ks.keysDirPath = path
return ks
}
func (ks keyStorePlain) GenerateNewKey(auth string) (key *Key, err error) {
return GenerateNewKeyDefault(ks, auth)
} }
func GenerateNewKeyDefault(ks KeyStore2, auth string) (key *Key, err error) { func GenerateNewKeyDefault(ks KeyStore2, auth string) (key *Key, err error) {
@ -64,50 +69,46 @@ func GenerateNewKeyDefault(ks KeyStore2, auth string) (key *Key, err error) {
}() }()
key = NewKey() key = NewKey()
err = ks.StoreKey(key, auth) err = ks.StoreKey(key, auth)
return return key, err
} }
func (ks KeyStorePlaintext) GetKey(keyId *uuid.UUID, auth string) (key *Key, err error) { func (ks keyStorePlain) GetKey(keyId *uuid.UUID, auth string) (key *Key, err error) {
fileContent, err := GetKeyFile(ks.keysDirPath, keyId) fileContent, err := GetKeyFile(ks.keysDirPath, keyId)
if err != nil { if err != nil {
return return nil, err
} }
key = new(Key) key = new(Key)
err = json.Unmarshal(fileContent, key) err = json.Unmarshal(fileContent, key)
return return key, err
} }
func (ks KeyStorePlaintext) StoreKey(key *Key, auth string) (err error) { func (ks keyStorePlain) StoreKey(key *Key, auth string) (err error) {
keyJSON, err := json.Marshal(key) keyJSON, err := json.Marshal(key)
if err != nil { if err != nil {
return return err
} }
err = WriteKeyFile(key.Id.String(), ks.keysDirPath, keyJSON) err = WriteKeyFile(key.Id.String(), ks.keysDirPath, keyJSON)
return return err
} }
func (ks KeyStorePlaintext) DeleteKey(keyId *uuid.UUID, auth string) (err error) { func (ks keyStorePlain) DeleteKey(keyId *uuid.UUID, auth string) (err error) {
keyDirPath := path.Join(ks.keysDirPath, keyId.String()) keyDirPath := path.Join(ks.keysDirPath, keyId.String())
err = os.RemoveAll(keyDirPath) err = os.RemoveAll(keyDirPath)
return return err
} }
func GetKeyFile(keysDirPath string, keyId *uuid.UUID) (fileContent []byte, err error) { func GetKeyFile(keysDirPath string, keyId *uuid.UUID) (fileContent []byte, err error) {
idString := keyId.String() id := keyId.String()
keyDirPath := path.Join(keysDirPath, idString) return ioutil.ReadFile(path.Join(keysDirPath, id, id))
keyFilePath := path.Join(keyDirPath, idString)
fileContent, err = ioutil.ReadFile(keyFilePath)
return
} }
func WriteKeyFile(idString string, keysDirPath string, content []byte) (err error) { func WriteKeyFile(id string, keysDirPath string, content []byte) (err error) {
keyDirPath := path.Join(keysDirPath, idString) keyDirPath := path.Join(keysDirPath, id)
keyFilePath := path.Join(keyDirPath, idString) keyFilePath := path.Join(keyDirPath, id)
err = os.MkdirAll(keyDirPath, 0700) // read, write and dir search for user err = os.MkdirAll(keyDirPath, 0700) // read, write and dir search for user
if err != nil { if err != nil {
return return err
} }
err = ioutil.WriteFile(keyFilePath, content, 0600) // read, write for user return ioutil.WriteFile(keyFilePath, content, 0600) // read, write for user
return
} }

View File

@ -6,20 +6,19 @@ import (
"testing" "testing"
) )
func TestKeyStorePlaintext(t *testing.T) { func TestKeyStorePlain(t *testing.T) {
ks := new(KeyStorePlaintext) ks := NewKeyStorePlain(DefaultDataDir())
ks.keysDirPath = DefaultDataDir()
pass := "" // not used but required by API pass := "" // not used but required by API
k1, err := ks.GenerateNewKey(pass) k1, err := ks.GenerateNewKey(pass)
if err != nil { if err != nil {
fmt.Println(err.Error()) t.Error(err)
t.FailNow() t.FailNow()
} }
k2 := new(Key) k2 := new(Key)
k2, err = ks.GetKey(k1.Id, pass) k2, err = ks.GetKey(k1.Id, pass)
if err != nil { if err != nil {
fmt.Println(err.Error()) t.Error(err)
t.FailNow() t.FailNow()
} }
@ -40,25 +39,24 @@ func TestKeyStorePlaintext(t *testing.T) {
err = ks.DeleteKey(k2.Id, pass) err = ks.DeleteKey(k2.Id, pass)
if err != nil { if err != nil {
fmt.Println(err.Error()) t.Error(err)
t.FailNow() t.FailNow()
} }
} }
func TestKeyStorePassphrase(t *testing.T) { func TestKeyStorePassphrase(t *testing.T) {
ks := new(KeyStorePassphrase) ks := NewKeyStorePassphrase(DefaultDataDir())
ks.keysDirPath = DefaultDataDir()
pass := "foo" pass := "foo"
k1, err := ks.GenerateNewKey(pass) k1, err := ks.GenerateNewKey(pass)
if err != nil { if err != nil {
fmt.Println(err.Error()) t.Error(err)
t.FailNow() t.FailNow()
} }
k2 := new(Key) k2 := new(Key)
k2, err = ks.GetKey(k1.Id, pass) k2, err = ks.GetKey(k1.Id, pass)
if err != nil { if err != nil {
fmt.Println(err.Error()) t.Error(err)
t.FailNow() t.FailNow()
} }
@ -79,36 +77,35 @@ func TestKeyStorePassphrase(t *testing.T) {
err = ks.DeleteKey(k2.Id, pass) // also to clean up created files err = ks.DeleteKey(k2.Id, pass) // also to clean up created files
if err != nil { if err != nil {
fmt.Println(err.Error()) t.Error(err)
t.FailNow() t.FailNow()
} }
} }
func TestKeyStorePassphraseDecryptionFail(t *testing.T) { func TestKeyStorePassphraseDecryptionFail(t *testing.T) {
ks := new(KeyStorePassphrase) ks := NewKeyStorePassphrase(DefaultDataDir())
ks.keysDirPath = DefaultDataDir()
pass := "foo" pass := "foo"
k1, err := ks.GenerateNewKey(pass) k1, err := ks.GenerateNewKey(pass)
if err != nil { if err != nil {
fmt.Println(err.Error()) t.Error(err)
t.FailNow() t.FailNow()
} }
_, err = ks.GetKey(k1.Id, "bar") // wrong passphrase _, err = ks.GetKey(k1.Id, "bar") // wrong passphrase
// fmt.Println(err.Error()) // t.Error(err)
if err == nil { if err == nil {
t.FailNow() t.FailNow()
} }
err = ks.DeleteKey(k1.Id, "bar") // wrong passphrase err = ks.DeleteKey(k1.Id, "bar") // wrong passphrase
if err == nil { if err == nil {
fmt.Println(err.Error()) t.Error(err)
t.FailNow() t.FailNow()
} }
err = ks.DeleteKey(k1.Id, pass) // to clean up err = ks.DeleteKey(k1.Id, pass) // to clean up
if err != nil { if err != nil {
fmt.Println(err.Error()) t.Error(err)
t.FailNow() t.FailNow()
} }
} }