cbc.go 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. // Copyright 2019 getensh.com. All rights reserved.
  2. // Use of this source code is governed by getensh.com.
  3. package util
  4. import (
  5. "bytes"
  6. "crypto/cipher"
  7. "crypto/des"
  8. )
  9. // CBCDesEncrypt des加密, mode: cbc
  10. func CBCDesEncrypt(key, iv, plainText []byte) ([]byte, error) {
  11. block, err := des.NewCipher(key)
  12. if err != nil {
  13. return nil, err
  14. }
  15. blockSize := block.BlockSize()
  16. origData := pkcs5Padding(plainText, blockSize)
  17. blockMode := cipher.NewCBCEncrypter(block, iv)
  18. cryted := make([]byte, len(origData))
  19. blockMode.CryptBlocks(cryted, origData)
  20. return cryted, nil
  21. }
  22. // CBCDesDecrypt des解密, mode: cbc
  23. func CBCDesDecrypt(key, iv, cipherText []byte) ([]byte, error) {
  24. block, err := des.NewCipher(key)
  25. if err != nil {
  26. return nil, err
  27. }
  28. blockMode := cipher.NewCBCDecrypter(block, iv)
  29. origData := make([]byte, len(cipherText))
  30. blockMode.CryptBlocks(origData, cipherText)
  31. origData = pkcs5UnPadding(origData)
  32. return origData, nil
  33. }
  34. func pkcs5Padding(src []byte, blockSize int) []byte {
  35. padding := blockSize - len(src)%blockSize
  36. padtext := bytes.Repeat([]byte{byte(padding)}, padding)
  37. return append(src, padtext...)
  38. }
  39. func pkcs5UnPadding(src []byte) []byte {
  40. length := len(src)
  41. unpadding := int(src[length-1])
  42. return src[:(length - unpadding)]
  43. }