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

  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值