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