Home | History | Annotate | Download | only in cipher
      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 	// If len(dst) < len(src), XORKeyStream should panic. It is acceptable
     33 	// to pass a dst bigger than src, and in that case, XORKeyStream will
     34 	// only update dst[:len(src)] and will not touch the rest of dst.
     35 	XORKeyStream(dst, src []byte)
     36 }
     37 
     38 // A BlockMode represents a block cipher running in a block-based mode (CBC,
     39 // ECB etc).
     40 type BlockMode interface {
     41 	// BlockSize returns the mode's block size.
     42 	BlockSize() int
     43 
     44 	// CryptBlocks encrypts or decrypts a number of blocks. The length of
     45 	// src must be a multiple of the block size. Dst and src may point to
     46 	// the same memory.
     47 	CryptBlocks(dst, src []byte)
     48 }
     49 
     50 // Utility routines
     51 
     52 func dup(p []byte) []byte {
     53 	q := make([]byte, len(p))
     54 	copy(q, p)
     55 	return q
     56 }
     57