網站首頁 編程語言 正文
前言
安全總是相對的,對于敏感數據最好要有一定保護措施,尤其是在線數據,通過加密可轉換信息為編碼,從而防止非法獲取。對開發者來說,加密本質是保護應用程序數據,假設我們以明文存儲用戶密碼,可能會導致信息泄露。使用密文在一定程度上可避免信息落入他人之手,本文介紹Golang的對稱加密算法實現。
前置知識
在正式學習加密解密之前,首先看看如何生成隨機數,以及為什么要隨機數。
生成隨機數
編程中生成隨機數或字符串非常重要,它是加密的基礎工作。如果沒有隨機生成數,加密可能會失去作用,讓加密數據可預測。為了生成隨機數,Go提供了math/rand包及其他工具,下面通過實例說明:
package main import ( "fmt" "math/rand" ) func main() { fmt.Println(rand.Intn(100)) }
程序很簡單,生成[0,100)之間的整數,但多次運行程序,會發現每次結果都一樣。這是因為程序按照算法設定,默認隨機種子為1,因此每次結果相同。我們通過設置不同隨機種子修復錯誤:
package main import ( "fmt" "math/rand" "time" ) func main() { rand.Seed(time.Now().UnixNano()) fmt.Println(rand.Intn(100)) }
這樣每次運行時隨機種子不同,結果自然就不同。
生成隨機字符串
為了在Go中生成隨機字符串,我們使用Base64編碼和外部包,這是一種更實用和安全的方式。
首先我們看Base64編碼:
package main import ( "encoding/base64" "fmt" ) func main() { StringToEncode := "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789" Encoding := base64.StdEncoding.EncodeToString([]byte(StringToEncode)) fmt.Println(Encoding) }
通過使用Base64編碼,可以對字符串進行編碼或解碼,上面示例對StringToEncode字符值進行base64編碼,讀者可以運行程序查看結果。
為了每次運行返回結果不同,可以使用第三方包randstr
,它采用比使用Seed方法更好更快的方法,安裝命令為:
go get -u github.com/thanhpk/randstr
下面示例生成隨機長度為20字符串,代碼如下:
package main import( "github.com/thanhpk/randstr" "fmt" ) func main() { MyString := randstr.String(20) fmt.Println(MyString) }
運行多次,每次結果都不同。
加密和解密
了解了生成隨機字符和數字,下面進入正題,加密和解密。要了解安全,需要先了解這些模塊:crypto/aes, crypto/cipher, encoding/base64
。
加密
加密是隱藏數據的方法,是的別有用心的人拿到數據也沒有用。這里主要使用crypto/aes(Advanced Encryption Standard)包提供的功能。
package main import ( "crypto/aes" "crypto/cipher" "encoding/base64" "fmt" ) var bytes = []byte{35, 46, 57, 24, 85, 35, 24, 74, 87, 35, 88, 98, 66, 32, 14, 05} // 生成環境應該通過配置文件獲取 const MySecret string = "abc&1*~#^2^#s0^=)^^7%b34" func Encode(b []byte) string { return base64.StdEncoding.EncodeToString(b) } // 加密方法可以加密任何類型文本 func Encrypt(text, MySecret string) (string, error) { block, err := aes.NewCipher([]byte(MySecret)) if err != nil { return "", err } plainText := []byte(text) cfb := cipher.NewCFBEncrypter(block, bytes) cipherText := make([]byte, len(plainText)) cfb.XORKeyStream(cipherText, plainText) return Encode(cipherText), nil } func main() { StringToEncrypt := "Encrypting this string" // To encrypt the StringToEncrypt encText, err := Encrypt(StringToEncrypt, MySecret) if err != nil { fmt.Println("error encrypting your classified text: ", err) } fmt.Println(encText) }
crypto/cipher
包中NewCFBEncrypter
方法使用16字節隨機值作為參數,注意這里長度必須為16,因為AES默認block長度為16,這兩者長度要一致,不同長度對應不同算法,對應關系如下:
16, 24, or 32, AES-128, AES-192, or AES-256.
cipher.go的源碼定義如下:
// The AES block size in bytes. const BlockSize = 16 // A cipher is an instance of AES encryption using a particular key. type aesCipher struct { enc []uint32 dec []uint32 } type KeySizeError int func (k KeySizeError) Error() string { return "crypto/aes: invalid key size " + strconv.Itoa(int(k)) } // NewCipher creates and returns a new cipher.Block. // The key argument should be the AES key, // either 16, 24, or 32 bytes to select // AES-128, AES-192, or AES-256. ...
再看下NewCFBEncrypter方法源碼,注釋寫的很清楚兩者長度需相同。
// NewCFBEncrypter returns a Stream which encrypts with cipher feedback mode, // using the given Block. The iv must be the same length as the Block's block // size. func NewCFBEncrypter(block Block, iv []byte) Stream { return newCFB(block, iv, false) }
Encrypt函數帶兩個參數,待加密的明文和加密的密鑰。MySecret常量是加密方法所需的密鑰,最后通過Encode函數返回Base64格式的密文。運行程序,輸出結果即為密文,是StringToEncrypt變量值加密的結果。
Li5E8RFcV/EPZY/neyCXQYjrfa/atA==
解密
成功加密字符串后,需要能夠正確解密,從密文還原為明文。典型的場景是用戶數據是加密后存入數據庫中,當用戶再次訪問時需要能夠正確解密。也就說我們需要把前節中加密的密文正確還原為明文,首先需要使用解碼函數,該函數會在解密方法中使用:
func Decode(s string) []byte { data, err := base64.StdEncoding.DecodeString(s) if err != nil { panic(err) } return data }
Decode函數有一個參數,對于Base64編碼進行解碼,解密方法代碼如下:
// 解密方法把密文正確轉為明文 func Decrypt(text, MySecret string) (string, error) { block, err := aes.NewCipher([]byte(MySecret)) if err != nil { return "", err } cipherText := Decode(text) cfb := cipher.NewCFBDecrypter(block, bytes) plainText := make([]byte, len(cipherText)) cfb.XORKeyStream(plainText, cipherText) return string(plainText), nil }
解密方法包括兩個參數:text是密文,MySeret是密鑰。在main函數中可以對前面密文進行解密并輸出明文:
decText, err := Decrypt("Li5E8RFcV/EPZY/neyCXQYjrfa/atA==", MySecret) if err != nil { fmt.Println("error decrypting your encrypted text: ", err) } fmt.Println(decText)
最后給出完整代碼和注釋:
package main import ( "crypto/aes" "crypto/cipher" "encoding/base64" "fmt" ) // 16位隨機字符串 var bytes = []byte{35, 46, 57, 24, 85, 35, 24, 74, 87, 35, 88, 98, 66, 32, 14, 05} // 密鑰,實際應用中應該從環境變量或文件中獲取 const MySecret string = "abc&1*~#^2^#s0^=)^^7%b34" // Base64編碼和解碼方法 func Encode(b []byte) string { return base64.StdEncoding.EncodeToString(b) } func Decode(s string) []byte { data, err := base64.StdEncoding.DecodeString(s) if err != nil { panic(err) } return data } // 加密方法 func Encrypt(text, MySecret string) (string, error) { block, err := aes.NewCipher([]byte(MySecret)) if err != nil { return "", err } plainText := []byte(text) cfb := cipher.NewCFBEncrypter(block, bytes) cipherText := make([]byte, len(plainText)) cfb.XORKeyStream(cipherText, plainText) return Encode(cipherText), nil } // 解密方法 func Decrypt(text, MySecret string) (string, error) { block, err := aes.NewCipher([]byte(MySecret)) if err != nil { return "", err } cipherText := Decode(text) cfb := cipher.NewCFBDecrypter(block, bytes) plainText := make([]byte, len(cipherText)) cfb.XORKeyStream(plainText, cipherText) return string(plainText), nil } func main() { StringToEncrypt := "Encrypting this string" // 對StringToEncrypt變量值進行加密 encText, err := Encrypt(StringToEncrypt, MySecret) if err != nil { fmt.Println("error encrypting your classified text: ", err) } fmt.Println(encText) // 對密文進行解密 decText, err := Decrypt("Li5E8RFcV/EPZY/neyCXQYjrfa/atA==", MySecret) if err != nil { fmt.Println("error decrypting your encrypted text: ", err) } fmt.Println(decText) }
結合前面的內容,當然可以每次動態獲取16位隨機數,加密完成后和密文連接一起返回:cipherText = append(cipherText, bytes...)
,最后解密時從密文中先截取隨機數再解密,從而讓每次加密生成的密文都不一樣。
總結
本文介紹Go如何實現對稱加密,包括生成隨機字符,Base64編碼和解碼,實現AES加密和解密,注意使用了內置的crypto/aes, crypto/cipher, encoding/base64
模塊。
原文鏈接:https://blog.csdn.net/neweastsun/article/details/128961333
- 上一篇:沒有了
- 下一篇:沒有了
相關推薦
- 2023-05-29 linux?rename?批量修改文件名的操作方法_linux shell
- 2022-11-02 Kotlin中@JvmOverloads注解作用示例介紹_Android
- 2022-03-08 C#中BackgroundWorker類用法總結_C#教程
- 2022-06-22 C語言詳解如何實現堆及堆的結構與接口_C 語言
- 2022-07-19 macOS Docker 內存 CPU 占用過高,監控到 com.Docker.hyperkit 進
- 2022-10-03 python中pandas操作apply返回多列的實現_python
- 2022-06-02 關于Python使用turtle庫畫任意圖的問題_python
- 2023-05-16 Python入門之布爾值詳解_python
- 欄目分類
-
- 最近更新
-
- window11 系統安裝 yarn
- 超詳細win安裝深度學習環境2025年最新版(
- Linux 中運行的top命令 怎么退出?
- MySQL 中decimal 的用法? 存儲小
- get 、set 、toString 方法的使
- @Resource和 @Autowired注解
- Java基礎操作-- 運算符,流程控制 Flo
- 1. Int 和Integer 的區別,Jav
- spring @retryable不生效的一種
- Spring Security之認證信息的處理
- Spring Security之認證過濾器
- Spring Security概述快速入門
- Spring Security之配置體系
- 【SpringBoot】SpringCache
- Spring Security之基于方法配置權
- redisson分布式鎖中waittime的設
- maven:解決release錯誤:Artif
- restTemplate使用總結
- Spring Security之安全異常處理
- MybatisPlus優雅實現加密?
- Spring ioc容器與Bean的生命周期。
- 【探索SpringCloud】服務發現-Nac
- Spring Security之基于HttpR
- Redis 底層數據結構-簡單動態字符串(SD
- arthas操作spring被代理目標對象命令
- Spring中的單例模式應用詳解
- 聊聊消息隊列,發送消息的4種方式
- bootspring第三方資源配置管理
- GIT同步修改后的遠程分支