Java默認DES算法使用DES/ECB/PKCS5Padding,而golang認爲這種方式是不安全的,因此故意沒有提供這種加密方式,那若是咱們仍是要用到怎麼辦?下面貼上golang版的DES ECB加密解密代碼(默認對密文作了base64處理)。golang
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)] }