您的位置:首页 > 编程语言 > Go语言

golang中DES/ECB/PKCS5Padding的实现

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

import (
"encoding/base64"
"bytes"
"encoding/binary"
"crypto/des"
"errors"
"log"
)

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 DesEncrypt(src, key []byte) ([]byte, error) {
block, err := des.NewCipher(key)
if err != nil {
return nil, err
}
bs := block.BlockSize()
src = PKCS5Padding(src, bs)
if len(src) % bs != 0 {
return nil, 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 out, nil
}

func DesDecrypt(src, key []byte) ([]byte, error) {
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 = PKCS5UnPadding(out)
return out, nil
}


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

另外java和golang byte数组转化也是一个坑 @see http://blog.csdn.net/hai046/article/details/52353963
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  golang 算法 DES PKCS5Paddi