summaryrefslogtreecommitdiff
path: root/devdocs/go/crypto%2Fcipher%2Findex.html
blob: 4abc775c446967a256ea80daf60914def7769a9b (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
<h1> Package cipher  </h1>     <ul id="short-nav">
<li><code>import "crypto/cipher"</code></li>
<li><a href="#pkg-overview" class="overviewLink">Overview</a></li>
<li><a href="#pkg-index" class="indexLink">Index</a></li>
<li><a href="#pkg-examples" class="examplesLink">Examples</a></li>
</ul>     <h2 id="pkg-overview">Overview </h2> <p>Package cipher implements standard block cipher modes that can be wrapped around low-level block cipher implementations. See <a href="https://csrc.nist.gov/groups/ST/toolkit/BCM/current_modes.html">https://csrc.nist.gov/groups/ST/toolkit/BCM/current_modes.html</a> and NIST Special Publication 800-38A. </p>     <h2 id="pkg-index">Index </h2>  <ul id="manual-nav">
<li><a href="#AEAD">type AEAD</a></li>
<li> <a href="#NewGCM">func NewGCM(cipher Block) (AEAD, error)</a>
</li>
<li> <a href="#NewGCMWithNonceSize">func NewGCMWithNonceSize(cipher Block, size int) (AEAD, error)</a>
</li>
<li> <a href="#NewGCMWithTagSize">func NewGCMWithTagSize(cipher Block, tagSize int) (AEAD, error)</a>
</li>
<li><a href="#Block">type Block</a></li>
<li><a href="#BlockMode">type BlockMode</a></li>
<li> <a href="#NewCBCDecrypter">func NewCBCDecrypter(b Block, iv []byte) BlockMode</a>
</li>
<li> <a href="#NewCBCEncrypter">func NewCBCEncrypter(b Block, iv []byte) BlockMode</a>
</li>
<li><a href="#Stream">type Stream</a></li>
<li> <a href="#NewCFBDecrypter">func NewCFBDecrypter(block Block, iv []byte) Stream</a>
</li>
<li> <a href="#NewCFBEncrypter">func NewCFBEncrypter(block Block, iv []byte) Stream</a>
</li>
<li> <a href="#NewCTR">func NewCTR(block Block, iv []byte) Stream</a>
</li>
<li> <a href="#NewOFB">func NewOFB(b Block, iv []byte) Stream</a>
</li>
<li><a href="#StreamReader">type StreamReader</a></li>
<li> <a href="#StreamReader.Read">func (r StreamReader) Read(dst []byte) (n int, err error)</a>
</li>
<li><a href="#StreamWriter">type StreamWriter</a></li>
<li> <a href="#StreamWriter.Close">func (w StreamWriter) Close() error</a>
</li>
<li> <a href="#StreamWriter.Write">func (w StreamWriter) Write(src []byte) (n int, err error)</a>
</li>
</ul> <div id="pkg-examples"> <h3>Examples</h3>  <dl> <dd><a class="exampleLink" href="#example_NewCBCDecrypter">NewCBCDecrypter</a></dd> <dd><a class="exampleLink" href="#example_NewCBCEncrypter">NewCBCEncrypter</a></dd> <dd><a class="exampleLink" href="#example_NewCFBDecrypter">NewCFBDecrypter</a></dd> <dd><a class="exampleLink" href="#example_NewCFBEncrypter">NewCFBEncrypter</a></dd> <dd><a class="exampleLink" href="#example_NewCTR">NewCTR</a></dd> <dd><a class="exampleLink" href="#example_NewGCM_decrypt">NewGCM (Decrypt)</a></dd> <dd><a class="exampleLink" href="#example_NewGCM_encrypt">NewGCM (Encrypt)</a></dd> <dd><a class="exampleLink" href="#example_NewOFB">NewOFB</a></dd> <dd><a class="exampleLink" href="#example_StreamReader">StreamReader</a></dd> <dd><a class="exampleLink" href="#example_StreamWriter">StreamWriter</a></dd> </dl> </div> <h3>Package files</h3> <p>  <span>cbc.go</span> <span>cfb.go</span> <span>cipher.go</span> <span>ctr.go</span> <span>gcm.go</span> <span>io.go</span> <span>ofb.go</span>  </p>   <h2 id="AEAD">type <span>AEAD</span>  <span title="Added in Go 1.2">1.2</span> </h2> <p>AEAD is a cipher mode providing authenticated encryption with associated data. For a description of the methodology, see <a href="https://en.wikipedia.org/wiki/Authenticated_encryption">https://en.wikipedia.org/wiki/Authenticated_encryption</a>. </p>
<pre data-language="go">type AEAD interface {
    // NonceSize returns the size of the nonce that must be passed to Seal
    // and Open.
    NonceSize() int

    // Overhead returns the maximum difference between the lengths of a
    // plaintext and its ciphertext.
    Overhead() int

    // Seal encrypts and authenticates plaintext, authenticates the
    // additional data and appends the result to dst, returning the updated
    // slice. The nonce must be NonceSize() bytes long and unique for all
    // time, for a given key.
    //
    // To reuse plaintext's storage for the encrypted output, use plaintext[:0]
    // as dst. Otherwise, the remaining capacity of dst must not overlap plaintext.
    Seal(dst, nonce, plaintext, additionalData []byte) []byte

    // Open decrypts and authenticates ciphertext, authenticates the
    // additional data and, if successful, appends the resulting plaintext
    // to dst, returning the updated slice. The nonce must be NonceSize()
    // bytes long and both it and the additional data must match the
    // value passed to Seal.
    //
    // To reuse ciphertext's storage for the decrypted output, use ciphertext[:0]
    // as dst. Otherwise, the remaining capacity of dst must not overlap plaintext.
    //
    // Even if the function fails, the contents of dst, up to its capacity,
    // may be overwritten.
    Open(dst, nonce, ciphertext, additionalData []byte) ([]byte, error)
}</pre> <h3 id="NewGCM">func <span>NewGCM</span>  <span title="Added in Go 1.2">1.2</span> </h3> <pre data-language="go">func NewGCM(cipher Block) (AEAD, error)</pre> <p>NewGCM returns the given 128-bit, block cipher wrapped in Galois Counter Mode with the standard nonce length. </p>
<p>In general, the GHASH operation performed by this implementation of GCM is not constant-time. An exception is when the underlying <a href="#Block">Block</a> was created by aes.NewCipher on systems with hardware support for AES. See the <span>crypto/aes</span> package documentation for details. </p>   <h4 id="example_NewGCM_decrypt"> <span class="text">Example (Decrypt)</span>
</h4> <p>Code:</p> <pre class="code" data-language="go">// Load your secret key from a safe place and reuse it across multiple
// Seal/Open 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.
// When decoded the key should be 16 bytes (AES-128) or 32 (AES-256).
key, _ := hex.DecodeString("6368616e676520746869732070617373776f726420746f206120736563726574")
ciphertext, _ := hex.DecodeString("c3aaa29f002ca75870806e44086700f62ce4d43e902b3888e23ceff797a7a471")
nonce, _ := hex.DecodeString("64a9433eae7ccceee2fc0eda")

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)
</pre> <p>Output:</p> <pre class="output" data-language="go">exampleplaintext
</pre>      <h4 id="example_NewGCM_encrypt"> <span class="text">Example (Encrypt)</span>
</h4> <p>Code:</p> <pre class="code" data-language="go">
// Load your secret key from a safe place and reuse it across multiple
// Seal/Open 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.
// When decoded the key should be 16 bytes (AES-128) or 32 (AES-256).
key, _ := hex.DecodeString("6368616e676520746869732070617373776f726420746f206120736563726574")
plaintext := []byte("exampleplaintext")

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

