GO加密和解密数据

GO加密和解密数据

前面小节介绍了如何存储密码,但是有的时候,我们想把一些敏感数据加密后存储起来,
在将来的某个时候,随需将它们解密出来,此时我们应该在选用对称加密算法来满足我们
的需求。

**base64 **加解密

如果 Web 应用足够简单,数据的安全性没有那么严格的要求,那么可以采用一种比较简单
的加解密方法是 base64,这种方式实现起来比较简单,Go 语言的 base64 包已经很好的支
持了这个,请看下面的例子:

package main
import (
    "encoding/base64"
    "fmt"
)
func base64Encode(src []byte) []byte {
    return []byte(base64.StdEncoding.EncodeToString(src))
}
func base64Decode(src []byte) ([]byte, error) {
    return base64.StdEncoding.DecodeString(string(src))
}
func main() {
    // encode
    hello := "你好,世界! hello world"
    debyte := base64Encode([]byte(hello))
    fmt.Println(debyte)
    // decode
    enbyte, err := base64Decode(debyte)
    if err != nil {
        fmt.Println(err.Error())
    }
    if hello != string(enbyte) {
        fmt.Println("hello is not equal to enbyte")
    }
    fmt.Println(string(enbyte))
}

高级加解密

Go 语言的 crypto 里面支持对称加密的高级加解密包有:
• crypto/aes 包:AES(Advanced Encryption Standard),又称 Rijndael 加密法,是美
国联邦政府采用的一种区块加密标准。
• crypto/des 包:DEA(Data Encryption Algorithm),是一种对称加密算法,是目前使
用最广泛的密钥系统,特别是在保护金融数据的安全中。
因为这两种算法使用方法类似,所以在此,我们仅用 aes 包为例来讲解它们的使用,请看
下面的例子

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 name is Astaxie")
    //如果传入加密串的话,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)
}

上面通过调用函数 aes.NewCipher(参数 key 必须是 16、24 或者 32 位的[]byte,分别对应
AES-128, AES-192 或 AES-256 算法),返回了一个 cipher.Block 接口,这个接口实现了三个
功能:

type Block interface {
    // BlockSize returns the cipher's block size.
    BlockSize() int
    // Encrypt encrypts the first block in src into dst.
    // Dst and src may point at the same memory.
    Encrypt(dst, src []byte)
    // Decrypt decrypts the first block in src into dst.
    // Dst and src may point at the same memory.
    Decrypt(dst, src []byte)
}

这三个函数实现了加解密操作,详细的操作请看上面的例子。

在开发 Web 应用的时候可以根据需求采用不同的方式进
行加解密,一般的应用可以采用 base64 算法,更加高级的话可以采用 aes 或者 des 算法

  • 3
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
使用golang传输post数据进行加密解密可以通过以下步骤实现: 1. 创建一个公钥和私钥来进行加密解密数据。 2. 在发送数据之前,先将其加密。可以使用AES、DES或RSA算法来加密数据。 3. 将加密数据转换成Base64编码格式,然后发送到接收方。 4. 接收方接收到数据后,把Base64格式的数据解码。 5. 使用相同的密钥和算法来解密数据。 以下是一个使用AES算法进行加密解密数据的示例代码: ``` package main import ( "crypto/aes" "crypto/cipher" "encoding/base64" "fmt" ) func main() { key := "1234567890123456" plaintext := []byte("Hello World") // 加密 block, err := aes.NewCipher([]byte(key)) if err != nil { panic(err) } ciphertext := make([]byte, aes.BlockSize+len(plaintext)) iv := ciphertext[:aes.BlockSize] if _, err := rand.Read(iv); err != nil { panic(err) } mode := cipher.NewCBCEncrypter(block, iv) mode.CryptBlocks(ciphertext[aes.BlockSize:], plaintext) fmt.Printf("加密后的数据: %s\n", base64.StdEncoding.EncodeToString(ciphertext)) // 解密 ciphertext, err = base64.StdEncoding.DecodeString("LksRIe+I7LVEw/sCh3qyQQ==") if err != nil { panic(err) } iv = ciphertext[:aes.BlockSize] ciphertext = ciphertext[aes.BlockSize:] mode = cipher.NewCBCDecrypter(block, iv) mode.CryptBlocks(ciphertext, ciphertext) fmt.Printf("解密后的数据: %s\n", ciphertext) } ``` 注意,该示例代码中使用的AES算法是对称加密算法,因此加密解密使用的是相同的密钥。在实际应用中,需要使用公钥和私钥来实现非对称加密,以确保传输的数据更加安全。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值