golang中DES/ECB/PKCS5Padding的实现

前端之家收集整理的这篇文章主要介绍了golang中DES/ECB/PKCS5Padding的实现前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

场景:google认为DES/ECB/PKCS5Padding ECB加密安全性低,故没有对方开放.但是我们以前的工程使用的DES/ECB/PKCS5Padding算法,并且已经入库了,所以只能自己实现该算法

  1. import (
  2. "encoding/base64"
  3. "bytes"
  4. "encoding/binary"
  5. "crypto/des"
  6. "errors"
  7. "log"
  8. )
  9.  
  10. func PKCS5Padding(ciphertext []byte,blockSize int) []byte {
  11. padding := blockSize - len(ciphertext) % blockSize
  12. padtext := bytes.Repeat([]byte{byte(padding)},padding)
  13. return append(ciphertext,padtext...)
  14. }
  15.  
  16. func PKCS5UnPadding(origData []byte) []byte {
  17. length := len(origData)
  18. unpadding := int(origData[length - 1])
  19. return origData[:(length - unpadding)]
  20. }
  21.  
  22. func DesEncrypt(src,key []byte) ([]byte,error) {
  23. block,err := des.NewCipher(key)
  24. if err != nil {
  25. return nil,err
  26. }
  27. bs := block.BlockSize()
  28. src = PKCS5Padding(src,bs)
  29. if len(src) % bs != 0 {
  30. return nil,errors.New("Need a multiple of the blocksize")
  31. }
  32. out := make([]byte,len(src))
  33. dst := out
  34. for len(src) > 0 {
  35. block.Encrypt(dst,src[:bs])
  36. src = src[bs:]
  37. dst = dst[bs:]
  38. }
  39. return out,nil
  40. }
  41.  
  42. func DesDecrypt(src,err
  43. }
  44. out := make([]byte,len(src))
  45. dst := out
  46. bs := block.BlockSize()
  47. if len(src) % bs != 0 {
  48. return nil,errors.New("crypto/cipher: input not full blocks")
  49. }
  50. for len(src) > 0 {
  51. block.Decrypt(dst,src[:bs])
  52. src = src[bs:]
  53. dst = dst[bs:]
  54. }
  55. out = PKCS5UnPadding(out)
  56. return out,nil
  57. }

参考 https://gist.github.com/cuixin/10612934 通过他修改而来

另外java和golang byte数组转化也是一个坑 @see http://www.jb51.cc/article/p-gefnvkxj-bpk.html

猜你在找的Go相关文章