之前寫了一個python監控系統,裏面用到了使用了AES對密碼進行加密,那golang去如何實現AES的加密解密呢,
說明:
1.這裏就以CBC模式來說明,使用了iv(偏遠向量),所以在對同一個明文使用同一個key 加密的時候,發現每次加密出來結果都不同,就不要大驚小怪了
2.這裏麪包含了2種補全方式:PKCS5Padding/PKCS7Padding,代碼裏都寫出了,至於選擇哪一個,根據自己的需要去決定
當然了,我這裏使用了PKCS5Padding,因爲之前的寫的python AES加密解密使用的就是PKCS5Padding,爲了能夠python和go互通,這裏就統一使用同一種方式。
3.這裏還有一個注意的地方就是密鑰key 長度必須爲16(AES-128)、24(AES-192)、或32(AES-256)
當然我使用的python 寫的腳本就沒有對key長度要求,至於go如何去實現不限制key的長度這裏先不說,等後面實現了再貼上。
package main
import (
"bytes"
"crypto/aes"
"crypto/cipher"
"crypto/rand"
"encoding/base64"
"fmt"
"io"
)
func main() {
var key = []byte("ABCDEFGHIJKLMNOp")
//每次得到的結果都不同,但是都可以解密
fmt.Println("oracle=", []byte("oracle"))
msg, ok := AesCBCEncrypt([]byte("oracle"),key)
if ok !=nil {
fmt.Println("encrypt is failed.")
}
fmt.Println("msg=", msg)
text, ok := AesCBCDncrypt(msg, key)
if ok !=nil {
fmt.Println("decrypt is failed.")
}
fmt.Println("text=", text)
fmt.Println("text=", string(text))
}
/*CBC加密 按照golang標準庫的例子代碼
不過裏面沒有填充的部分,所以補上
*/
//使用PKCS5進行填充
func PKCS5Padding(ciphertext []byte, blockSize int) []byte {
padding := blockSize - len(ciphertext) % blockSize
padtext := bytes.Repeat([]byte{byte(padding)}, padding)
return append(ciphertext, padtext...)
}
func PKCS5UnPadding(origData []byte) []byte {
length := len(origData)
unpadding := int(origData[length - 1])
return origData[:(length - unpadding)]
}
//使用PKCS7進行填充
func PKCS7Padding(ciphertext []byte, blockSize int) []byte {
padding := blockSize - len(ciphertext) % blockSize
padtext := bytes.Repeat([]byte{byte(padding)}, padding)
return append(ciphertext, padtext...)
}
func PKCS7UnPadding(origData []byte) []byte {
length := len(origData)
unpadding := int(origData[length-1])
return origData[:(length - unpadding)]
}
//aes加密,填充祕鑰key的16位,24,32分別對應AES-128, AES-192, or AES-256.
func AesCBCEncrypt(rawData,key []byte) ([]byte, error) {
block, err := aes.NewCipher(key)
if err != nil {
panic(err)
}
//填充原文
blockSize := block.BlockSize()
rawData = PKCS5Padding(rawData, blockSize)
//初始向量IV必須是唯一,但不需要保密
cipherText := make([]byte,blockSize+len(rawData))
//block大小 16
iv := cipherText[:blockSize]
if _, err := io.ReadFull(rand.Reader,iv); err != nil {
panic(err)
}
//block大小和初始向量大小一定要一致
mode := cipher.NewCBCEncrypter(block,iv)
mode.CryptBlocks(cipherText[blockSize:],rawData)
return cipherText, nil
}
func AesCBCDncrypt(encryptData, key []byte) ([]byte,error) {
block, err := aes.NewCipher(key)
if err != nil {
panic(err)
}
blockSize := block.BlockSize()
if len(encryptData) < blockSize {
panic("ciphertext too short")
}
iv := encryptData[:blockSize]
encryptData = encryptData[blockSize:]
fmt.Println("encryptData=", encryptData)
fmt.Println(len(encryptData)%blockSize)
// CBC mode always works in whole blocks.
if len(encryptData)%blockSize != 0 {
panic("ciphertext is not a multiple of the block size")
}
mode := cipher.NewCBCDecrypter(block, iv)
// CryptBlocks can work in-place if the two arguments are the same.
mode.CryptBlocks(encryptData, encryptData)
//解填充
encryptData = PKCS5UnPadding(encryptData)
return encryptData,nil
}
func Encrypt(rawData,key []byte) (string,error) {
data, err:= AesCBCEncrypt(rawData,key)
if err != nil {
return "",err
}
return base64.StdEncoding.EncodeToString(data),nil
}
func Dncrypt(rawData string,key []byte) (string,error) {
data,err := base64.StdEncoding.DecodeString(rawData)
if err != nil {
return "",err
}
dnData,err := AesCBCDncrypt(data,key)
if err != nil {
return "",err
}
return string(dnData),nil //
}