des_ecb.go 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. package util
  2. import (
  3. "bytes"
  4. "crypto/des"
  5. "encoding/hex"
  6. "fmt"
  7. )
  8. // Go DES ECB加密
  9. func EncryptDES_ECB(data []byte, key string) string {
  10. keyByte := []byte(key)
  11. block, err := des.NewCipher(keyByte)
  12. if err != nil {
  13. panic(err)
  14. }
  15. bs := block.BlockSize()
  16. //对明文数据进行补码
  17. data = PKCS5Padding(data, bs)
  18. if len(data)%bs != 0 {
  19. panic("Need a multiple of the blocksize")
  20. }
  21. out := make([]byte, len(data))
  22. dst := out
  23. for len(data) > 0 {
  24. //对明文按照blocksize进行分块加密
  25. //必要时可以使用go关键字进行并行加密
  26. block.Encrypt(dst, data[:bs])
  27. data = data[bs:]
  28. dst = dst[bs:]
  29. }
  30. return fmt.Sprintf("%X", out)
  31. }
  32. func DecryptDES_ECB(src, key string) (string, error) {
  33. data, err := hex.DecodeString(src)
  34. if err != nil {
  35. return "", err
  36. }
  37. keyByte := []byte(key)
  38. block, err := des.NewCipher(keyByte)
  39. if err != nil {
  40. return "", err
  41. }
  42. bs := block.BlockSize()
  43. if len(data)%bs != 0 {
  44. panic("crypto/cipher: input not full blocks")
  45. }
  46. out := make([]byte, len(data))
  47. dst := out
  48. for len(data) > 0 {
  49. block.Decrypt(dst, data[:bs])
  50. data = data[bs:]
  51. dst = dst[bs:]
  52. }
  53. out = PKCS5UnPadding(out)
  54. return string(out), nil
  55. }
  56. // *********************************************
  57. //明文补码算法
  58. func PKCS5Padding(ciphertext []byte, blockSize int) []byte {
  59. padding := blockSize - len(ciphertext)%blockSize
  60. padtext := bytes.Repeat([]byte{byte(padding)}, padding)
  61. return append(ciphertext, padtext...)
  62. }
  63. //明文减码算法
  64. func PKCS5UnPadding(origData []byte) []byte {
  65. length := len(origData)
  66. unpadding := int(origData[length-1])
  67. return origData[:(length - unpadding)]
  68. }