des3.go 967 B

12345678910111213141516171819202122232425262728293031323334353637
  1. package utils
  2. import (
  3. "bytes"
  4. "crypto/cipher"
  5. "crypto/des"
  6. "encoding/base64"
  7. )
  8. // des3 + base64 encrypt
  9. func DesBase64Encrypt(origData []byte, desKey string) []byte {
  10. result, err := TripleDesEncrypt(origData, []byte(desKey))
  11. if err != nil {
  12. panic(any(err))
  13. }
  14. return []byte(base64.StdEncoding.EncodeToString(result))
  15. }
  16. // 3DES加密
  17. func TripleDesEncrypt(origData, key []byte) ([]byte, error) {
  18. block, err := des.NewTripleDESCipher(key)
  19. if err != nil {
  20. return nil, err
  21. }
  22. origData = PKCS5Padding(origData, block.BlockSize())
  23. // origData = ZeroPadding(origData, block.BlockSize())
  24. blockMode := cipher.NewCBCEncrypter(block, key[:8])
  25. crypted := make([]byte, len(origData))
  26. blockMode.CryptBlocks(crypted, origData)
  27. return crypted, nil
  28. }
  29. func PKCS5Padding(ciphertext []byte, blockSize int) []byte {
  30. padding := blockSize - len(ciphertext)%blockSize
  31. padtext := bytes.Repeat([]byte{byte(padding)}, padding)
  32. return append(ciphertext, padtext...)
  33. }