github.com/yanyiwu/go@v0.0.0-20150106053140-03d6637dbb7f/src/crypto/aes/cipher.go (about)

     1  // Copyright 2009 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 aes
     6  
     7  import (
     8  	"crypto/cipher"
     9  	"strconv"
    10  )
    11  
    12  // The AES block size in bytes.
    13  const BlockSize = 16
    14  
    15  // A cipher is an instance of AES encryption using a particular key.
    16  type aesCipher struct {
    17  	enc []uint32
    18  	dec []uint32
    19  }
    20  
    21  type KeySizeError int
    22  
    23  func (k KeySizeError) Error() string {
    24  	return "crypto/aes: invalid key size " + strconv.Itoa(int(k))
    25  }
    26  
    27  // NewCipher creates and returns a new cipher.Block.
    28  // The key argument should be the AES key,
    29  // either 16, 24, or 32 bytes to select
    30  // AES-128, AES-192, or AES-256.
    31  func NewCipher(key []byte) (cipher.Block, error) {
    32  	k := len(key)
    33  	switch k {
    34  	default:
    35  		return nil, KeySizeError(k)
    36  	case 16, 24, 32:
    37  		break
    38  	}
    39  
    40  	n := k + 28
    41  	c := &aesCipher{make([]uint32, n), make([]uint32, n)}
    42  	expandKey(key, c.enc, c.dec)
    43  	return c, nil
    44  }
    45  
    46  func (c *aesCipher) BlockSize() int { return BlockSize }
    47  
    48  func (c *aesCipher) Encrypt(dst, src []byte) {
    49  	if len(src) < BlockSize {
    50  		panic("crypto/aes: input not full block")
    51  	}
    52  	if len(dst) < BlockSize {
    53  		panic("crypto/aes: output not full block")
    54  	}
    55  	encryptBlock(c.enc, dst, src)
    56  }
    57  
    58  func (c *aesCipher) Decrypt(dst, src []byte) {
    59  	if len(src) < BlockSize {
    60  		panic("crypto/aes: input not full block")
    61  	}
    62  	if len(dst) < BlockSize {
    63  		panic("crypto/aes: output not full block")
    64  	}
    65  	decryptBlock(c.dec, dst, src)
    66  }