golang crypto aes 加密,解密示例

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

内容简介:加密:解密:

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 加密,解密示例》,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对 码农网 的支持!

查看所有标签

猜你喜欢:

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

Python神经网络编程

Python神经网络编程

[英]塔里克·拉希德(Tariq Rashid) / 林赐 / 人民邮电出版社 / 2018-4 / 69.00元

神经网络是一种模拟人脑的神经网络,以期能够实现类人工智能的机器学习 技术。 本书揭示神经网络背后的概念,并介绍如何通过Python实现神经网络。全书 分为3章和两个附录。第1章介绍了神经网络中所用到的数学思想。第2章介绍使 用Python实现神经网络,识别手写数字,并测试神经网络的性能。第3章带领读 者进一步了解简单的神经网络,观察已受训练的神经网络内部,尝试进一步改......一起来看看 《Python神经网络编程》 这本书的介绍吧!

随机密码生成器
随机密码生成器

多种字符组合密码

XML、JSON 在线转换
XML、JSON 在线转换

在线XML、JSON转换工具

正则表达式在线测试
正则表达式在线测试

正则表达式在线测试