github.com/chain5j/chain5j-pkg@v1.0.7/crypto/scrypt/key.go (about) 1 // Package scrypt 2 // 3 // @author: xwc1125 4 package scrypt 5 6 import ( 7 "encoding/hex" 8 "encoding/json" 9 10 "github.com/pborman/uuid" 11 ) 12 13 const ( 14 version = 3 15 ) 16 17 type Key struct { 18 Id uuid.UUID // Version 4 "random" for unique id not derived from key data 19 // we only store privkey as pubkey/address can be derived from it 20 // privkey in this struct is always in plaintext 21 PrivateKey []byte 22 } 23 24 type keyStore interface { 25 // Loads and decrypts the key from disk. 26 GetKey(addr []byte, filename string, auth string) (*Key, error) 27 // Writes and encrypts the key. 28 StoreKey(filename string, k *Key, auth string) error 29 // Joins filename with the key directory unless it is already absolute. 30 JoinPath(filename string) string 31 } 32 33 type plainKeyJSON struct { 34 PrivateKey string `json:"privatekey"` 35 Id string `json:"id"` 36 Version int `json:"version"` 37 } 38 39 type encryptedKeyJSONV3 struct { 40 Crypto CryptoJSON `json:"crypto"` 41 Id string `json:"id"` 42 Version int `json:"version"` 43 } 44 45 type encryptedKeyJSONV1 struct { 46 Address string `json:"address"` 47 Crypto CryptoJSON `json:"crypto"` 48 Id string `json:"id"` 49 Version string `json:"version"` 50 } 51 52 type CryptoJSON struct { 53 Cipher string `json:"cipher"` 54 CipherText string `json:"ciphertext"` 55 CipherParams cipherparamsJSON `json:"cipherparams"` 56 KDF string `json:"kdf"` 57 KDFParams map[string]interface{} `json:"kdfparams"` 58 MAC string `json:"mac"` 59 } 60 61 type cipherparamsJSON struct { 62 IV string `json:"iv"` 63 } 64 65 func (k *Key) MarshalJSON() (j []byte, err error) { 66 jStruct := plainKeyJSON{ 67 hex.EncodeToString(k.PrivateKey), 68 k.Id.String(), 69 version, 70 } 71 j, err = json.Marshal(jStruct) 72 return j, err 73 } 74 75 func (k *Key) UnmarshalJSON(j []byte) (err error) { 76 keyJSON := new(plainKeyJSON) 77 err = json.Unmarshal(j, &keyJSON) 78 if err != nil { 79 return err 80 } 81 82 u := new(uuid.UUID) 83 *u = uuid.Parse(keyJSON.Id) 84 k.Id = *u 85 privkey, err := hex.DecodeString(keyJSON.PrivateKey) 86 if err != nil { 87 return err 88 } 89 90 k.PrivateKey = privkey 91 92 return nil 93 }