// Never use more than 2^32 random nonces with a given key because of the risk of a repeat.
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)
</pre>   <h3 id="NewGCMWithNonceSize">func <span>NewGCMWithNonceSize</span>  <span title="Added in Go 1.5">1.5</span> </h3> <pre data-language="go">func NewGCMWithNonceSize(cipher Block, size int) (AEAD, error)</pre> <p>NewGCMWithNonceSize returns the given 128-bit, block cipher wrapped in Galois Counter Mode, which accepts nonces of the given length. The length must not be zero. </p>
<p>Only use this function if you require compatibility with an existing cryptosystem that uses non-standard nonce lengths. All other users should use <a href="#NewGCM">NewGCM</a>, which is faster and more resistant to misuse. </p>
<h3 id="NewGCMWithTagSize">func <span>NewGCMWithTagSize</span>  <span title="Added in Go 1.11">1.11</span> </h3> <pre data-language="go">func NewGCMWithTagSize(cipher Block, tagSize int) (AEAD, error)</pre> <p>NewGCMWithTagSize returns the given 128-bit, block cipher wrapped in Galois Counter Mode, which generates tags with the given length. </p>
<p>Tag sizes between 12 and 16 bytes are allowed. </p>
<p>Only use this function if you require compatibility with an existing cryptosystem that uses non-standard tag lengths. All other users should use <a href="#NewGCM">NewGCM</a>, which is more resistant to misuse. </p>
<h2 id="Block">type <span>Block</span>  </h2> <p>A Block represents an implementation of block cipher using a given key. It provides the capability to encrypt or decrypt individual blocks. The mode implementations extend that capability to streams of blocks. </p>
<pre data-language="go">type Block interface {
    // BlockSize returns the cipher's block size.
    BlockSize() int

    // Encrypt encrypts the first block in src into dst.
    // Dst and src must overlap entirely or not at all.
    Encrypt(dst, src []byte)

    // Decrypt decrypts the first block in src into dst.
    // Dst and src must overlap entirely or not at all.
    Decrypt(dst, src []byte)
}</pre> <h2 id="BlockMode">type <span>BlockMode</span>  </h2> <p>A BlockMode represents a block cipher running in a block-based mode (CBC, ECB etc). </p>
<pre data-language="go">type BlockMode interface {
    // BlockSize returns the mode's block size.
    BlockSize() int

    // CryptBlocks encrypts or decrypts a number of blocks. The length of
    // src must be a multiple of the block size. Dst and src must overlap
    // entirely or not at all.
    //
    // If len(dst) &lt; len(src), CryptBlocks should panic. It is acceptable
    // to pass a dst bigger than src, and in that case, CryptBlocks will
    // only update dst[:len(src)] and will not touch the rest of dst.
    //
    // Multiple calls to CryptBlocks behave as if the concatenation of
    // the src buffers was passed in a single run. That is, BlockMode
    // maintains state and does not reset at each CryptBlocks call.
    CryptBlocks(dst, src []byte)
}</pre> <h3 id="NewCBCDecrypter">func <span>NewCBCDecrypter</span>  </h3> <pre data-language="go">func NewCBCDecrypter(b Block, iv []byte) BlockMode</pre> <p>NewCBCDecrypter returns a BlockMode which decrypts in cipher block chaining mode, using the given Block. The length of iv must be the same as the Block's block size and must match the iv used to encrypt the data. </p>   <h4 id="example_NewCBCDecrypter"> <span class="text">Example</span>
</h4> <p>Code:</p> <pre class="code" data-language="go">// 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) &lt; 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)
</pre> <p>Output:</p> <pre class="output" data-language="go">exampleplaintext
</pre>   <h3 id="NewCBCEncrypter">func <span>NewCBCEncrypter</span>  </h3> <pre data-language="go">func NewCBCEncrypter(b Block, iv []byte) BlockMode</pre> <p>NewCBCEncrypter returns a BlockMode which encrypts in cipher block chaining mode, using the given Block. The length of iv must be the same as the Block's block size. </p>   <h4 id="example_NewCBCEncrypter"> <span class="text">Example</span>
</h4> <p>Code:</p> <pre class="code" data-language="go">
// 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)
</pre>   <h2 id="Stream">type <span>Stream</span>  </h2> <p>A Stream represents a stream cipher. </p>
<pre data-language="go">type Stream interface {
    // XORKeyStream XORs each byte in the given slice with a byte from the
    // cipher's key stream. Dst and src must overlap entirely or not at all.
    //
    // If len(dst) &lt; len(src), XORKeyStream should panic. It is acceptable
    // to pass a dst bigger than src, and in that case, XORKeyStream will
    // only update dst[:len(src)] and will not touch the rest of dst.
    //
    // Multiple calls to XORKeyStream behave as if the concatenation of
    // the src buffers was passed in a single run. That is, Stream
    // maintains state and does not reset at each XORKeyStream call.
    XORKeyStream(dst, src []byte)
}</pre> <h3 id="NewCFBDecrypter">func <span>NewCFBDecrypter</span>  </h3> <pre data-language="go">func NewCFBDecrypter(block Block, iv []byte) Stream</pre> <p>NewCFBDecrypter returns a <a href="#Stream">Stream</a> which decrypts with cipher feedback mode, using the given <a href="#Block">Block</a>. The iv must be the same length as the <a href="#Block">Block</a>'s block size. </p>   <h4 id="example_NewCFBDecrypter"> <span class="text">Example</span>
</h4> <p>Code:</p> <pre class="code" data-language="go">// 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("7dd015f06bec7f1b8f6559dad89f4131da62261786845100056b353194ad")

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) &lt; aes.BlockSize {
    panic("ciphertext too short")
}
iv := ciphertext[:aes.BlockSize]
ciphertext = ciphertext[aes.BlockSize:]

