golang中DES/ECB/PKCS5Padding的实现

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