cipher.go 1.6 KB

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