直接上代码:

    1. package main
    2. import (
    3. "fmt"
    4. "crypto/aes"
    5. "crypto/cipher"
    6. "encoding/base64"
    7. "bytes"
    8. )
    9. const (
    10. key = "X2bJDtJtM7IAmbpB"
    11. iv = "9338010611913253"
    12. )
    13. func main() {
    14. str := "我勒个去"
    15. es, _ := AesEncrypt(str, []byte(key))
    16. fmt.Println(es)
    17. ds, _ := AesDecrypt(es, []byte(key))
    18. fmt.Println(string(ds))
    19. }
    20. func AesEncrypt(encodeStr string, key []byte) (string, error) {
    21. encodeBytes := []byte(encodeStr)
    22. //根据key 生成密文
    23. block, err := aes.NewCipher(key)
    24. if err != nil {
    25. return "", err
    26. }
    27. blockSize := block.BlockSize()
    28. encodeBytes = PKCS5Padding(encodeBytes, blockSize)
    29. blockMode := cipher.NewCBCEncrypter(block, []byte(iv))
    30. crypted := make([]byte, len(encodeBytes))
    31. blockMode.CryptBlocks(crypted, encodeBytes)
    32. return base64.StdEncoding.EncodeToString(crypted), nil
    33. }
    34. func PKCS5Padding(ciphertext []byte, blockSize int) []byte {
    35. padding := blockSize - len(ciphertext)%blockSize
    36. //填充
    37. padtext := bytes.Repeat([]byte{byte(padding)}, padding)
    38. return append(ciphertext, padtext...)
    39. }
    40. func AesDecrypt(decodeStr string, key []byte) ([]byte, error) {
    41. //先解密base64
    42. decodeBytes, err := base64.StdEncoding.DecodeString(decodeStr)
    43. if err != nil {
    44. return nil, err
    45. }
    46. block, err := aes.NewCipher(key)
    47. if err != nil {
    48. return nil, err
    49. }
    50. blockMode := cipher.NewCBCDecrypter(block, []byte(iv))
    51. origData := make([]byte, len(decodeBytes))
    52. blockMode.CryptBlocks(origData, decodeBytes)
    53. origData = PKCS5UnPadding(origData)
    54. return origData, nil
    55. }
    56. func PKCS5UnPadding(origData []byte) []byte {
    57. length := len(origData)
    58. unpadding := int(origData[length-1])
    59. return origData[:(length - unpadding)]
    60. }