1
// Copyright 2010 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.
5
// Package blowfish implements Bruce Schneier's Blowfish encryption algorithm.
6
package blowfish // import "golang.org/x/crypto/blowfish"
8
// The code is a port of Bruce Schneier's C implementation.
9
// See http://www.schneier.com/blowfish.html.
13
// The Blowfish block size in bytes.
16
// A Cipher is an instance of Blowfish encryption using a particular key.
19
s0, s1, s2, s3 [256]uint32
24
func (k KeySizeError) Error() string {
25
return "crypto/blowfish: invalid key size " + strconv.Itoa(int(k))
28
// NewCipher creates and returns a Cipher.
29
// The key argument should be the Blowfish key, from 1 to 56 bytes.
30
func NewCipher(key []byte) (*Cipher, error) {
32
if k := len(key); k < 1 || k > 56 {
33
return nil, KeySizeError(k)
36
ExpandKey(key, &result)
40
// NewSaltedCipher creates a returns a Cipher that folds a salt into its key
41
// schedule. For most purposes, NewCipher, instead of NewSaltedCipher, is
42
// sufficient and desirable. For bcrypt compatiblity, the key can be over 56
44
func NewSaltedCipher(key, salt []byte) (*Cipher, error) {
49
if k := len(key); k < 1 {
50
return nil, KeySizeError(k)
53
expandKeyWithSalt(key, salt, &result)
57
// BlockSize returns the Blowfish block size, 8 bytes.
58
// It is necessary to satisfy the Block interface in the
59
// package "crypto/cipher".
60
func (c *Cipher) BlockSize() int { return BlockSize }
62
// Encrypt encrypts the 8-byte buffer src using the key k
63
// and stores the result in dst.
64
// Note that for amounts of data larger than a block,
65
// it is not safe to just call Encrypt on successive blocks;
66
// instead, use an encryption mode like CBC (see crypto/cipher/cbc.go).
67
func (c *Cipher) Encrypt(dst, src []byte) {
68
l := uint32(src[0])<<24 | uint32(src[1])<<16 | uint32(src[2])<<8 | uint32(src[3])
69
r := uint32(src[4])<<24 | uint32(src[5])<<16 | uint32(src[6])<<8 | uint32(src[7])
70
l, r = encryptBlock(l, r, c)
71
dst[0], dst[1], dst[2], dst[3] = byte(l>>24), byte(l>>16), byte(l>>8), byte(l)
72
dst[4], dst[5], dst[6], dst[7] = byte(r>>24), byte(r>>16), byte(r>>8), byte(r)
75
// Decrypt decrypts the 8-byte buffer src using the key k
76
// and stores the result in dst.
77
func (c *Cipher) Decrypt(dst, src []byte) {
78
l := uint32(src[0])<<24 | uint32(src[1])<<16 | uint32(src[2])<<8 | uint32(src[3])
79
r := uint32(src[4])<<24 | uint32(src[5])<<16 | uint32(src[6])<<8 | uint32(src[7])
80
l, r = decryptBlock(l, r, c)
81
dst[0], dst[1], dst[2], dst[3] = byte(l>>24), byte(l>>16), byte(l>>8), byte(l)
82
dst[4], dst[5], dst[6], dst[7] = byte(r>>24), byte(r>>16), byte(r>>8), byte(r)
85
func initCipher(c *Cipher) {
87
copy(c.s0[0:], s0[0:])
88
copy(c.s1[0:], s1[0:])
89
copy(c.s2[0:], s2[0:])
90
copy(c.s3[0:], s3[0:])