代碼地址:https://github.com/FakerGit/go-tools/tree/master/encrypt
對稱加密算法巷燥,即加密和解密使用一樣的密鑰的加解密算法。
分組密碼(block cipher),是每次只能處理特定長度的一塊(block)數(shù)據(jù)的一類加解密算法票髓。
目前常見的對稱加密算法DES锅纺、3DES掷空、AES都是屬于分組密碼。
背景
Golang沒有像PHP那樣提供一個現(xiàn)成的aes加密函數(shù)囤锉,不過標(biāo)準(zhǔn)庫里有crypto坦弟,利用里面的aes等可以自己封裝個加密函數(shù),不過需要理解下整個加解密的過程和原理
AES加密詳解
1. 參考文章golang 中AES加密詳解
2. 這里使用的是AES加密中的CBC模式官地,塊加密需要劃分成整數(shù)長度相等個消息塊不斷加密(串行)酿傍,分組長度是固定128位,但密鑰的長度可以使用128位驱入,192位或者256位(這里指的是bit)拧粪,即密鑰16,24沧侥,32長度對應(yīng)AES-128, AES-192, AES-256可霎。
3.初始向量要求隨機,但不需要保密宴杀。
代碼
自己研究代碼比較清晰癣朗,根據(jù)golang標(biāo)準(zhǔn)庫AES實例代碼,再參考網(wǎng)上的PKCS7填充旺罢,最后進(jìn)行base64的編碼(因為加密后有些字符不可見)旷余。最后Encrypt和Dncrypt兩個就是AES加解密(CBC模式,PKCS7填充)封裝后的函數(shù)扁达,密鑰位數(shù)限定16,24,32(要注意的是密鑰無論多少正卧,blocksize都是固定16)
package encrypt
import (
"bytes"
"crypto/aes"
"io"
"crypto/rand"
"crypto/cipher"
"encoding/base64"
)
/*CBC加密 按照golang標(biāo)準(zhǔn)庫的例子代碼
不過里面沒有填充的部分,所以補上
*/
//使用PKCS7進(jìn)行填充,IOS也是7
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分別對應(yīng)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 = PKCS7Padding(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:]
// 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 = PKCS7UnPadding(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
}
參考: