go中使用des cbc加密解密

加密:

func MyEncrypt(data, key []byte, iv []byte) ([]byte, error) {
	/*
		key必须是8位,否则报错:
		if len(key) != 8 {
			return nil, KeySizeError(len(key))
		}
	*/
	block, err := des.NewCipher(key)
	if err != nil {
		return nil, err
	}
	bs := block.BlockSize()
	data = PKCS5Padding(data, bs) //填充字符
	blockMode := cipher.NewCBCEncrypter(block, iv)
	out := make([]byte, len(data))
	blockMode.CryptBlocks(out, data)
	return out, nil
}

func PKCS5Padding(ciphertext []byte, blockSize int) []byte {
	padding := blockSize - len(ciphertext)%blockSize
	padText := bytes.Repeat([]byte{byte(padding)}, padding)
	return append(ciphertext, padText...)
}

func base64Encode(src []byte) []byte {
	return []byte(base64.StdEncoding.EncodeToString(src))
}

func main() {
	key := []byte("12345678")
	iv := []byte("12345678")
	data := []byte("hello world")
	out, _ := MyEncrypt(data, key, iv)
	deByte := base64Encode(out)
	log.Println("加密后:", string(deByte))   //2022/01/17 15:40:30 加密后: CyqS6B+0nOGkMmaqyup7gQ==
}

解密: 

func MyDecrypt(data []byte, key []byte, iv []byte) ([]byte, error) {
	block, err := des.NewCipher(key)
	if err != nil {
		return nil, err
	}
	blockMode := cipher.NewCBCDecrypter(block, iv)
	out := make([]byte, len(data))
	blockMode.CryptBlocks(out, data)
	out = PKCS5UnPadding(out)
	return out, nil
}

func PKCS5UnPadding(origData []byte) []byte {
	length := len(origData)
	unPadding := int(origData[length-1])
	return origData[:(length - unPadding)]
}

func base64Decode(src []byte) ([]byte, error) {
	return base64.StdEncoding.DecodeString(string(src))
}

func main() {
	key := []byte("12345678")
	iv := []byte("12345678")
	src := []byte("CyqS6B+0nOGkMmaqyup7gQ==")
	enByte, _ := base64Decode(src)
	out, _ := MyDecrypt(enByte, key, iv)
	log.Println("解密后:", string(out))  //2022/01/17 15:44:23 解密后: hello world
}

  

  

posted @ 2022-01-17 15:45  屁桃  阅读(369)  评论(0编辑  收藏  举报