參考:https://studygolang.com/pkgdocgolang
導入方式:算法
import "crypto/des"
des包實現了DES標準和TDEA算法,參見U.S. Federal Information Processing Standards Publication 46-3。app
const BlockSize = 8
DES字節塊的大小。spa
type KeySizeError int
func (k KeySizeError) Error() string
func NewCipher(key []byte) (cipher.Block, error)
建立並返回一個使用DES算法的cipher.Block接口。code
它與的區別在於它的key最長只能爲8字節,不然會報錯,如:orm
key := []byte("example w")
就會報錯:blog
panic: crypto/des: invalid key size 9
舉例:接口
package main import ( "fmt" "crypto/des" ) func main() { key := []byte("examplew") desCipher, err := des.NewCipher(key) if err != nil { panic(err) } var inputData = []byte{0x32, 0x43, 0xf6, 0xa8, 0x88, 0x5a, 0x30, 0x8d, 0x31, 0x31, 0x98, 0xa2, 0xe0, 0x37, 0x07, 0x34} out := make([]byte, len(inputData)) desCipher.Encrypt(out, inputData) fmt.Printf("Encrypted data : %#v\n", out) //Encrypted data : []byte{0xac, 0x53, 0x6b, 0xbd, 0x59, 0xc5, 0x82, 0x59, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0} plain := make([]byte, len(inputData)) desCipher.Decrypt(plain, out) fmt.Printf("Decrypted data : %#v\n", plain) //Decrypted data : []byte{0x32, 0x43, 0xf6, 0xa8, 0x88, 0x5a, 0x30, 0x8d, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0} }
func NewTripleDESCipher(key []byte) (cipher.Block, error)
建立並返回一個使用TDEA算法的cipher.Block接口。ip
舉例:ci
package main import ( "fmt" "crypto/des" ) func main() { ede2Key := []byte("example key 1234") var tripleDESKey []byte tripleDESKey = append(tripleDESKey, ede2Key[:16]...) tripleDESKey = append(tripleDESKey, ede2Key[:8]...) desCipher, err := des.NewTripleDESCipher(tripleDESKey) if err != nil { panic(err) } var inputData = []byte{0x32, 0x43, 0xf6, 0xa8, 0x88, 0x5a, 0x30, 0x8d, 0x31, 0x31, 0x98, 0xa2, 0xe0, 0x37, 0x07, 0x34} out := make([]byte, len(inputData)) desCipher.Encrypt(out, inputData) fmt.Printf("Encrypted data : %#v\n", out) //Encrypted data : []byte{0x39, 0x9e, 0xbe, 0xa9, 0xc3, 0xfa, 0x77, 0x5e, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0} plain := make([]byte, len(inputData)) desCipher.Decrypt(plain, out) fmt.Printf("Decrypted data : %#v\n", plain) //Decrypted data : []byte{0x32, 0x43, 0xf6, 0xa8, 0x88, 0x5a, 0x30, 0x8d, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0} }