Golang(13)Security and Secret

本文介绍了使用Golang进行数据加密的基本方法,包括BASE64编码解码实现及AES加密算法的应用。通过具体代码示例展示了如何对字符串进行加密和解密。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Golang(13)Security and Secret

1. Simple BASE64
package main

import (
     "encoding/base64"
     "fmt"
)

func base64Encode(src string) string {
     return base64.StdEncoding.EncodeToString([]byte(src))
}

func base64Decode(src string) (string, error) {
     c, err := base64.StdEncoding.DecodeString(src)
     return string(c), err
}

func main() {
     // encode
     hello := "hello sillycat, you will do auth again."
     debyte := base64Encode(hello)
     fmt.Println(debyte)
     // decode
     enbyte, err := base64Decode(debyte)
     if err != nil {
          fmt.Println(err.Error())
     }

     if hello != enbyte {
          fmt.Println("hello is not equal to enbyte")
     }

     fmt.Println(enbyte)
}

2. AES and DES
AES(Advanced Encryption Standard), DES(Data Encryption Standard)

Go AES is just using a module

package main

import (
     "crypto/aes"
     "crypto/cipher"
     "fmt"
     "os"
)

var commonIV = []byte{0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f}

func main() {
     //需要去加密的字符串
     plaintext := []byte("My English name is Carl")
     //如果传入加密串的话,plaint就是传入的字符串
     if len(os.Args) > 1 {
          plaintext = []byte(os.Args[1])
     }

     //aes的加密字符串
     key_text := "astaxie12798akljzmknm.ahkjkljl;k"
     if len(os.Args) > 2 {
          key_text = os.Args[2]
     }

     fmt.Println(len(key_text))

     // 创建加密算法aes
     c, err := aes.NewCipher([]byte(key_text))
     if err != nil {
          fmt.Printf("Error: NewCipher(%d bytes) = %s", len(key_text), err)
          os.Exit(-1)
     }

     //加密字符串
     cfb := cipher.NewCFBEncrypter(c, commonIV)
     ciphertext := make([]byte, len(plaintext))
     cfb.XORKeyStream(ciphertext, plaintext)
     fmt.Printf("%s=>%x\n", plaintext, ciphertext)

     // 解密字符串
     cfbdec := cipher.NewCFBDecrypter(c, commonIV)
     plaintextCopy := make([]byte, len(plaintext))
     cfbdec.XORKeyStream(plaintextCopy, ciphertext)
     fmt.Printf("%x=>%s\n", ciphertext, plaintextCopy)
}

A tool for string HEX
http://www.string-functions.com/hex-string.aspx


References:
https://github.com/astaxie/build-web-application-with-golang/blob/master/ebook/09.6.md

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值