另客网go项目公用的代码库

aes.go 1.5KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. package encrypt
  2. import (
  3. "bytes"
  4. "crypto/aes"
  5. "crypto/cipher"
  6. )
  7. // AES是对称加密算法
  8. // AES-128。key长度:16, 24, 32 bytes 对应 AES-128, AES-192, AES-256
  9. // 记住每次加密解密前都要设置iv.
  10. // 该包默认的密匙
  11. const defaultAesKey = "b8ca9aa66def05ff3f24919274bb4a66"
  12. func Encrypt(plaintext []byte) ([]byte, error) {
  13. key := []byte(defaultAesKey)
  14. block, err := aes.NewCipher(key)
  15. if err != nil {
  16. return nil, err
  17. }
  18. blockSize := block.BlockSize()
  19. plaintext = PKCS5Padding(plaintext, blockSize)
  20. blockMode := cipher.NewCBCEncrypter(block, key[:blockSize])
  21. ciphertext := make([]byte, len(plaintext))
  22. blockMode.CryptBlocks(ciphertext, plaintext)
  23. return ciphertext, nil
  24. }
  25. func Decrypt(ciphertext []byte) ([]byte, error) {
  26. key := []byte(defaultAesKey)
  27. block, err := aes.NewCipher(key)
  28. if err != nil {
  29. return nil, err
  30. }
  31. blockSize := block.BlockSize()
  32. blockMode := cipher.NewCBCDecrypter(block, key[:blockSize])
  33. plaintext := make([]byte, len(ciphertext))
  34. blockMode.CryptBlocks(plaintext, ciphertext)
  35. plaintext = PKCS5UnPadding(plaintext)
  36. return plaintext, nil
  37. }
  38. func PKCS5Padding(plaintext []byte, blockSize int) []byte {
  39. padding := blockSize - len(plaintext)%blockSize
  40. padtext := bytes.Repeat([]byte{byte(padding)}, padding)
  41. return append(plaintext, padtext...)
  42. }
  43. func PKCS5UnPadding(plaintext []byte) []byte {
  44. length := len(plaintext)
  45. // 去掉最后一个字节 unpadding 次
  46. unpadding := int(plaintext[length-1])
  47. return plaintext[:(length - unpadding)]
  48. }