当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


GO NewCBCDecrypter用法及代码示例


GO语言"crypto/cipher"包中"NewCBCDecrypter"函数的用法及代码示例。

用法:

func NewCBCDecrypter(b Block, iv []byte) BlockMode

NewCBCDecrypter 返回一个 BlockMode,它使用给定的块以密码块链接模式解密。 iv 的长度必须与 Block 的块大小相同,并且必须与用于加密数据的 iv 匹配。

例子:

package main

import (
	"crypto/aes"
	"crypto/cipher"
	"encoding/hex"
	"fmt"
)

func main() {
	// Load your secret key from a safe place and reuse it across multiple
	// NewCipher calls. (Obviously don't use this example key for anything
	// real.) If you want to convert a passphrase to a key, use a suitable
	// package like bcrypt or scrypt.
	key, _ := hex.DecodeString("6368616e676520746869732070617373")
	ciphertext, _ := hex.DecodeString("73c86d43a9d700a253a96c85b0f6b03ac9792e0e757f869cca306bd3cba1c62b")

	block, err := aes.NewCipher(key)
	if err != nil {
		panic(err)
	}

	// The IV needs to be unique, but not secure. Therefore it's common to
	// include it at the beginning of the ciphertext.
	if len(ciphertext) < aes.BlockSize {
		panic("ciphertext too short")
	}
	iv := ciphertext[:aes.BlockSize]
	ciphertext = ciphertext[aes.BlockSize:]

	// CBC mode always works in whole blocks.
	if len(ciphertext)%aes.BlockSize != 0 {
		panic("ciphertext is not a multiple of the block size")
	}

	mode := cipher.NewCBCDecrypter(block, iv)

	// CryptBlocks can work in-place if the two arguments are the same.
	mode.CryptBlocks(ciphertext, ciphertext)

	// If the original plaintext lengths are not a multiple of the block
	// size, padding would have to be added when encrypting, which would be
	// removed at this point. For an example, see
	// https://tools.ietf.org/html/rfc5246#section-6.2.3.2. However, it's
	// critical to note that ciphertexts must be authenticated (i.e. by
	// using crypto/hmac) before being decrypted in order to avoid creating
	// a padding oracle.

	fmt.Printf("%s\n", ciphertext)
}

输出:

exampleplaintext

相关用法


注:本文由纯净天空筛选整理自golang.google.cn大神的英文原创作品 NewCBCDecrypter。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。