stream := cipher.NewCFBDecrypter(block, iv)

// XORKeyStream can work in-place if the two arguments are the same.
stream.XORKeyStream(ciphertext, ciphertext)
fmt.Printf("%s", ciphertext)
</pre> <p>Output:</p> <pre class="output" data-language="go">some plaintext
</pre>   <h3 id="NewCFBEncrypter">func <span>NewCFBEncrypter</span>  </h3> <pre data-language="go">func NewCFBEncrypter(block Block, iv []byte) Stream</pre> <p>NewCFBEncrypter returns a <a href="#Stream">Stream</a> which encrypts with cipher feedback mode, using the given <a href="#Block">Block</a>. The iv must be the same length as the <a href="#Block">Block</a>'s block size. </p>   <h4 id="example_NewCFBEncrypter"> <span class="text">Example</span>
</h4> <p>Code:</p> <pre class="code" data-language="go">
// 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("some plaintext")

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

stream := cipher.NewCFBEncrypter(block, iv)
stream.XORKeyStream(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)
</pre>   <h3 id="NewCTR">func <span>NewCTR</span>  </h3> <pre data-language="go">func NewCTR(block Block, iv []byte) Stream</pre> <p>NewCTR returns a <a href="#Stream">Stream</a> which encrypts/decrypts using the given <a href="#Block">Block</a> in counter mode. The length of iv must be the same as the <a href="#Block">Block</a>'s block size. </p>   <h4 id="example_NewCTR"> <span class="text">Example</span>
</h4> <p>Code:</p> <pre class="code" data-language="go">// 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("some plaintext")

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

