Java默认DES算法使用DES/ECB/PKCS5Padding,而golang认为这种方式是不安全的,所以故意没有提供这种加密方式,那如果我们还是要用到怎么办?下面贴上golang版的DES ECB加密解密代码(默认对密文做了base64处理)。
1package main 2 3import ( 4 log "ad-service/alog" 5 "bytes" 6 "crypto/des" 7 "encoding/base64" ) 8 9func EntryptDesECB(data, key []byte) string { if len(key) > 8 { 10 key = key[:8] 11 } 12 block, err := des.NewCipher(key) if err != nil { 13 log.Errorf("EntryptDesECB newCipher error[%v]", err) return "" } 14 bs := block.BlockSize() 15 data = PKCS5Padding(data, bs) if len(data)%bs != 0 { 16 log.Error("EntryptDesECB Need a multiple of the blocksize") return "" } out := make([]byte, len(data)) 17 dst := out 18 for len(data) > 0 { 19 block.Encrypt(dst, data[:bs]) 20 data = data[bs:] 21 dst = dst[bs:] 22 } return base64.StdEncoding.EncodeToString(out) 23} 24func DecryptDESECB(d, key []byte) string { 25 data, err := base64.StdEncoding.DecodeString(d) if err != nil { 26 log.Errorf("DecryptDES Decode base64 error[%v]", err) return "" } if len(key) > 8 { 27 key = key[:8] 28 } 29 block, err := des.NewCipher(key) if err != nil { 30 log.Errorf("DecryptDES NewCipher error[%v]", err) return "" } 31 bs := block.BlockSize() if len(data)%bs != 0 { 32 log.Error("DecryptDES crypto/cipher: input not full blocks") return "" } out := make([]byte, len(data)) 33 dst := out 34 for len(data) > 0 { 35 block.Decrypt(dst, data[:bs]) 36 data = data[bs:] 37 dst = dst[bs:] 38 } out = PKCS5UnPadding(out) return string(out) 39} 40 41func PKCS5Padding(ciphertext []byte, blockSize int) []byte { 42 padding := blockSize - len(ciphertext)%blockSize 43 padtext := bytes.Repeat([]byte{byte(padding)}, padding) return append(ciphertext, padtext...) 44} 45 46func PKCS5UnPadding(origData []byte) []byte { 47 length := len(origData) 48 unpadding := int(origData[length-1]) return origData[:(length - unpadding)] 49}
