go标准库的学习-crypto/des

参考:https://studygolang.com/pkgdoc

导入方式:

import "crypto/des"

des包实现了DES标准和TDEA算法,参见U.S. Federal Information Processing Standards Publication 46-3。

Constants 

const BlockSize = 8

DES字节块的大小。

type KeySizeError

type KeySizeError int

func (KeySizeError) Error

func (k KeySizeError) Error() string

func NewCipher

func NewCipher(key []byte) (cipher.Block, error)

创建并返回一个使用DES算法的cipher.Block接口。

它与的区别在于它的key最长只能为8字节,否则会报错,如:

key := []byte("example w")

就会报错:

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

func NewTripleDESCipher(key []byte) (cipher.Block, error)

创建并返回一个使用TDEA算法的cipher.Block接口。

举例:

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}
}

 

posted @ 2019-02-28 23:01  慢行厚积  阅读(2161)  评论(0编辑  收藏  举报