stream := cipher.NewCTR(block, iv)
stream.XORKeyStream(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.

// CTR mode is the same for both encryption and decryption, so we can
// also decrypt that ciphertext with NewCTR.

plaintext2 := make([]byte, len(plaintext))
stream = cipher.NewCTR(block, iv)
stream.XORKeyStream(plaintext2, ciphertext[aes.BlockSize:])

fmt.Printf("%s\n", plaintext2)
</pre> <p>Output:</p> <pre class="output" data-language="go">some plaintext
</pre>   <h3 id="NewOFB">func <span>NewOFB</span>  </h3> <pre data-language="go">func NewOFB(b Block, iv []byte) Stream</pre> <p>NewOFB returns a <a href="#Stream">Stream</a> that encrypts or decrypts using the block cipher b in output feedback mode. The initialization vector iv's length must be equal to b's block size. </p>   <h4 id="example_NewOFB"> <span class="text">Example</span>
</h4> <p>Code:</p> <pre class="code" data-language="go">// 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("some plaintext")

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

stream := cipher.NewOFB(block, iv)
stream.XORKeyStream(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.

// OFB mode is the same for both encryption and decryption, so we can
// also decrypt that ciphertext with NewOFB.

plaintext2 := make([]byte, len(plaintext))
stream = cipher.NewOFB(block, iv)
stream.XORKeyStream(plaintext2, ciphertext[aes.BlockSize:])

fmt.Printf("%s\n", plaintext2)
</pre> <p>Output:</p> <pre class="output" data-language="go">some plaintext
</pre>   <h2 id="StreamReader">type <span>StreamReader</span>  </h2> <p>StreamReader wraps a <a href="#Stream">Stream</a> into an <span>io.Reader</span>. It calls XORKeyStream to process each slice of data which passes through. </p>
<pre data-language="go">type StreamReader struct {
    S Stream
    R io.Reader
}
</pre>    <h4 id="example_StreamReader"> <span class="text">Example</span>
</h4> <p>Code:</p> <pre class="code" data-language="go">// 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")

encrypted, _ := hex.DecodeString("cf0495cc6f75dafc23948538e79904a9")
bReader := bytes.NewReader(encrypted)

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

// If the key is unique for each ciphertext, then it's ok to use a zero
// IV.
var iv [aes.BlockSize]byte
stream := cipher.NewOFB(block, iv[:])

reader := &amp;cipher.StreamReader{S: stream, R: bReader}
// Copy the input to the output stream, decrypting as we go.
if _, err := io.Copy(os.Stdout, reader); err != nil {
    panic(err)
}

// Note that this example is simplistic in that it omits any
// authentication of the encrypted data. If you were actually to use
// StreamReader in this manner, an attacker could flip arbitrary bits in
// the output.

</pre> <p>Output:</p> <pre class="output" data-language="go">some secret text
</pre>   <h3 id="StreamReader.Read">func (StreamReader) <span>Read</span>  </h3> <pre data-language="go">func (r StreamReader) Read(dst []byte) (n int, err error)</pre> <h2 id="StreamWriter">type <span>StreamWriter</span>  </h2> <p>StreamWriter wraps a <a href="#Stream">Stream</a> into an io.Writer. It calls XORKeyStream to process each slice of data which passes through. If any <a href="#StreamWriter.Write">StreamWriter.Write</a> call returns short then the StreamWriter is out of sync and must be discarded. A StreamWriter has no internal buffering; <a href="#StreamWriter.Close">StreamWriter.Close</a> does not need to be called to flush write data. </p>
<pre data-language="go">type StreamWriter struct {
    S   Stream
    W   io.Writer
    Err error // unused
}
</pre>    <h4 id="example_StreamWriter"> <span class="text">Example</span>
</h4> <p>Code:</p> <pre class="code" data-language="go">// 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")

bReader := bytes.NewReader([]byte("some secret text"))

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

// If the key is unique for each ciphertext, then it's ok to use a zero
// IV.
var iv [aes.BlockSize]byte
stream := cipher.NewOFB(block, iv[:])

var out bytes.Buffer

writer := &amp;cipher.StreamWriter{S: stream, W: &amp;out}
// Copy the input to the output buffer, encrypting as we go.
if _, err := io.Copy(writer, bReader); err != nil {
    panic(err)
}

// Note that this example is simplistic in that it omits any
// authentication of the encrypted data. If you were actually to use
// StreamReader in this manner, an attacker could flip arbitrary bits in
// the decrypted result.

fmt.Printf("%x\n", out.Bytes())
</pre> <p>Output:</p> <pre class="output" data-language="go">cf0495cc6f75dafc23948538e79904a9
</pre>   <h3 id="StreamWriter.Close">func (StreamWriter) <span>Close</span>  </h3> <pre data-language="go">func (w StreamWriter) Close() error</pre> <p>Close closes the underlying Writer and returns its Close return value, if the Writer is also an io.Closer. Otherwise it returns nil. </p>
<h3 id="StreamWriter.Write">func (StreamWriter) <span>Write</span>  </h3> <pre data-language="go">func (w StreamWriter) Write(src []byte) (n int, err error)</pre><div class="_attribution">
  <p class="_attribution-p">
    &copy; Google, Inc.<br>Licensed under the Creative Commons Attribution License 3.0.<br>
    <a href="http://golang.org/pkg/crypto/cipher/" class="_attribution-link">http://golang.org/pkg/crypto/cipher/</a>
  </p>
</div>