1  
     2  
     3  
     4  
     5  
     6  
     7  
     8  
     9  
    10  
    11  
    12  
    13  
    14  package blowfish 
    15  
    16  
    17  
    18  
    19  import "strconv"
    20  
    21  
    22  const BlockSize = 8
    23  
    24  
    25  type Cipher struct {
    26  	p              [18]uint32
    27  	s0, s1, s2, s3 [256]uint32
    28  }
    29  
    30  type KeySizeError int
    31  
    32  func (k KeySizeError) Error() string {
    33  	return "crypto/blowfish: invalid key size " + strconv.Itoa(int(k))
    34  }
    35  
    36  
    37  
    38  func NewCipher(key []byte) (*Cipher, error) {
    39  	var result Cipher
    40  	if k := len(key); k < 1 || k > 56 {
    41  		return nil, KeySizeError(k)
    42  	}
    43  	initCipher(&result)
    44  	ExpandKey(key, &result)
    45  	return &result, nil
    46  }
    47  
    48  
    49  
    50  
    51  
    52  func NewSaltedCipher(key, salt []byte) (*Cipher, error) {
    53  	if len(salt) == 0 {
    54  		return NewCipher(key)
    55  	}
    56  	var result Cipher
    57  	if k := len(key); k < 1 {
    58  		return nil, KeySizeError(k)
    59  	}
    60  	initCipher(&result)
    61  	expandKeyWithSalt(key, salt, &result)
    62  	return &result, nil
    63  }
    64  
    65  
    66  
    67  
    68  func (c *Cipher) BlockSize() int { return BlockSize }
    69  
    70  
    71  
    72  
    73  
    74  
    75  func (c *Cipher) Encrypt(dst, src []byte) {
    76  	l := uint32(src[0])<<24 | uint32(src[1])<<16 | uint32(src[2])<<8 | uint32(src[3])
    77  	r := uint32(src[4])<<24 | uint32(src[5])<<16 | uint32(src[6])<<8 | uint32(src[7])
    78  	l, r = encryptBlock(l, r, c)
    79  	dst[0], dst[1], dst[2], dst[3] = byte(l>>24), byte(l>>16), byte(l>>8), byte(l)
    80  	dst[4], dst[5], dst[6], dst[7] = byte(r>>24), byte(r>>16), byte(r>>8), byte(r)
    81  }
    82  
    83  
    84  
    85  func (c *Cipher) Decrypt(dst, src []byte) {
    86  	l := uint32(src[0])<<24 | uint32(src[1])<<16 | uint32(src[2])<<8 | uint32(src[3])
    87  	r := uint32(src[4])<<24 | uint32(src[5])<<16 | uint32(src[6])<<8 | uint32(src[7])
    88  	l, r = decryptBlock(l, r, c)
    89  	dst[0], dst[1], dst[2], dst[3] = byte(l>>24), byte(l>>16), byte(l>>8), byte(l)
    90  	dst[4], dst[5], dst[6], dst[7] = byte(r>>24), byte(r>>16), byte(r>>8), byte(r)
    91  }
    92  
    93  func initCipher(c *Cipher) {
    94  	copy(c.p[0:], p[0:])
    95  	copy(c.s0[0:], s0[0:])
    96  	copy(c.s1[0:], s1[0:])
    97  	copy(c.s2[0:], s2[0:])
    98  	copy(c.s3[0:], s3[0:])
    99  }
   100  
View as plain text