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 implements AES encryption (formerly Rijndael), as defined in
6 // U.S. Federal Information Processing Standards Publication 197.
7 //
8 // The AES operations in this package are not implemented using constant-time algorithms.
9 // An exception is when running on systems with enabled hardware support for AES
10 // that makes these operations constant-time. Examples include amd64 systems using AES-NI
11 // extensions and s390x systems using Message-Security-Assist extensions.
12 // On such systems, when the result of NewCipher is passed to cipher.NewGCM,
13 // the GHASH operation used by GCM is also constant-time.
14 package aes
15 16 import (
17 "crypto/cipher"
18 "crypto/internal/boring"
19 "crypto/internal/fips140/aes"
20 "strconv"
21 )
22 23 // The AES block size in bytes.
24 const BlockSize = 16
25 26 type KeySizeError int
27 28 func (k KeySizeError) Error() string {
29 var buf []byte
30 buf = append(buf, "crypto/aes: invalid key size "...)
31 buf = append(buf, strconv.Itoa(int(k))...)
32 return string(buf)
33 }
34 35 // NewCipher creates and returns a new [cipher.Block].
36 // The key argument must be the AES key,
37 // either 16, 24, or 32 bytes to select
38 // AES-128, AES-192, or AES-256.
39 func NewCipher(key []byte) (cipher.Block, error) {
40 k := len(key)
41 switch k {
42 default:
43 return nil, KeySizeError(k)
44 case 16, 24, 32:
45 break
46 }
47 if boring.Enabled {
48 return boring.NewAESCipher(key)
49 }
50 return aes.New(key)
51 }
52