golang中DES/ECB/PKCS5Padding的实现

来源:互联网 发布:博士德汽修软件 编辑:程序博客网 时间:2024/06/05 22:39

场景: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

0 0
原创粉丝点击