aes.go 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. package encrypt
  2. import (
  3. "bytes"
  4. "crypto/aes"
  5. "crypto/cipher"
  6. "encoding/hex"
  7. )
  8. /*CBC加密 按照golang标准库的例子代码
  9. 不过里面没有填充的部分,所以补上,根据key来决定填充blocksize
  10. */
  11. //使用PKCS7进行填充,IOS也是7
  12. func pkcs7Padding(ciphertext []byte, blockSize int) []byte {
  13. padding := blockSize - len(ciphertext)%blockSize
  14. padtext := bytes.Repeat([]byte{byte(0)}, padding)
  15. return append(ciphertext, padtext...)
  16. }
  17. func pkcs7UnPadding(ciphertext []byte, blockSize int) []byte {
  18. padding := blockSize - len(ciphertext)%blockSize
  19. padtext := bytes.Repeat([]byte{0}, padding) //用0去填充
  20. return append(ciphertext, padtext...)
  21. }
  22. //aes加密,填充模式由key决定,16位,24,32分别对应AES-128, AES-192, or AES-256.源码好像是写死16了
  23. func AesCBCEncrypt(rawData, key []byte) ([]byte, error) {
  24. block, err := aes.NewCipher(key)
  25. if err != nil {
  26. panic(err)
  27. }
  28. //填充原文
  29. blockSize := block.BlockSize()
  30. rawData = pkcs7Padding(rawData, blockSize)
  31. cipherText := make([]byte, len(rawData))
  32. //block大小和初始向量大小一定要一致
  33. mode := cipher.NewCBCEncrypter(block, key)
  34. mode.CryptBlocks(cipherText, rawData)
  35. return cipherText, nil
  36. }
  37. func AesCBCDecrypt(encryptData, key []byte) ([]byte, error) {
  38. block, err := aes.NewCipher(key)
  39. if err != nil {
  40. panic(err)
  41. }
  42. blockSize := block.BlockSize()
  43. if len(encryptData) < blockSize {
  44. panic("ciphertext too short")
  45. }
  46. // CBC mode always works in whole blocks.
  47. if len(encryptData)%blockSize != 0 {
  48. panic("ciphertext is not a multiple of the block size")
  49. }
  50. mode := cipher.NewCBCDecrypter(block, key)
  51. // CryptBlocks can work in-place if the two arguments are the same.
  52. mode.CryptBlocks(encryptData, encryptData)
  53. //解填充
  54. encryptData = pkcs7UnPadding(encryptData, blockSize)
  55. return encryptData, nil
  56. }
  57. func Encrypt(rawData, key []byte) (string, error) {
  58. data, err := AesCBCEncrypt(rawData, key)
  59. if err != nil {
  60. return "", err
  61. }
  62. encryptData := hex.EncodeToString(data)
  63. return encryptData, nil
  64. }
  65. func Decrypt(rawData string, key []byte) (string, error) {
  66. data, err := hex.DecodeString(rawData)
  67. if err != nil {
  68. return "", err
  69. }
  70. dnData, err := AesCBCDecrypt(data, key)
  71. if err != nil {
  72. return "", err
  73. }
  74. return string(dnData), nil
  75. }