?
This document uses PHP Chinese website manual Release
import "crypto/cipher"
概述
索引
示例
加密包(Package cipher)實(shí)現(xiàn)了標(biāo)準(zhǔn)塊密碼模式,可以圍繞低級(jí)塊密碼實(shí)現(xiàn)。請(qǐng)參閱http://csrc.nist.gov/groups/ST/toolkit/BCM/current_modes.html和NIST Special Publication
800-38A。
type AEAD
func NewGCM(cipher Block) (AEAD, error)
func NewGCMWithNonceSize(cipher Block, size int) (AEAD, error)
type Block
type BlockMode
func NewCBCDecrypter(b Block, iv []byte) BlockMode
func NewCBCEncrypter(b Block, iv []byte) BlockMode
type Stream
func NewCFBDecrypter(block Block, iv []byte) Stream
func NewCFBEncrypter(block Block, iv []byte) Stream
func NewCTR(block Block, iv []byte) Stream
func NewOFB(b Block, iv []byte) Stream
type StreamReader
func (r StreamReader) Read(dst []byte) (n int, err error)
type StreamWriter
func (w StreamWriter) Close() error
func (w StreamWriter) Write(src []byte) (n int, err error)
NewCBCDecrypter NewCBCEncrypter NewCFBDecrypter NewCFBEncrypter NewCTR NewGCM (Decrypt) NewGCM (Encrypt) NewOFB StreamReader StreamWriter
cbc.go cfb.go cipher.go ctr.go gcm.go io.go ofb.go xor.go
AEAD是一種密碼模式,提供帶有關(guān)聯(lián)數(shù)據(jù)的認(rèn)證加密。有關(guān)該方法的說明,請(qǐng)參閱
https://en.wikipedia.org/wiki/Authenticated_encryption
type AEAD interface { // NonceSize返回必須傳遞給Seal的隨機(jī)數(shù)的大小 // and Open. NonceSize() int // Overhead返回以下兩者間的最大差異 // plaintext 和 its ciphertext. Overhead() int // 密封加密和驗(yàn)證明文,驗(yàn)證 // 附加數(shù)據(jù)并將結(jié)果附加到dst,并返回更新 // slice。 nonce必須是NonceSize()字節(jié)長(zhǎng)且對(duì)所有人都是唯一的 // time, 對(duì)于給定的密鑰。 // // 明文和dst可能完全或根本不是別名。 重用 // 明文的加密輸出存儲(chǔ),使用 plaintext[:0]作為dst。 Seal(dst, nonce, plaintext, additionalData []byte) []byte // 打開解密并驗(yàn)證密文,驗(yàn)證密文 // 額外的數(shù)據(jù),如果成功的話,附加結(jié)果明文 // 到dst,返回更新的片。 nonce必須是NonceSize() // 字節(jié)長(zhǎng),它和附加數(shù)據(jù)必須匹配 // 值傳遞給Seal。 // // 密文和dst可以完全混淆或根本不混淆。 重用 // 密文的解密輸出存儲(chǔ),使用ciphertext [:0]作為dst。 // // 即使該功能失敗,dst的內(nèi)容,直到其容量, // 可能會(huì)被覆蓋。 Open(dst, nonce, ciphertext, additionalData []byte) ([]byte, error)}
func NewGCM(cipher Block) (AEAD, error)
NewGCM 返回給定的128-bit,以伽羅華計(jì)數(shù)器模式(Galois Counter Mode包裝的分組密碼,其標(biāo)準(zhǔn)隨機(jī)數(shù)長(zhǎng)度。
一般來說,這種 GCM 實(shí)施的 GHASH 操作不是一個(gè)固定時(shí)間。當(dāng)硬件支持 AES 的系統(tǒng)上由 aes.NewCipher 創(chuàng)建底層 Block 時(shí),則是個(gè)例外。有關(guān)詳細(xì)信息,請(qǐng)參閱 crypto/aes 軟件包文檔。
package mainimport ("crypto/aes""crypto/cipher""encoding/hex""fmt")func main() {// 關(guān)鍵參數(shù)應(yīng)該是AES密鑰,16或32個(gè)字節(jié)// 選擇 AES-128 或 AES-256。 key := []byte("AES256Key-32Characters1234567890") ciphertext, _ := hex.DecodeString("1019aa66cd7c024f9efd0038899dae1973ee69427f5a6579eba292ffe1b5a260") nonce, _ := hex.DecodeString("37b8e8a308c354048d245f6d") block, err := aes.NewCipher(key)if err != nil {panic(err.Error())} aesgcm, err := cipher.NewGCM(block)if err != nil {panic(err.Error())} plaintext, err := aesgcm.Open(nil, nonce, ciphertext, nil)if err != nil {panic(err.Error())} fmt.Printf("%s\n", plaintext)}
package mainimport ("crypto/aes""crypto/cipher""crypto/rand""fmt""io")func main() {// 關(guān)鍵參數(shù)應(yīng)該是AES密鑰,16或32個(gè)字節(jié)// 選擇AES-128或AES-256。 key := []byte("AES256Key-32Characters1234567890") plaintext := []byte("exampleplaintext") block, err := aes.NewCipher(key)if err != nil {panic(err.Error())}// 由于存在重復(fù)的風(fēng)險(xiǎn),請(qǐng)勿使用給定密鑰使用超過2^32個(gè)隨機(jī)值。 nonce := make([]byte, 12)if _, err := io.ReadFull(rand.Reader, nonce); err != nil {panic(err.Error())} aesgcm, err := cipher.NewGCM(block)if err != nil {panic(err.Error())} ciphertext := aesgcm.Seal(nil, nonce, plaintext, nil) fmt.Printf("%x\n", ciphertext)}
func NewGCMWithNonceSize(cipher Block, size int) (AEAD, error)
NewGCMWithNonceSize 返回給定的 128 位,以 Galois 計(jì)數(shù)器模式包裝的分組密碼,它接受給定長(zhǎng)度的隨機(jī)數(shù)。
如果您需要與使用非標(biāo)準(zhǔn)隨機(jī)數(shù)長(zhǎng)度的現(xiàn)有密碼系統(tǒng)兼容,請(qǐng)僅使用此功能。所有其他用戶都應(yīng)該使用 NewGCM,它更快,更耐濫用。
塊表示使用給定密鑰的分組密碼的實(shí)現(xiàn)。它提供了加密或解密各個(gè)塊的功能。模式實(shí)現(xiàn)將該能力擴(kuò)展到塊流。
type Block interface { // BlockSize返回密碼的塊大小。 BlockSize() int // 加密將src中的第一個(gè)塊加密到dst中。 // Dst和src可能指向相同的內(nèi)存。 Encrypt(dst, src []byte) // 解密將src中的第一個(gè)塊解密為dst。 // Dst和src可能指向相同的內(nèi)存。 Decrypt(dst, src []byte)}
BlockMode表示以基于塊的模式運(yùn)行的分組密碼(CBC,ECB等)。
type BlockMode interface { // BlockSize返回模式的塊大小。 BlockSize() int // CryptBlocks加密或解密一些塊。 The length of // src必須是塊大小的倍數(shù)。 Dst和src可能指向 // 相同的內(nèi)存。 CryptBlocks(dst, src []byte)}
func NewCBCDecrypter(b Block, iv []byte) BlockMode
NewCBCDecrypter 返回一個(gè) BlockMode,它使用給定的Block 以密碼塊鏈接模式解密。iv 的長(zhǎng)度必須與 Block 的塊大小相同,并且必須與用于加密數(shù)據(jù)的 iv 相匹配。
package mainimport ("crypto/aes""crypto/cipher""encoding/hex""fmt")func main() { key := []byte("example key 1234") ciphertext, _ := hex.DecodeString("f363f3ccdcb12bb883abf484ba77d9cd7d32b5baecb3d4b1b3e0e4beffdb3ded") block, err := aes.NewCipher(key)if err != nil {panic(err)}// IV需要獨(dú)特,但不安全。 所以這很常見// 將其包括在密文的開頭。if len(ciphertext) < aes.BlockSize {panic("ciphertext too short")} iv := ciphertext[:aes.BlockSize] ciphertext = ciphertext[aes.BlockSize:]// CBC模式總是在整個(gè)模塊中工作。if len(ciphertext)%aes.BlockSize != 0 {panic("ciphertext is not a multiple of the block size")} mode := cipher.NewCBCDecrypter(block, iv)// 如果兩個(gè)參數(shù)相同,CryptBlocks可以在原地工作。 mode.CryptBlocks(ciphertext, ciphertext)// 如果原始plaintext長(zhǎng)度不是塊的倍數(shù)// 大小,填充將不得不在加密時(shí)添加,這將是// 在這一點(diǎn)刪除。 有關(guān)示例,請(qǐng)參閱// https://tools.ietf.org/html/rfc5246#section-6.2.3.2. 然而,// 至關(guān)重要的是要注意密文必須被認(rèn)證(即通過// 使用crypto/hmac)解密之前,以避免創(chuàng)建// 一個(gè)填充oracle。 fmt.Printf("%s\n", ciphertext)}
func NewCBCEncrypter(b Block, iv []byte) BlockMode
NewCBCEncrypter 返回一個(gè) BlockMode,它使用給定的 Block 以密碼塊鏈接模式加密。iv 的長(zhǎng)度必須與塊的塊大小相同。
package mainimport ("crypto/aes""crypto/cipher""crypto/rand""fmt""io")func main() { key := []byte("example key 1234") plaintext := []byte("exampleplaintext")// CBC模式在塊上工作,所以明文可能需要填充到塊// 下一個(gè)整塊。 有關(guān)這種填充的示例,請(qǐng)參閱// https://tools.ietf.org/html/rfc5246#section-6.2.3.2. 這里,我們將// 假定 plaintext 已經(jīng)是正確的長(zhǎng)度。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)}// IV需要獨(dú)特,但不安全。 所以這很常見// 將其包括在密文的開頭。 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)// 記住密文必須經(jīng)過認(rèn)證是很重要的// (即通過使用crypto/hmac)以及為了加密而被加密// 保持secure。 fmt.Printf("%x\n", ciphertext)}
Stream表示流密碼。
type Stream interface { // XORKeyStream將給定片中的每個(gè)字節(jié)與來自該字節(jié)的一個(gè)字節(jié)異或 // 密碼的密鑰流。 Dst和src可能指向相同的內(nèi)存。 // 如果len(dst)<len(src),XORKeyStream應(yīng)該是恐慌的。 它是可以接受的 // 傳遞比src更大的dst,在那種情況下,XORKeyStream會(huì) // 只更新dst[:len(src)]并且不會(huì)觸及dst的其余部分。 XORKeyStream(dst, src []byte)}
func NewCFBDecrypter(block Block, iv []byte) Stream
新的 CFB 解密器使用給定的塊返回一個(gè)使用密碼反饋模式解密的 Stream。iv 的長(zhǎng)度必須與塊的塊大小相同。
package mainimport ("crypto/aes""crypto/cipher""encoding/hex""fmt")func main() { key := []byte("example key 1234") ciphertext, _ := hex.DecodeString("22277966616d9bc47177bd02603d08c9a67d5380d0fe8cf3b44438dff7b9") block, err := aes.NewCipher(key)if err != nil {panic(err)}// IV需要獨(dú)特,但不安全。 所以這很常見// 將其包括在密文的開頭。if len(ciphertext) < aes.BlockSize {panic("ciphertext too short")} iv := ciphertext[:aes.BlockSize] ciphertext = ciphertext[aes.BlockSize:] stream := cipher.NewCFBDecrypter(block, iv)// 如果兩個(gè)參數(shù)相同,XORKeyStream可以在原地工作。 stream.XORKeyStream(ciphertext, ciphertext) fmt.Printf("%s", ciphertext)}
func NewCFBEncrypter(block Block, iv []byte) Stream
NewCFBEncrypter 使用給定的 Block 返回一個(gè)使用密碼反饋模式加密的 Stream。iv 的長(zhǎng)度必須與塊的塊大小相同。
package mainimport ("crypto/aes""crypto/cipher""crypto/rand""io")func main() { key := []byte("example key 1234") plaintext := []byte("some plaintext") block, err := aes.NewCipher(key)if err != nil {panic(err)}// IV需要獨(dú)特,但不安全。 所以這很常見// 將其包括在密文的開頭。 ciphertext := make([]byte, aes.BlockSize+len(plaintext)) iv := ciphertext[:aes.BlockSize]if _, err := io.ReadFull(rand.Reader, iv); err != nil {panic(err)} stream := cipher.NewCFBEncrypter(block, iv) stream.XORKeyStream(ciphertext[aes.BlockSize:], plaintext)// 記住密文必須經(jīng)過認(rèn)證是很重要的// (即通過使用crypto/hmac)以及為了加密而被加密// 保持secure。}
func NewCTR(block Block, iv []byte) Stream
NewCTR 返回一個(gè) Stream,它使用計(jì)數(shù)器模式下的給定 Block加密/解密。iv 的長(zhǎng)度必須與塊的塊大小相同。
package mainimport ("crypto/aes""crypto/cipher""crypto/rand""fmt""io")func main() { key := []byte("example key 1234") plaintext := []byte("some plaintext") block, err := aes.NewCipher(key)if err != nil {panic(err)}// IV需要獨(dú)特,但不安全。 所以這很常見// 將其包括在密文的開頭。 ciphertext := make([]byte, aes.BlockSize+len(plaintext)) iv := ciphertext[:aes.BlockSize]if _, err := io.ReadFull(rand.Reader, iv); err != nil {panic(err)} stream := cipher.NewCTR(block, iv) stream.XORKeyStream(ciphertext[aes.BlockSize:], plaintext)// 記住密文必須經(jīng)過認(rèn)證是很重要的// (即通過使用crypto/hmac)以及為了加密而被加密// 保持secure。// CTR模式對(duì)于加密和解密都是一樣的,所以我們可以// 也用NewCTR解密該密文。 plaintext2 := make([]byte, len(plaintext)) stream = cipher.NewCTR(block, iv) stream.XORKeyStream(plaintext2, ciphertext[aes.BlockSize:]) fmt.Printf("%s\n", plaintext2)}
func NewOFB(b Block, iv []byte) Stream
NewOFB 返回一個(gè)在輸出反饋模式下使用分組密碼 b 進(jìn)行加密或解密的 Stream。初始化矢量 iv 的長(zhǎng)度必須等于 b 的塊大小。
package mainimport ("crypto/aes""crypto/cipher""crypto/rand""fmt""io")func main() { key := []byte("example key 1234") plaintext := []byte("some plaintext") block, err := aes.NewCipher(key)if err != nil {panic(err)}// IV需要獨(dú)特,但不安全。 所以這很常見// 將其包括在密文的開頭。 ciphertext := make([]byte, aes.BlockSize+len(plaintext)) iv := ciphertext[:aes.BlockSize]if _, err := io.ReadFull(rand.Reader, iv); err != nil {panic(err)} stream := cipher.NewOFB(block, iv) stream.XORKeyStream(ciphertext[aes.BlockSize:], plaintext)// 記住密文必須經(jīng)過認(rèn)證是很重要的// (即通過使用crypto/hmac)以及為了加密而被加密// 保持secure。// OFB模式對(duì)加密和解密都是一樣的,所以我們可以// 也使用 NewOFB 解密該密文。 plaintext2 := make([]byte, len(plaintext)) stream = cipher.NewOFB(block, iv) stream.XORKeyStream(plaintext2, ciphertext[aes.BlockSize:]) fmt.Printf("%s\n", plaintext2)}
StreamReader 將 Stream 封裝到 io.Reader 中。它調(diào)用 XORKeyStream 來處理通過的每一片數(shù)據(jù)。
type StreamReader struct { S Stream R io.Reader}
package mainimport ("crypto/aes""crypto/cipher""io""os")func main() { key := []byte("example key 1234") inFile, err := os.Open("encrypted-file")if err != nil {panic(err)} defer inFile.Close() block, err := aes.NewCipher(key)if err != nil {panic(err)}// 如果密鑰對(duì)于每個(gè)密文都是唯一的,那么可以使用零// IV.var iv [aes.BlockSize]byte stream := cipher.NewOFB(block, iv[:]) outFile, err := os.OpenFile("decrypted-file", os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0600)if err != nil {panic(err)} defer outFile.Close() reader := &cipher.StreamReader{S: stream, R: inFile}// 將輸入文件復(fù)制到輸出文件,隨著我們的解密。if _, err := io.Copy(outFile, reader); err != nil {panic(err)}// 請(qǐng)注意,這個(gè)例子是簡(jiǎn)單的,因?yàn)樗÷粤?/ 加密數(shù)據(jù)的認(rèn)證。 如果你真的使用// StreamReader以這種方式,攻擊者可以翻轉(zhuǎn)任意位// 輸出。}
func (r StreamReader) Read(dst []byte) (n int, err error)
StreamWriter 將 Stream 封裝到 io.Writer 中。它調(diào)用 XORKeyStream 來處理通過的每一片數(shù)據(jù)。如果任何寫入調(diào)用返回短,那么 StreamWriter 不同步并且必須被丟棄。StreamWriter 沒有內(nèi)部緩沖;不需要調(diào)用 Close 來刷新寫入數(shù)據(jù)。
type StreamWriter struct { S Stream W io.Writer Err error // unused}
package mainimport ("crypto/aes""crypto/cipher""io""os")func main() { key := []byte("example key 1234") inFile, err := os.Open("plaintext-file")if err != nil {panic(err)} defer inFile.Close() block, err := aes.NewCipher(key)if err != nil {panic(err)}// 如果密鑰對(duì)于每個(gè)密文都是唯一的,那么可以使用zero// IV.var iv [aes.BlockSize]byte stream := cipher.NewOFB(block, iv[:]) outFile, err := os.OpenFile("encrypted-file", os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0600)if err != nil {panic(err)} defer outFile.Close() writer := &cipher.StreamWriter{S: stream, W: outFile}// 將輸入文件復(fù)制到輸出文件,并隨時(shí)加密。if _, err := io.Copy(writer, inFile); err != nil {panic(err)}// 請(qǐng)注意,這個(gè)例子是簡(jiǎn)單的,因?yàn)樗÷粤?/ 加密數(shù)據(jù)的認(rèn)證。 如果你真的使用// StreamReader以這種方式,攻擊者可以翻轉(zhuǎn)任意位// 解密的結(jié)果。}
func (w StreamWriter) Close() error
Close 關(guān)閉底層 Writer 并返回其 Close 返回值,如果 Writer 也是 io.Closer。否則它返回零。
func (w StreamWriter) Write(src []byte) (n int, err error)