main.go 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. package main
  2. import (
  3. "bytes"
  4. "crypto/aes"
  5. "crypto/cipher"
  6. "encoding/base64"
  7. "fmt"
  8. )
  9. func main() {
  10. text := "18851177173"
  11. AesKey := []byte("#avata-console$!") //对称秘钥长度必须是16的倍数
  12. fmt.Printf("明文: %s\n秘钥: %s\n", text, string(AesKey))
  13. encrypted, err := AesEncrypt([]byte(text), AesKey)
  14. if err != nil {
  15. panic(err)
  16. }
  17. fmt.Printf("加密后: %s\n", base64.StdEncoding.EncodeToString(encrypted))
  18. origin, err := AesDecrypt(encrypted, AesKey)
  19. if err != nil {
  20. panic(err)
  21. }
  22. fmt.Printf("解密后明文: %s\n", string(origin))
  23. }
  24. func PKCS7Padding(ciphertext []byte, blockSize int) []byte {
  25. padding := blockSize - len(ciphertext)%blockSize
  26. padtext := bytes.Repeat([]byte{byte(padding)}, padding)
  27. return append(ciphertext, padtext...)
  28. }
  29. func PKCS7UnPadding(origData []byte) []byte {
  30. length := len(origData)
  31. unpadding := int(origData[length-1])
  32. return origData[:(length - unpadding)]
  33. }
  34. //AES加密,CBC
  35. func AesEncrypt(origData, key []byte) ([]byte, error) {
  36. block, err := aes.NewCipher(key)
  37. if err != nil {
  38. return nil, err
  39. }
  40. blockSize := block.BlockSize()
  41. origData = PKCS7Padding(origData, blockSize)
  42. blockMode := cipher.NewCBCEncrypter(block, key[:blockSize])
  43. crypted := make([]byte, len(origData))
  44. blockMode.CryptBlocks(crypted, origData)
  45. return crypted, nil
  46. }
  47. //AES解密
  48. func AesDecrypt(crypted, key []byte) ([]byte, error) {
  49. block, err := aes.NewCipher(key)
  50. if err != nil {
  51. return nil, err
  52. }
  53. blockSize := block.BlockSize()
  54. blockMode := cipher.NewCBCDecrypter(block, key[:blockSize])
  55. origData := make([]byte, len(crypted))
  56. blockMode.CryptBlocks(origData, crypted)
  57. origData = PKCS7UnPadding(origData)
  58. return origData, nil
  59. }