Copy
type KeyDAO interface{// Write will use user password to encrypt data and save to file, the file name is user nameWrite(name, password string, store KeyInfo)error// Read will read encrypted data from file and decrypt with user passwordRead(name, password string)(KeyInfo,error)// Delete will delete user data and use user password to verify permissionsDelete(name, password string)error// Has returns whether the specified user name existsHas(name string)bool}type Crypto interface{Encrypt(data string, password string)(string,error)Decrypt(data string, password string)(string,error)}
Copy
// KeyInfo saves the basic information of the keytype KeyInfo struct{
Name string`json:"name"`
PubKey []byte`json:"pubkey"`
PrivKeyArmor string`json:"priv_key_armor"`
Algo string`json:"algo"`}
Go SDK 提供了 KeyDAO 的一个基于内存的简单实现,开发者不应在产品环境中直接使用,仅用于参考或测试目的。如下所示:
Copy
// Use memory as storage, use with caution in build environmenttype MemoryDAO struct{
store map[string]KeyInfo
Crypto
}funcNewMemory(crypto Crypto) MemoryDAO {if crypto ==nil{
crypto = AES{}}return MemoryDAO{
store:make(map[string]KeyInfo),
Crypto: crypto,}}func(m MemoryDAO)Write(name, password string, store KeyInfo)error{
m.store[name]= store
returnnil}func(m MemoryDAO)Read(name, password string)(KeyInfo,error){return m.store[name],nil}// ReadMetadata read a key information from the local storefunc(m MemoryDAO)ReadMetadata(name string)(store KeyInfo, err error){return m.store[name],nil}func(m MemoryDAO)Delete(name, password string)error{delete(m.store, name)returnnil}func(m MemoryDAO)Has(name string)bool{_, ok := m.store[name]return ok
}