W3Cschool
恭喜您成為首批注冊用戶
獲得88經(jīng)驗值獎勵
前面小節(jié)介紹了如何存儲密碼,但是有的時候,我們想把一些敏感數(shù)據(jù)加密后存儲起來,在將來的某個時候,隨需將它們解密出來,此時我們應該在選用對稱加密算法來滿足我們的需求。
如果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算法。
Copyright©2021 w3cschool編程獅|閩ICP備15016281號-3|閩公網(wǎng)安備35020302033924號
違法和不良信息舉報電話:173-0602-2364|舉報郵箱:jubao@eeedong.com
掃描二維碼
下載編程獅App
編程獅公眾號
聯(lián)系方式:
更多建議: