...

Source file src/crypto/aes/cipher.go

Documentation: crypto/aes

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

View as plain text