Golang加密系列之AES html
Golang加密系列之RSAjava
這裏咱們只討論使用aes加密算法,pkcs7padding,CBC模式模式進行加密。git
加密代碼:github
func Encrypt(plantText, key []byte) ([]byte, error) { block, err := aes.NewCipher(key) //選擇加密算法 if err != nil { return nil, err } plantText = PKCS7Padding(plantText, block.BlockSize()) blockModel := cipher.NewCBCEncrypter(block, key[:block.BlockSize()]) ciphertext := make([]byte, len(plantText)) blockModel.CryptBlocks(ciphertext, plantText) return ciphertext, nil } func PKCS7Padding(ciphertext []byte, blockSize int) []byte { padding := blockSize - len(ciphertext)%blockSize padtext := bytes.Repeat([]byte{byte(padding)}, padding) return append(ciphertext, padtext...) }
解密代碼:算法
func Decrypt(ciphertext, key []byte) ([]byte, error) { block, err := aes.NewCipher(key) //選擇加密算法 if err != nil { return nil, err } blockModel := cipher.NewCBCDecrypter(block, key[:block.BlockSize()]) plantText := make([]byte, len(ciphertext)) blockModel.CryptBlocks(plantText, ciphertext) plantText = PKCS7UnPadding(plantText, block.BlockSize()) return plantText, nil } func PKCS7UnPadding(plantText []byte, blockSize int) []byte { length := len(plantText) unpadding := int(plantText[length-1]) return plantText[:(length - unpadding)] }
OK,代碼上完,須要馬上能幹活的童鞋,直接command+c & command+v 就OK了,想折騰的童鞋接着往下看,咱們來討論下相關的概念性的東西,app
AES:高級加密標準(Advanced Encryption Standard),又稱Rijndael加密法,這個標準用來替代原先的DES。AES加密數據塊分組長度必須爲128bit(byte[16]),密鑰長度能夠是128bit(byte[16])、192bit(byte[24])、256bit(byte[32])中的任意一個。加密
塊:對明文進行加密的時候,先要將明文按照128bit進行劃分。spa
填充方式:由於明文的長度不必定老是128的整數倍,因此要進行補位,咱們這裏採用的是PKCS7填充方式,關於PKCS7,請戳這裏
.net
模式:這個,介紹起來有點複雜,請戳code
嗯,加密解密,作了個包放在github上了,歡迎提bug,