82 lines
1.8 KiB
Go
82 lines
1.8 KiB
Go
package des
|
|
|
|
import (
|
|
utils "anytunnel/at-common"
|
|
"bytes"
|
|
"crypto/des"
|
|
"encoding/hex"
|
|
"errors"
|
|
)
|
|
|
|
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[length-1])
|
|
return origData[:(length - unpadding)]
|
|
}
|
|
|
|
func ZeroPadding(ciphertext []byte, blockSize int) []byte {
|
|
padding := blockSize - len(ciphertext)%blockSize
|
|
padtext := bytes.Repeat([]byte{0}, padding)
|
|
return append(ciphertext, padtext...)
|
|
}
|
|
|
|
func ZeroUnPadding(origData []byte) []byte {
|
|
return bytes.TrimFunc(origData,
|
|
func(r rune) bool {
|
|
return r == rune(0)
|
|
})
|
|
}
|
|
|
|
func Encrypt(src []byte, key string) (string, error) {
|
|
block, err := des.NewCipher([]byte(utils.Md5(key)[0:8]))
|
|
if err != nil {
|
|
return "", err
|
|
}
|
|
bs := block.BlockSize()
|
|
src = ZeroPadding(src, bs)
|
|
// src = PKCS5Padding(src, bs)
|
|
if len(src)%bs != 0 {
|
|
return "", errors.New("Need a multiple of the blocksize")
|
|
}
|
|
out := make([]byte, len(src))
|
|
dst := out
|
|
for len(src) > 0 {
|
|
block.Encrypt(dst, src[:bs])
|
|
src = src[bs:]
|
|
dst = dst[bs:]
|
|
}
|
|
return hex.EncodeToString(out), nil
|
|
}
|
|
|
|
func Decrypt(_src string, _key string) ([]byte, error) {
|
|
key := []byte(utils.Md5(_key)[0:8])
|
|
src, err := hex.DecodeString(_src)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
block, err := des.NewCipher(key)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
out := make([]byte, len(src))
|
|
dst := out
|
|
bs := block.BlockSize()
|
|
if len(src)%bs != 0 {
|
|
return nil, errors.New("crypto/cipher: input not full blocks")
|
|
}
|
|
for len(src) > 0 {
|
|
block.Decrypt(dst, src[:bs])
|
|
src = src[bs:]
|
|
dst = dst[bs:]
|
|
}
|
|
out = ZeroUnPadding(out)
|
|
// out = PKCS5UnPadding(out)
|
|
return out, nil
|
|
}
|