GO语言"crypto/cipher"包中"NewCBCEncrypter"函数的用法及代码示例。
用法:
func NewCBCEncrypter(b Block, iv []byte) BlockMode
NewCBCEncrypter 返回一个 BlockMode,它使用给定的块以密码块链接模式进行加密。 iv 的长度必须与 Block 的块大小相同。
例子:
package main
import (
"crypto/aes"
"crypto/cipher"
"crypto/rand"
"encoding/hex"
"fmt"
"io"
)
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")
plaintext := []byte("exampleplaintext")
// CBC mode works on blocks so plaintexts may need to be padded to the
// next whole block. For an example of such padding, see
// https://tools.ietf.org/html/rfc5246#section-6.2.3.2. Here we'll
// assume that the plaintext is already of the correct length.
if len(plaintext)%aes.BlockSize != 0 {
panic("plaintext is not a multiple of the block size")
}
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.
ciphertext := make([]byte, aes.BlockSize+len(plaintext))
iv := ciphertext[:aes.BlockSize]
if _, err := io.ReadFull(rand.Reader, iv); err != nil {
panic(err)
}
mode := cipher.NewCBCEncrypter(block, iv)
mode.CryptBlocks(ciphertext[aes.BlockSize:], plaintext)
// It's important to remember that ciphertexts must be authenticated
// (i.e. by using crypto/hmac) as well as being encrypted in order to
// be secure.
fmt.Printf("%x\n", ciphertext)
}
相关用法
- GO NewCBCDecrypter用法及代码示例
- GO NewCFBDecrypter用法及代码示例
- GO NewCFBEncrypter用法及代码示例
- GO NewCTR用法及代码示例
- GO NewFromFiles用法及代码示例
- GO NewReader用法及代码示例
- GO NewReplacer用法及代码示例
- GO New用法及代码示例
- GO NewGCM用法及代码示例
- GO NewTripleDESCipher用法及代码示例
- GO NewWriter用法及代码示例
- GO NewOFB用法及代码示例
- GO NewTLSServer用法及代码示例
- GO NewTicker用法及代码示例
- GO NewEncoder用法及代码示例
- GO NumError用法及代码示例
- GO NotifyContext用法及代码示例
- GO Node用法及代码示例
- GO Notify用法及代码示例
- GO NotFoundHandler用法及代码示例
注:本文由纯净天空筛选整理自golang.google.cn大神的英文原创作品 NewCBCEncrypter。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。