yanfei 发表于 2018-9-20 12:39:08

DES加密ECB(模式) golang

package main  

  
import (
  log
"ad-service/alog"  "bytes"
  "crypto/des"
  "encoding/base64"
  
)
  

  
func EntryptDesECB(data, key []byte) string {
  if len(key) > 8 {
  key = key[:8]
  }
  block, err := des.NewCipher(key)
  if err != nil {
  log.Errorf("EntryptDesECB newCipher error[%v]", err)
  return ""
  }
  bs := block.BlockSize()
  data = PKCS5Padding(data, bs)
  if len(data)%bs != 0 {
  log.Error("EntryptDesECB Need a multiple of the blocksize")
  return ""
  }
  out := make([]byte, len(data))
  dst := out
  for len(data) > 0 {
  block.Encrypt(dst, data[:bs])
  data = data
  dst = dst
  }
  return base64.StdEncoding.EncodeToString(out)
  
}
  
func DecryptDESECB(d, key []byte) string {
  data, err := base64.StdEncoding.DecodeString(d)
  if err != nil {
  log.Errorf("DecryptDES Decode base64 error[%v]", err)
  return ""
  }
  if len(key) > 8 {
  key = key[:8]
  }
  block, err := des.NewCipher(key)
  if err != nil {
  log.Errorf("DecryptDES NewCipher error[%v]", err)
  return ""
  }
  bs := block.BlockSize()
  if len(data)%bs != 0 {
  log.Error("DecryptDES crypto/cipher: input not full blocks")
  return ""
  }
  out := make([]byte, len(data))
  dst := out
  for len(data) > 0 {
  block.Decrypt(dst, data[:bs])
  data = data
  dst = dst
  }
  out = PKCS5UnPadding(out)
  return string(out)
  
}
  

  
func PKCS5Padding(ciphertext []byte, blockSize int) []byte {
  padding := blockSize - len(ciphertext)%blockSize
  padtext := bytes.Repeat([]byte{byte(padding)}, padding)
  return append(ciphertext, padtext...)
  
}
  

  
func PKCS5UnPadding(origData []byte) []byte {
  length := len(origData)
  unpadding := int(origData)
  return origData[:(length - unpadding)]
  
}


页: [1]
查看完整版本: DES加密ECB(模式) golang