aes_utils.go 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. package auth
  2. import (
  3. "bytes"
  4. "crypto/aes"
  5. "crypto/cipher"
  6. "crypto/rand"
  7. "errors"
  8. "io"
  9. )
  10. // GenerateAESKey 生成 AES 密钥
  11. func GenerateAESKey() ([]byte, error) {
  12. key := make([]byte, 16)
  13. _, err := io.ReadFull(rand.Reader, key)
  14. if err != nil {
  15. return nil, err
  16. }
  17. return key, nil
  18. }
  19. // EncryptWithAES 使用 AES 加密数据
  20. func EncryptWithAES(key []byte, plaintext []byte) ([]byte, error) {
  21. block, err := aes.NewCipher(key)
  22. if err != nil {
  23. return nil, err
  24. }
  25. ciphertext := make([]byte, aes.BlockSize+len(plaintext))
  26. iv := ciphertext[:aes.BlockSize]
  27. if _, err := io.ReadFull(rand.Reader, iv); err != nil {
  28. return nil, err
  29. }
  30. stream := cipher.NewCFBEncrypter(block, iv)
  31. stream.XORKeyStream(ciphertext[aes.BlockSize:], plaintext)
  32. return ciphertext, nil
  33. }
  34. // DecryptWithAES 使用 AES 解密数据
  35. func DecryptWithAES(key []byte, ciphertext []byte) ([]byte, error) {
  36. block, err := aes.NewCipher(key)
  37. if err != nil {
  38. return nil, err
  39. }
  40. if len(ciphertext) < aes.BlockSize {
  41. return nil, errors.New("ciphertext too short")
  42. }
  43. iv := ciphertext[:aes.BlockSize]
  44. ciphertext = ciphertext[aes.BlockSize:]
  45. stream := cipher.NewCBCDecrypter(block, iv)
  46. stream.CryptBlocks(ciphertext, ciphertext)
  47. //去填充数据
  48. unpadded, err := unPad(ciphertext)
  49. if err != nil {
  50. return nil, err
  51. }
  52. return unpadded, nil
  53. }
  54. func unPad(buf []byte) ([]byte, error) {
  55. if len(buf) == 0 {
  56. return nil, errors.New("输入缓冲区为空")
  57. }
  58. // 获取最后一个字节作为填充长度
  59. padding := int(buf[len(buf)-1])
  60. // 检查填充是否有效
  61. if padding > len(buf) || padding == 0 {
  62. return nil, errors.New("无效的填充")
  63. }
  64. // 验证填充是否一致
  65. for i := len(buf) - padding; i < len(buf); i++ {
  66. if buf[i] != byte(padding) {
  67. return nil, errors.New("无效的填充")
  68. }
  69. }
  70. // 返回未填充的数据
  71. return buf[:len(buf)-padding], nil
  72. }
  73. func pad(buf []byte, blockSize int) []byte {
  74. padding := blockSize - (len(buf) % blockSize)
  75. padText := bytes.Repeat([]byte{byte(padding)}, padding)
  76. return append(buf, padText...)
  77. }