蛋蛋星球-客户端
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

utils.go 2.3 KiB

1 maand geleden
1 maand geleden
1 maand geleden
1 maand geleden
1 maand geleden
1 maand geleden
1 maand geleden
1 maand geleden
1 maand geleden
1 maand geleden
1 maand geleden
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. package aes
  2. import (
  3. "bytes"
  4. "crypto/aes"
  5. "encoding/base64"
  6. "fmt"
  7. )
  8. // 加密
  9. func AesEncryptByECB(key, data string) string {
  10. // 判断key长度
  11. keyLenMap := map[int]struct{}{16: {}, 24: {}, 32: {}}
  12. if _, ok := keyLenMap[len(key)]; !ok {
  13. panic("key长度必须是 16、24、32 其中一个")
  14. }
  15. // 密钥和待加密数据转成[]byte
  16. originByte := []byte(data)
  17. keyByte := []byte(key)
  18. // 创建密码组,长度只能是16、24、32 字节
  19. block, _ := aes.NewCipher(keyByte)
  20. // 获取密钥长度
  21. blockSize := block.BlockSize()
  22. // 补码
  23. originByte = PKCS7Padding(originByte, blockSize)
  24. // 创建保存加密变量
  25. encryptResult := make([]byte, len(originByte))
  26. // CEB是把整个明文分成若干段相同的小段,然后对每一小段进行加密
  27. for bs, be := 0, blockSize; bs < len(originByte); bs, be = bs+blockSize, be+blockSize {
  28. block.Encrypt(encryptResult[bs:be], originByte[bs:be])
  29. }
  30. res := base64.StdEncoding.EncodeToString(encryptResult)
  31. return res
  32. }
  33. // 补码
  34. func PKCS7Padding(originByte []byte, blockSize int) []byte {
  35. // 计算补码长度
  36. padding := blockSize - len(originByte)%blockSize
  37. // 生成补码
  38. padText := bytes.Repeat([]byte{byte(padding)}, padding)
  39. // 追加补码
  40. return append(originByte, padText...)
  41. }
  42. // 解密
  43. func AesDecryptByECB(key, data string) (string, error) {
  44. // 判断key长度
  45. keyLenMap := map[int]struct{}{16: {}, 24: {}, 32: {}}
  46. if _, ok := keyLenMap[len(key)]; !ok {
  47. panic("key长度必须是 16、24、32 其中一个")
  48. }
  49. // 反解密码base64
  50. originByte, err := base64.StdEncoding.DecodeString(data)
  51. if err != nil {
  52. fmt.Println(err.Error())
  53. return "", err
  54. }
  55. // 密钥和待加密数据转成[]byte
  56. keyByte := []byte(key)
  57. // 创建密码组,长度只能是16、24、32 字节
  58. block, _ := aes.NewCipher(keyByte)
  59. // 获取密钥长度
  60. blockSize := block.BlockSize()
  61. // 创建保存解密变量
  62. decrypted := make([]byte, len(originByte))
  63. for bs, be := 0, blockSize; bs < len(originByte); bs, be = bs+blockSize, be+blockSize {
  64. block.Decrypt(decrypted[bs:be], originByte[bs:be])
  65. }
  66. // 解码
  67. return string(PKCS7UNPadding(decrypted)), nil
  68. }
  69. // 解码
  70. func PKCS7UNPadding(originDataByte []byte) []byte {
  71. length := len(originDataByte)
  72. unpadding := int(originDataByte[length-1])
  73. return originDataByte[:(length - unpadding)]
  74. }