在golang结构中转换字符串

Shreyans

我有AES加密机密的json文件。结构为:

{
    "username": "asdf123ASLdf3",
    "password": "elisjdvo4etQW"
}

以及持有这些价值观的结构

type Secrets struct {
    Username string `json:"username"`
    Password string `json:"password"`
}

将加密的json值加载到结构中很容易,但是我真正想要的是具有未加密值的结构。

因此,对于每个值,我想通过一个函数运行它:

aesDecrypt(key string, value string) string

我很高兴在第一次加载时完成此操作,或者将所有内容移到新的结构中。

我想避免重复json键或字段名称。

最好的方法是什么?

(还允许使用其他方法来管理Go中的加密机密)

以斯拉

一种选择是定义自定义JSON Unmarshaler。正如您提到的,另一个是将其复制到另一个结构。

  1. 实施Unmarshaler界面

    关键的见识是知道您可以json.Unmarshal通过实现Unmarshaler接口来覆盖行为在我们的案例中,这意味着定义一个函数func (ss *Secrets) UnmarshalJSON(bb []byte) error,当您尝试将任何JSON解组到时,将执行AES解密Secrets

    package main
    
    import "fmt"
    import "encoding/json"
    
    type Secrets struct {
        Username string `json:"username"`
        Password string `json:"password"`
    }
    
    func main() {
        jj := []byte(`{
            "username": "asdf123ASLdf3",
            "password": "elisjdvo4etQW"
        }`)
        var ss Secrets
        json.Unmarshal(jj, &ss)
        fmt.Println(ss)
    }
    
    func aesDecrypt(key, value string) string {
        return fmt.Sprintf("'%s' decrypted with key '%s'", value, key)
    }
    
    func (ss *Secrets) UnmarshalJSON(bb []byte) error {
        var objmap map[string]*string
        err := json.Unmarshal(bb, &objmap)
        ss.Username = aesDecrypt("my key", *objmap["password"])
        ss.Password = aesDecrypt("my key", *objmap["username"])
        return err
    }
    

    这将输出一个Secrets结构:

    {'elisjdvo4etQW' decrypted with key 'my key'
     'asdf123ASLdf3' decrypted with key 'my key'}
    

    在Go Playground上观看它。

  2. 复制到另一个结构

    您可以在Secrets每次需要解密JSON时简单地创建一个新结构。如果您这样做很多,或者不需要中间状态,这可能会很乏味。

    package main
    
    import "fmt"
    import "encoding/json"
    
    type Secrets struct {
        Username string `json:"username"`
        Password string `json:"password"`
    }
    
    func main() {
        jj := []byte(`{
            "username": "asdf123ASLdf3",
            "password": "elisjdvo4etQW"
        }`)
        var ss Secrets
        json.Unmarshal(jj, &ss)
        decoded := Secrets{
            aesDecrypt(ss.Username, "my key"),
            aesDecrypt(ss.Password, "my key")}
        fmt.Println(decoded)
    }
    
    func aesDecrypt(key, value string) string {
        return fmt.Sprintf("'%s' decrypted with key '%s'", value, key)
    }
    

    在Go Playground检查一下。

    与上面的输出相同:

    {'elisjdvo4etQW' decrypted with key 'my key'
     'asdf123ASLdf3' decrypted with key 'my key'}
    

显然,您将使用其他版本的aesDecrypt,只是我的假人。而且,与往常一样,您实际上应该在自己的代码中检查返回的错误。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章