zoukankan      html  css  js  c++  java
  • DES加密ECB(模式) golang

    Java默认DES算法使用DES/ECB/PKCS5Padding,而golang认为这种方式是不安全的,所以故意没有提供这种加密方式,那如果我们还是要用到怎么办?下面贴上golang版的DES ECB加密解密代码(默认对密文做了base64处理)。

    package main
    
    import (
        log "ad-service/alog"
        "bytes"
        "crypto/des"
        "encoding/base64"
    )
    
    func EntryptDesECB(data, key []byte) string {
        if len(key) > 8 {
            key = key[:8]
        }
        block, err := des.NewCipher(key)
        if err != nil {
            log.Errorf("EntryptDesECB newCipher error[%v]", err)
            return ""
        }
        bs := block.BlockSize()
        data = PKCS5Padding(data, bs)
        if len(data)%bs != 0 {
            log.Error("EntryptDesECB Need a multiple of the blocksize")
            return ""
        }
        out := make([]byte, len(data))
        dst := out
        for len(data) > 0 {
            block.Encrypt(dst, data[:bs])
            data = data[bs:]
            dst = dst[bs:]
        }
        return base64.StdEncoding.EncodeToString(out)
    }
    func DecryptDESECB(d, key []byte) string {
        data, err := base64.StdEncoding.DecodeString(d)
        if err != nil {
            log.Errorf("DecryptDES Decode base64 error[%v]", err)
            return ""
        }
        if len(key) > 8 {
            key = key[:8]
        }
        block, err := des.NewCipher(key)
        if err != nil {
            log.Errorf("DecryptDES NewCipher error[%v]", err)
            return ""
        }
        bs := block.BlockSize()
        if len(data)%bs != 0 {
            log.Error("DecryptDES crypto/cipher: input not full blocks")
            return ""
        }
        out := make([]byte, len(data))
        dst := out
        for len(data) > 0 {
            block.Decrypt(dst, data[:bs])
            data = data[bs:]
            dst = dst[bs:]
        }
        out = PKCS5UnPadding(out)
        return string(out)
    }
    
    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)]
    }
    View Code
  • 相关阅读:
    java JSONObject
    android 8.0 悬浮窗 最简demo
    使用adb 命令(atrace)抓起systrace的方法。
    使用python处理selenium中的获取元素属性
    使用adb/Linux获取网关ip
    Requests text乱码
    python-uiautomator2
    adb命令 判断锁屏
    缓存穿透、缓存击穿与缓存雪崩
    ReentrantLock重入锁详解
  • 原文地址:https://www.cnblogs.com/xiaxiaosheng/p/8818456.html
Copyright © 2011-2022 走看看