GoLang AES GSM

以太坊Whisper协议中,默认的对称加密使用的是AES-GCM加密算法。

AES是一种对称加密算法,它的相关概念在此不赘述。

GCM ( Galois/Counter Mode) 指的是该对称加密采用Counter模式,并带有GMAC消息认证码。

在详细介绍AES-GCM之前,我们先了解一些相关概念。
https://blog.csdn.net/T0mato_/article/details/53160772

1、准备

// AesKey 密钥
var AesKey string = "HQECux7Tt6UrGOUl"

// nonce 初始向量
nonce, _ := hex.DecodeString("000000010000010000000010")

2、辅助函数

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)
}
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • 起点 最近空闲时间都在研究Google开源项目Tink的源码,发现很多密码学相关概念似懂非懂,直接导致越看越蒙圈。...
    技术学徒阅读 1,262评论 0 3
  • TLS 的目的便是解决数据的一、Record 记录协议 (对称加解密) 二、HandShake 握手,挥手验证通...
    OOM_Killer阅读 5,217评论 0 0
  • 前言: 工作中常用模块,我们所说的加密方式,都是对二进制编码的格式进行加密的,就是人们常说的Bytes数据,所以当...
    Simon0903阅读 1,794评论 0 0
  • 我亲爱的姑娘,我现在在黑漆漆的京城,费劲心思找到一台电脑,急切的看你帮我做的小东西,心思沉沉,塞了好多好多东西,却...
    yuto_67yuan77阅读 413评论 0 2
  • 父亲如山 巍峨挺拔 母亲是灯 近处温暖 父之爱深沉 母之爱温柔
    江南如梦love阅读 1,495评论 0 1

友情链接更多精彩内容