golang crypto aes 加密,解密示例

栏目: Go · 发布时间: 7年前

内容简介:加密:解密:

https://cyberspy.io/articles/crypto101/

加密:

package main

import (
        "crypto/aes"
        "crypto/cipher"
        "crypto/rand"
        "fmt"
        "io"
)

func main() {
        // The key argument should be the AES key, either 16 or 32 bytes
        // to select AES-128 or AES-256.
        key := []byte("0123456789ABCDEF")
        plaintext := []byte("Apple")

        block, err := aes.NewCipher(key)
        if err != nil {
                panic(err.Error())
        }

        nonce := make([]byte, 12)
        if false {
                if _, err := io.ReadFull(rand.Reader, nonce); err != nil {
                        panic(err.Error())
                }
        }

        fmt.Printf("nonce: %x\n", nonce)

        aesgcm, err := cipher.NewGCM(block)
        if err != nil {
                panic(err.Error())
        }

        ciphertext := aesgcm.Seal(nil, nonce, plaintext, nil)
        fmt.Printf("cipher:%x\n", ciphertext)
}

解密:

package main

import (
        "crypto/aes"
        "crypto/cipher"
        "fmt"
    "encoding/hex"
)


func main (){

    key := []byte("0123456789ABCDEF")

        ciphertext, _ := hex.DecodeString("08f24c28f0fc9aef5812a35ce66235bc2488d6c29b")  //加密生成的结果

        nonce, _ := hex.DecodeString("000000000000000000000000") //加密用的nonce

        block, err := aes.NewCipher(key)
        if err != nil {
                panic(err.Error())
        }

        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())
        }
    fmt.Println(string(plaintext))
}

跟踪 tls(https) 代码里面, server 和client 走的 就是 aes GCM。

nonce 应该就是随机数(random)


以上所述就是小编给大家介绍的《golang crypto aes 加密,解密示例》,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对 码农网 的支持!

查看所有标签

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

基于内容图像检索技术

基于内容图像检索技术

周明全 / 清华大学 / 2007-12 / 28.00元

《基于内容图像检索技术》从理论方法研究与实现技术角度,总结归纳了基于内容图像检索(CBIR)技术的研究与进展,并融入了作者多年来的相关研究与应用成果,系统地介绍了CBIR的主要概念、基本原理、典型方法、实用范例以及新动向。《基于内容图像检索技术》共有12章分为五部分:第一部分是概述,分析了CBIR的体系结构、技术现状和发展趋势;第一部分讨论图像特征提取,给出图像低层特征(颜色、形状、纹理、空间关系......一起来看看 《基于内容图像检索技术》 这本书的介绍吧!

URL 编码/解码
URL 编码/解码

URL 编码/解码

UNIX 时间戳转换
UNIX 时间戳转换

UNIX 时间戳转换

HEX CMYK 转换工具
HEX CMYK 转换工具

HEX CMYK 互转工具