以太坊Whisper協(xié)議中,默認(rèn)的對(duì)稱(chēng)加密使用的是AES-GCM加密算法。
AES是一種對(duì)稱(chēng)加密算法,它的相關(guān)概念在此不贅述。
GCM ( Galois/Counter Mode) 指的是該對(duì)稱(chēng)加密采用Counter模式,并帶有GMAC消息認(rèn)證碼。
在詳細(xì)介紹AES-GCM之前,我們先了解一些相關(guān)概念。
https://blog.csdn.net/T0mato_/article/details/53160772
1、準(zhǔn)備
// AesKey 密鑰
var AesKey string = "HQECux7Tt6UrGOUl"
// nonce 初始向量
nonce, _ := hex.DecodeString("000000010000010000000010")
2、輔助函數(shù)
func getKeys() ([]byte) {
return []byte(AesKey)
}
func getBlock() cipher.Block {
key := getKeys()
block, err := aes.NewCipher(key)
if err != nil {
panic(err.Error())
}
return block
}
func getNonce() []byte {
nonce, err := hex.DecodeString(Gsm_IV)
if err != nil {
panic(err.Error())
}
return nonce
}
3、encrypt
func encrypt(data string) (string) {
block := getBlock()
nonce := getNonce()
aesgcm, err := cipher.NewGCM(block)
if err != nil {
panic(err.Error())
}
cipherText := aesgcm.Seal(nil, nonce, []byte(data), nil)
return fmt.Sprintf("%x", cipherText)
}
4、decrypt
func decrypt(data string) string {
cipherText, _ := hex.DecodeString(data)
nonce := getNonce()
block := getBlock()
aesgcm, err := cipher.NewGCM(block)
if err != nil {
panic(err.Error())
}
plaintext, err := aesgcm.Open(nil, nonce, cipherText, nil)
if err != nil {
panic(err.Error())
}
return fmt.Sprintf("%x", plaintext)
}