Go 語言怎麼使用對稱加密?

大家好,我是 frank。
歡迎大家關注「Golang 語言開發棧」公衆號。

01 介紹

在項目開發中,我們經常會遇到需要使用對稱密鑰加密的場景,比如客戶端調用接口時,參數包含手機號、身份證號或銀行卡號等。

對稱密鑰加密是一種加密方式,其中只有一個密鑰用於加密和解密數據。通過對稱加密進行通信的實體必須共享該密鑰,以便可以在解密過程中使用它。這種加密方法與非對稱加密不同,非對稱加密使用一對密鑰(一個公鑰和一個私鑰)來加密和解密數據。

02 AES 算法

常見的對稱密鑰加密算法有 AES (Advanced Encryption Standard),DES (Data Encryption Standard) 等,它們都屬於分組密碼。

因爲基於目前計算機的處理能力,可以很快破解 DES 算法,所以 DES 目前已經很少被使用。

AES 是目前最常用的對稱密鑰加密算法,最初稱爲 Rijndael。AES 密碼每個分組大小是 128 bits,但是它具有三種密鑰長度,分別是 AES-128、AES-192 和 AES-256。需要注意的是,在 Golang 標準庫提供的接口中,僅支持 AES-128(16 byte),實際上 AES-128 的加密強度已經足夠安全。

本文我們主要介紹 Golang 中怎麼使用 AES 算法的對稱密鑰加密。

03 實踐

AES 算法的分組模式包含 ECB、CBC、CFB、OFB 和 CTR,其中 ECB 和 CBC 使用比較多,雖然 ECB 比 CBC 簡單,效率高,但是它的密文有規律,比較容易破解,所以,更推薦大家使用 CBC,本文我們主要介紹使用最多的 CBC 分組模式。

需要注意的是,ECB 和 CBC 分組模式的最後一個分組,需要填充滿 16 byte,關於填充模式,限於篇幅,本文不展開介紹,但會提供填充數據和取消填充數據的代碼。

Golang 實現 AES 對稱加密算法主要分爲以下幾個步驟:

加密步驟:

  1. 創建一個新的加密塊。

  2. 獲取加密塊的大小。

  3. 填充數據。

  4. 初始化向量。

  5. 指定加密塊的分組模式。

  6. 進行加密多個塊。

示例代碼:

func AESCbcEncrypt(secretKey, src string) string {
 key := []byte(secretKey)
 if len(key) > 16 {
  key = key[:16]
 }
 plaintext := []byte(src)
 block, err := aes.NewCipher(key)
 if err != nil {
  panic(err)
 }
 blockSize := block.BlockSize()
 plaintext = Padding(plaintext, blockSize)
 if len(plaintext)%aes.BlockSize != 0 {
  panic("plaintext is not a multiple of the block size")
 }
 ciphertext := make([]byte, aes.BlockSize+len(plaintext))
 iv := ciphertext[:aes.BlockSize]
 if _, err := io.ReadFull(rand.Reader, iv); err != nil {
  panic(err)
 }
 mode := cipher.NewCBCEncrypter(block, iv)
 mode.CryptBlocks(ciphertext[aes.BlockSize:], plaintext)
 return base64.StdEncoding.EncodeToString(ciphertext)
}

解密步驟:

  1. 創建一個新的加密塊。

  2. 初始化向量。

  3. 指定解密塊的分組模式。

  4. 進行解密多個塊。

  5. 取消填充數據。

示例代碼:

func AESCbcDecrypt(secretKey, src string) string {
 key := []byte(secretKey)
 ciphertext, _ := base64.StdEncoding.DecodeString(src)
 block, err := aes.NewCipher(key)
 if err != nil {
  panic(err)
 }
 if len(ciphertext) < aes.BlockSize {
  panic("ciphertext too short")
 }
 iv := ciphertext[:aes.BlockSize]
 ciphertext = ciphertext[aes.BlockSize:]
 if len(ciphertext)%aes.BlockSize != 0 {
  panic("ciphertext is not a multiple of the block size")
 }
 mode := cipher.NewCBCDecrypter(block, iv)
 mode.CryptBlocks(ciphertext, ciphertext)
 ciphertext = UnPadding(ciphertext)
 return string(ciphertext)
}

填充示例代碼:

func Padding(plainText []byte, blockSize int) []byte {
 padding := blockSize - len(plainText)%blockSize
 char := []byte{byte(padding)}
 newPlain := bytes.Repeat(char, padding)
 return append(plainText, newPlain...)
}

取消填充示例代碼:

func UnPadding(plainText []byte) []byte {
 length := len(plainText)
 lastChar := plainText[length-1]
 padding := int(lastChar)
 return plainText[:length-padding]
}

需要注意的是,初始化向量(IV)是隨機的,細心的讀者朋友們可能已經發現,使用隨機 IV ,同一份明文,每次加密得到的密文也都不同。但是,加密和解密使用的 IV 必須相同。

04 總結

本文我們介紹了對稱密鑰加密的概念,並簡單介紹了 AES 算法,最終我們還提供了 Golang 怎麼使用 AES 算法的 CBC 分組模式實現對稱密鑰加密的示例代碼,感興趣的讀者朋友,可以自行編寫其它分組模式的代碼。

本文重點是介紹怎麼使用 Go 語言實現對稱密鑰加密,代碼佔用篇幅比較多,關於 AES 算法的分組模式和填充模式的詳細介紹,感興趣的讀者朋友們可以閱讀參考資料給出的鏈接地址。

參考資料:

  1. https://en.wikipedia.org/wiki/Symmetric-key_algorithm

  2. https://pkg.go.dev/crypto/aes@go1.18.3#NewCipher

  3. https://pkg.go.dev/crypto/cipher#NewCBCEncrypter

  4. https://pkg.go.dev/crypto/cipher#NewCBCDecrypter

  5. https://datatracker.ietf.org/doc/html/rfc5246#section-6.2.3.2

  6. https://en.wikipedia.org/wiki/Padding_(cryptography)

  7. https://www.cryptomathic.com/news-events/blog/the-use-of-encryption-modes-with-symmetric-block-ciphers

本文由 Readfog 進行 AMP 轉碼,版權歸原作者所有。
來源https://mp.weixin.qq.com/s/rKPyAHfjR_UPsU_Fi9CQdQ