密码学-AES
AES算法
在AES算法中的秘鑰可以是16位,24位或者32位,在加密和解密的過程中要使用同一個秘鑰。
package mainimport ("bytes""crypto/aes""crypto/cipher""fmt" )func main() {key16 := []byte("1234567890123456")encryptcode := AesEncrypt([]byte("sanyang"), key16)fmt.Printf("%x\n", encryptcode)decryptcode := AesDeEncrypt(encryptcode, key16)fmt.Println(string(decryptcode)) }//補碼 func PKCS7Padding(ciphertext []byte, blocksize int) []byte {padding := blocksize - len(ciphertext)%blocksizepadtext := bytes.Repeat([]byte{byte(padding)}, padding)return append(ciphertext, padtext...) }//去碼 func PKCS7UnPadding(origData []byte) []byte {lenth := len(origData)unpadding := int(origData[lenth-1])return origData[:(lenth - unpadding)] }//加密 func AesEncrypt(origData []byte, key []byte) []byte {//分組秘鑰block, _ := aes.NewCipher(key)//獲得秘鑰塊長度blocksize := block.BlockSize()origData = PKCS7Padding(origData, blocksize)//設置加密方式blockMode := cipher.NewCBCEncrypter(block, key[:blocksize])//創建數組cryted := make([]byte, len(origData))//加密blockMode.CryptBlocks(cryted, origData)return cryted } //解密 func AesDeEncrypt(cryted, key []byte) []byte {//分組秘鑰block, _ := aes.NewCipher(key)//獲得秘鑰塊長度blocksize := block.BlockSize()//設置解密方式blockMode := cipher.NewCBCDecrypter(block, key[:blocksize])//創建數組origData := make([]byte, len(cryted))//解密blockMode.CryptBlocks(origData, cryted)origData = PKCS7UnPadding(origData)return origData }總結
- 上一篇: 密码学-3DES
- 下一篇: GO语言实现RSA 加密和解密的实现