加密
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.

101 lines
2.3 KiB

  1. package crypter
  2. import (
  3. "encoding/base64"
  4. "errors"
  5. "crypto/des"
  6. "encoding/hex"
  7. )
  8. // ECB模式加密,返回16进制结果
  9. func TripleECBEncryptForHex(key, plaintext string) (string, error) {
  10. keyBytes, err := base64.StdEncoding.DecodeString(key)
  11. if err != nil {
  12. return "", err
  13. }
  14. data := []byte(plaintext)
  15. ciphertext, err := TripleECBEncrypt(keyBytes, data)
  16. if err != nil {
  17. return "", err
  18. }
  19. return hex.EncodeToString(ciphertext), nil
  20. }
  21. // ECB模式解密16进制密文
  22. func TripleECBDecryptFromHex(key, plaintext string) (string, error) {
  23. keyBytes, err := base64.StdEncoding.DecodeString(key)
  24. if err != nil {
  25. return "", err
  26. }
  27. data, err := hex.DecodeString(plaintext)
  28. if err != nil {
  29. return "", err
  30. }
  31. ciphertext, err := TripleECBDecrypt(keyBytes, data)
  32. if err != nil {
  33. return "", err
  34. }
  35. return string(ciphertext), nil
  36. }
  37. // ECB模式加密,返回byte
  38. func TripleECBEncrypt(key, plaintext []byte) ([]byte, error) {
  39. // 创建Triple DES的块加密器
  40. block, err := des.NewTripleDESCipher(key)
  41. if err != nil {
  42. return []byte(""), err
  43. }
  44. // 创建切片来存储加密后的密文
  45. ciphertext := make([]byte, len(plaintext))
  46. // 复制明文到切片中
  47. copy(ciphertext, plaintext)
  48. // 应用PKCS#7填充
  49. ciphertext = PKCS5Padding(ciphertext, block.BlockSize())
  50. // 使用ECB模式加密填充后的数据
  51. for i := 0; i < len(ciphertext); i += block.BlockSize() {
  52. block.Encrypt(ciphertext[i:i+block.BlockSize()], ciphertext[i:i+block.BlockSize()])
  53. }
  54. return ciphertext, nil
  55. }
  56. // ECB模式解密,返回byte
  57. func TripleECBDecrypt(key, ciphertext []byte) ([]byte, error) {
  58. // 创建Triple DES的块加密器(解密时也需要这个)
  59. block, err := des.NewTripleDESCipher(key)
  60. if err != nil {
  61. return []byte(""), err
  62. }
  63. // 检查密文长度是否是8字节的倍数
  64. if len(ciphertext)%des.BlockSize != 0 {
  65. return []byte(""), errors.New("ciphertext is not a multiple of the block size")
  66. }
  67. // 创建一个buffer来存储解密后的明文
  68. plaintext := make([]byte, len(ciphertext))
  69. // 使用ECB模式解密
  70. for i := 0; i < len(ciphertext); i += block.BlockSize() {
  71. block.Decrypt(plaintext[i:i+block.BlockSize()], ciphertext[i:i+block.BlockSize()])
  72. }
  73. plaintext = PKCS5UnPadding(plaintext)
  74. // 打印解密后的明文
  75. return plaintext, nil
  76. }