aes_test.go 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. package service
  2. import (
  3. "crypto/aes"
  4. "crypto/cipher"
  5. "fmt"
  6. "testing"
  7. )
  8. var key = []byte("bili_account_enc")
  9. func TestService_cbcEncrypt(t *testing.T) {
  10. tel := []byte("18612340123")
  11. cipherText, _ := cbcEncrypt(tel)
  12. fmt.Println(len(cipherText))
  13. fmt.Println(cipherText)
  14. }
  15. func TestService_cbcDecrypt(t *testing.T) {
  16. cipherText := []byte{115, 201, 179, 163, 254, 77, 59, 220, 62, 178, 19, 241, 165, 28, 249, 249}
  17. fmt.Println(string(cipherText))
  18. tel, _ := cbcDecrypt(cipherText)
  19. fmt.Println(string(tel))
  20. }
  21. func TestService_cfbEncrypt(t *testing.T) {
  22. tel := []byte("18612340123")
  23. cipherText, _ := cfbEncrypt(tel)
  24. fmt.Println(len(cipherText))
  25. fmt.Println(cipherText)
  26. }
  27. func TestService_cfbDecrypt(t *testing.T) {
  28. cipherText := []byte{48, 35, 4, 24, 80, 204, 171, 226, 219, 74, 16, 95, 138, 184, 249, 205}
  29. fmt.Println(string(cipherText))
  30. tel, _ := cfbDecrypt(cipherText)
  31. fmt.Println(string(tel))
  32. }
  33. func cbcEncrypt(origData []byte) ([]byte, error) {
  34. block, err := aes.NewCipher(key)
  35. if err != nil {
  36. return nil, err
  37. }
  38. blockSize := block.BlockSize()
  39. origData = PKCS5Padding(origData, blockSize)
  40. blockMode := cipher.NewCBCEncrypter(block, key[:blockSize])
  41. crypted := make([]byte, len(origData))
  42. blockMode.CryptBlocks(crypted, origData)
  43. return crypted, nil
  44. }
  45. func cbcDecrypt(crypted []byte) ([]byte, error) {
  46. block, err := aes.NewCipher(key)
  47. if err != nil {
  48. return nil, err
  49. }
  50. blockSize := block.BlockSize()
  51. blockMode := cipher.NewCBCDecrypter(block, key[:blockSize])
  52. origData := make([]byte, len(crypted))
  53. blockMode.CryptBlocks(origData, crypted)
  54. origData = PKCS5UnPadding(origData)
  55. return origData, nil
  56. }
  57. func cfbEncrypt(origData []byte) ([]byte, error) {
  58. block, err := aes.NewCipher(key)
  59. if err != nil {
  60. return nil, err
  61. }
  62. blockSize := block.BlockSize()
  63. origData = PKCS5Padding(origData, blockSize)
  64. cfb := cipher.NewCFBEncrypter(block, key[:blockSize])
  65. crypted := make([]byte, len(origData))
  66. cfb.XORKeyStream(crypted, origData)
  67. return crypted, nil
  68. }
  69. func cfbDecrypt(crypted []byte) ([]byte, error) {
  70. block, err := aes.NewCipher(key)
  71. if err != nil {
  72. return nil, err
  73. }
  74. blockSize := block.BlockSize()
  75. cfb := cipher.NewCFBDecrypter(block, key[:blockSize])
  76. origData := make([]byte, len(crypted))
  77. cfb.XORKeyStream(origData, crypted)
  78. origData = PKCS5UnPadding(origData)
  79. return origData, nil
  80. }