Go 加密和解密數(shù)據(jù)

2022-05-13 17:39 更新

前面小節(jié)介紹了如何存儲密碼,但是有的時候,我們想把一些敏感數(shù)據(jù)加密后存儲起來,在將來的某個時候,隨需將它們解密出來,此時我們應該在選用對稱加密算法來滿足我們的需求。

base64加解密

如果Web應用足夠簡單,數(shù)據(jù)的安全性沒有那么嚴格的要求,那么可以采用一種比較簡單的加解密方法是base64,這種方式實現(xiàn)起來比較簡單,Go語言的base64包已經(jīng)很好的支持了這個,請看下面的例子:

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加密法,是美國聯(lián)邦政府采用的一種區(qū)塊加密標準。
  • crypto/des包:DES(Data Encryption Standard),是一種對稱加密標準,是目前使用最廣泛的密鑰系統(tǒng),特別是在保護金融數(shù)據(jù)的安全中。曾是美國聯(lián)邦政府的加密標準,但現(xiàn)已被AES所替代。

因為這兩種算法使用方法類似,所以在此,我們僅用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))

    // 創(chuàng)建加密算法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)
}

上面通過調用函數(shù)aes.NewCipher(參數(shù)key必須是16、24或者32位的[]byte,分別對應AES-128, AES-192或AES-256算法),返回了一個cipher.Block接口,這個接口實現(xiàn)了三個功能:

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)
}

這三個函數(shù)實現(xiàn)了加解密操作,詳細的操作請看上面的例子。

總結

這小節(jié)介紹了幾種加解密的算法,在開發(fā)Web應用的時候可以根據(jù)需求采用不同的方式進行加解密,一般的應用可以采用base64算法,更加高級的話可以采用aes或者des算法。

以上內容是否對您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號
微信公眾號

編程獅公眾號