// Copyright 2009 The Go Authors. All rights reserved.// Use of this source code is governed by a BSD-style// license that can be found in the LICENSE file.// Counter (CTR) mode.// CTR converts a block cipher into a stream cipher by// repeatedly encrypting an incrementing counter and// xoring the resulting stream of data with the input.// See NIST SP 800-38A, pp 13-15package cipherimport ()typectrstruct {bBlockctr []byteout []byteoutUsedint}conststreamBufferSize = 512// ctrAble is an interface implemented by ciphers that have a specific optimized// implementation of CTR, like crypto/aes. NewCTR will check for this interface// and return the specific Stream if found.typectrAbleinterface {NewCTR(iv []byte) Stream}// NewCTR returns a Stream which encrypts/decrypts using the given Block in// counter mode. The length of iv must be the same as the Block's block size.func ( Block, []byte) Stream {if , := .(ctrAble); {return .NewCTR() }iflen() != .BlockSize() {panic("cipher.NewCTR: IV length must equal block size") } := streamBufferSizeif < .BlockSize() { = .BlockSize() }return &ctr{b: ,ctr: bytes.Clone(),out: make([]byte, 0, ),outUsed: 0, }}func ( *ctr) () { := len(.out) - .outUsedcopy(.out, .out[.outUsed:]) .out = .out[:cap(.out)] := .b.BlockSize()for <= len(.out)- { .b.Encrypt(.out[:], .ctr) += // Increment counterfor := len(.ctr) - 1; >= 0; -- { .ctr[]++if .ctr[] != 0 {break } } } .out = .out[:] .outUsed = 0}func ( *ctr) (, []byte) {iflen() < len() {panic("crypto/cipher: output smaller than input") }ifalias.InexactOverlap([:len()], ) {panic("crypto/cipher: invalid buffer overlap") }forlen() > 0 {if .outUsed >= len(.out)-.b.BlockSize() { .refill() } := subtle.XORBytes(, , .out[.outUsed:]) = [:] = [:] .outUsed += }}
The pages are generated with Goldsv0.6.7. (GOOS=linux GOARCH=amd64)
Golds is a Go 101 project developed by Tapir Liu.
PR and bug reports are welcome and can be submitted to the issue list.
Please follow @Go100and1 (reachable from the left QR code) to get the latest news of Golds.