package聽util import聽( "bytes" "crypto/cipher" "crypto/des" "encoding/base64" ) var聽( iv聽聽=聽[]byte{1,聽2,聽3,聽4,聽5,聽6,聽7,聽8} key聽=聽[]byte("java") ) //DES加密 func聽DesEncrypt(data聽[]byte)聽string聽{ result,聽_聽:=聽DesEncrypt(data,聽key,聽iv) return聽base64.StdEncoding.EncodeToString(result) } //DES解密 func聽DesDecrypt(base64Str聽string)聽string聽{ result,聽err聽:=聽base64.StdEncoding.DecodeString(base64Str) if聽err聽!=聽nil聽{ return聽"" } origData,聽err聽:=聽DesDecrypt(result,聽key,聽iv) if聽err聽!=聽nil聽{ return聽"" } return聽string(origData) } func聽DesEncrypt(origData,聽key,聽iv聽[]byte)聽([]byte,聽error)聽{ block,聽err聽:=聽des.NewCipher(key) if聽err聽!=聽nil聽{ return聽nil,聽err } origData聽=聽PKCS5Padding(origData,聽block.BlockSize()) blockMode聽:=聽cipher.NewCBCEncrypter(block,聽iv) crypted聽:=聽make([]byte,聽len(origData)) blockMode.CryptBlocks(crypted,聽origData) return聽crypted,聽nil } func聽DesDecrypt(crypted,聽key,聽iv聽[]byte)聽([]byte,聽error)聽{ block,聽err聽:=聽des.NewCipher(key) if聽err聽!=聽nil聽{ return聽nil,聽err } blockMode聽:=聽cipher.NewCBCDecrypter(block,聽iv) origData聽:=聽make([]byte,聽len(crypted)) blockMode.CryptBlocks(origData,聽crypted) origData聽=聽PKCS5UnPadding(origData) return聽origData,聽nil } func聽ZeroUnPadding(origData聽[]byte)聽[]byte聽{ return聽bytes.TrimRightFunc(origData,聽func(r聽rune)聽bool聽{ return聽r聽==聽rune(0) }) } 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)] }
我查
#1