The Go Programming Language

Source file src/pkg/crypto/aes/cipher.go

     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		"os"
     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 Cipher struct {
    17		enc []uint32
    18		dec []uint32
    19	}
    20	
    21	type KeySizeError int
    22	
    23	func (k KeySizeError) String() string {
    24		return "crypto/aes: invalid key size " + strconv.Itoa(int(k))
    25	}
    26	
    27	// NewCipher creates and returns a new Cipher.
    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, os.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 := &Cipher{make([]uint32, n), make([]uint32, n)}
    42		expandKey(key, c.enc, c.dec)
    43		return c, nil
    44	}
    45	
    46	// BlockSize returns the AES block size, 16 bytes.
    47	// It is necessary to satisfy the Cipher interface in the
    48	// package "crypto/cipher".
    49	func (c *Cipher) BlockSize() int { return BlockSize }
    50	
    51	// Encrypt encrypts the 16-byte buffer src using the key k
    52	// and stores the result in dst.
    53	// Note that for amounts of data larger than a block,
    54	// it is not safe to just call Encrypt on successive blocks;
    55	// instead, use an encryption mode like CBC (see crypto/cipher/cbc.go).
    56	func (c *Cipher) Encrypt(dst, src []byte) { encryptBlock(c.enc, dst, src) }
    57	
    58	// Decrypt decrypts the 16-byte buffer src using the key k
    59	// and stores the result in dst.
    60	func (c *Cipher) Decrypt(dst, src []byte) { decryptBlock(c.dec, dst, src) }
    61	
    62	// Reset zeros the key data, so that it will no longer
    63	// appear in the process's memory.
    64	func (c *Cipher) Reset() {
    65		for i := 0; i < len(c.enc); i++ {
    66			c.enc[i] = 0
    67		}
    68		for i := 0; i < len(c.dec); i++ {
    69			c.dec[i] = 0
    70		}
    71	}

release.r60.3. Except as noted, this content is licensed under a Creative Commons Attribution 3.0 License.