| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768 |
- package main
- import (
- "bytes"
- "crypto/aes"
- "crypto/cipher"
- "encoding/base64"
- "fmt"
- )
- func main() {
- text := "18851177173"
- AesKey := []byte("#avata-console$!") //对称秘钥长度必须是16的倍数
- fmt.Printf("明文: %s\n秘钥: %s\n", text, string(AesKey))
- encrypted, err := AesEncrypt([]byte(text), AesKey)
- if err != nil {
- panic(err)
- }
- fmt.Printf("加密后: %s\n", base64.StdEncoding.EncodeToString(encrypted))
- origin, err := AesDecrypt(encrypted, AesKey)
- if err != nil {
- panic(err)
- }
- fmt.Printf("解密后明文: %s\n", string(origin))
- }
- 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加密,CBC
- func AesEncrypt(origData, key []byte) ([]byte, error) {
- block, err := aes.NewCipher(key)
- if err != nil {
- return nil, err
- }
- blockSize := block.BlockSize()
- origData = PKCS7Padding(origData, blockSize)
- blockMode := cipher.NewCBCEncrypter(block, key[:blockSize])
- crypted := make([]byte, len(origData))
- blockMode.CryptBlocks(crypted, origData)
- return crypted, nil
- }
- //AES解密
- func AesDecrypt(crypted, key []byte) ([]byte, error) {
- block, err := aes.NewCipher(key)
- if err != nil {
- return nil, err
- }
- blockSize := block.BlockSize()
- blockMode := cipher.NewCBCDecrypter(block, key[:blockSize])
- origData := make([]byte, len(crypted))
- blockMode.CryptBlocks(origData, crypted)
- origData = PKCS7UnPadding(origData)
- return origData, nil
- }
|