GoLang AES GSM

以太坊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)
}
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀(guān)點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容