github.com/Bytom/bytom@v1.1.2-0.20210127130405-ae40204c0b09/blockchain/pseudohsm/keystore_passphrase_test.go (about) 1 package pseudohsm 2 3 import ( 4 "io/ioutil" 5 "os" 6 "testing" 7 8 "github.com/bytom/bytom/crypto/ed25519/chainkd" 9 "github.com/pborman/uuid" 10 ) 11 12 const ( 13 veryLightScryptN = 2 14 veryLightScryptP = 1 15 ) 16 17 // Tests that a json key file can be decrypted and encrypted in multiple rounds. 18 func TestKeyEncryptDecrypt(t *testing.T) { 19 keyjson, err := ioutil.ReadFile("testdata/bytom-very-light-scrypt.json") 20 if err != nil { 21 t.Fatal(err) 22 } 23 password := "bytomtest" 24 alias := "verylight" 25 // Do a few rounds of decryption and encryption 26 for i := 0; i < 3; i++ { 27 // Try a bad password first 28 29 if _, err := DecryptKey(keyjson, password+"bad"); err == nil { 30 t.Errorf("test %d: json key decrypted with bad password", i) 31 } 32 33 // Decrypt with the correct password 34 key, err := DecryptKey(keyjson, password) 35 if err != nil { 36 t.Errorf("test %d: json key failed to decrypt: %v", i, err) 37 } 38 if key.Alias != alias { 39 t.Errorf("test %d: key address mismatch: have %x, want %x", i, key.Alias, alias) 40 } 41 42 // Recrypt with a new password and start over 43 //password += "new data appended" 44 if _, err = EncryptKey(key, password, veryLightScryptN, veryLightScryptP); err != nil { 45 t.Errorf("test %d: failed to recrypt key %v", i, err) 46 } 47 } 48 } 49 50 func TestGenerateFile(t *testing.T) { 51 xprv, xpub, err := chainkd.NewXKeys(nil) 52 if err != nil { 53 t.Fatal(err) 54 } 55 id := uuid.NewRandom() 56 key := &XKey{ 57 ID: id, 58 KeyType: "bytom_kd", 59 XPub: xpub, 60 XPrv: xprv, 61 Alias: "verylight", 62 } 63 t.Log(key) 64 password := "bytomtest" 65 xkey, err := EncryptKey(key, password, veryLightScryptN, veryLightScryptP) 66 file := keyFileName(key.ID.String()) 67 writeKeyFile(file, xkey) 68 os.Remove(file) 69 }