Home | History | Annotate | Download | only in des
      1 // Copyright 2011 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 des
      6 
      7 import (
      8 	"crypto/cipher"
      9 	"strconv"
     10 )
     11 
     12 // The DES block size in bytes.
     13 const BlockSize = 8
     14 
     15 type KeySizeError int
     16 
     17 func (k KeySizeError) Error() string {
     18 	return "crypto/des: invalid key size " + strconv.Itoa(int(k))
     19 }
     20 
     21 // desCipher is an instance of DES encryption.
     22 type desCipher struct {
     23 	subkeys [16]uint64
     24 }
     25 
     26 // NewCipher creates and returns a new cipher.Block.
     27 func NewCipher(key []byte) (cipher.Block, error) {
     28 	if len(key) != 8 {
     29 		return nil, KeySizeError(len(key))
     30 	}
     31 
     32 	c := new(desCipher)
     33 	c.generateSubkeys(key)
     34 	return c, nil
     35 }
     36 
     37 func (c *desCipher) BlockSize() int { return BlockSize }
     38 
     39 func (c *desCipher) Encrypt(dst, src []byte) { encryptBlock(c.subkeys[:], dst, src) }
     40 
     41 func (c *desCipher) Decrypt(dst, src []byte) { decryptBlock(c.subkeys[:], dst, src) }
     42 
     43 // A tripleDESCipher is an instance of TripleDES encryption.
     44 type tripleDESCipher struct {
     45 	cipher1, cipher2, cipher3 desCipher
     46 }
     47 
     48 // NewTripleDESCipher creates and returns a new cipher.Block.
     49 func NewTripleDESCipher(key []byte) (cipher.Block, error) {
     50 	if len(key) != 24 {
     51 		return nil, KeySizeError(len(key))
     52 	}
     53 
     54 	c := new(tripleDESCipher)
     55 	c.cipher1.generateSubkeys(key[:8])
     56 	c.cipher2.generateSubkeys(key[8:16])
     57 	c.cipher3.generateSubkeys(key[16:])
     58 	return c, nil
     59 }
     60 
     61 func (c *tripleDESCipher) BlockSize() int { return BlockSize }
     62 
     63 func (c *tripleDESCipher) Encrypt(dst, src []byte) {
     64 	c.cipher1.Encrypt(dst, src)
     65 	c.cipher2.Decrypt(dst, dst)
     66 	c.cipher3.Encrypt(dst, dst)
     67 }
     68 
     69 func (c *tripleDESCipher) Decrypt(dst, src []byte) {
     70 	c.cipher3.Decrypt(dst, src)
     71 	c.cipher2.Encrypt(dst, dst)
     72 	c.cipher1.Decrypt(dst, dst)
     73 }
     74