golang中DES/ECB/PKCS5Padding的实现
发布时间:2020-12-16 18:27:39 所属栏目:大数据 来源:网络整理
导读:场景:google认为DES/ECB/PKCS5Padding ECB加密安全性低,故没有对方开放.但是我们以前的工程使用的DES/ECB/PKCS5Padding算法,并且已经入库了,所以只能自己实现该算法 import ( "encoding/base64" "bytes" "encoding/binary" "crypto/des" "errors" "log" )
场景: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,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://www.52php.cn/article/p-gefnvkxj-bpk.html (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |