Source file src/pkg/crypto/cipher/cipher.go
1 // Copyright 2010 The Go Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style
3 // license that can be found in the LICENSE file.
4
5 // Package cipher implements standard block cipher modes that can be wrapped
6 // around low-level block cipher implementations.
7 // See http://csrc.nist.gov/groups/ST/toolkit/BCM/current_modes.html
8 // and NIST Special Publication 800-38A.
9 package cipher
10
11 // A Block represents an implementation of block cipher
12 // using a given key. It provides the capability to encrypt
13 // or decrypt individual blocks. The mode implementations
14 // extend that capability to streams of blocks.
15 type Block interface {
16 // BlockSize returns the cipher's block size.
17 BlockSize() int
18
19 // Encrypt encrypts the first block in src into dst.
20 // Dst and src may point at the same memory.
21 Encrypt(dst, src []byte)
22
23 // Decrypt decrypts the first block in src into dst.
24 // Dst and src may point at the same memory.
25 Decrypt(dst, src []byte)
26 }
27
28 // A Stream represents a stream cipher.
29 type Stream interface {
30 // XORKeyStream XORs each byte in the given slice with a byte from the
31 // cipher's key stream. Dst and src may point to the same memory.
32 XORKeyStream(dst, src []byte)
33 }
34
35 // A BlockMode represents a block cipher running in a block-based mode (CBC,
36 // ECB etc).
37 type BlockMode interface {
38 // BlockSize returns the mode's block size.
39 BlockSize() int
40
41 // CryptBlocks encrypts or decrypts a number of blocks. The length of
42 // src must be a multiple of the block size. Dst and src may point to
43 // the same memory.
44 CryptBlocks(dst, src []byte)
45 }
46
47 // Utility routines
48
49 func shift1(dst, src []byte) byte {
50 var b byte
51 for i := len(src) - 1; i >= 0; i-- {
52 bb := src[i] >> 7
53 dst[i] = src[i]<<1 | b
54 b = bb
55 }
56 return b
57 }
58
59 func dup(p []byte) []byte {
60 q := make([]byte, len(p))
61 copy(q, p)
62 return q
63 }