File: blowfish.go

package info (click to toggle)
golang-github-viant-toolbox 0.33.2-4
  • links: PTS, VCS
  • area: main
  • in suites: bookworm, forky, sid, trixie
  • size: 1,280 kB
  • sloc: makefile: 16
file content (58 lines) | stat: -rw-r--r-- 1,440 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
package cred

import (
	"crypto/cipher"
	"golang.org/x/crypto/blowfish"
)

func blowfishChecksizeAndPad(padded []byte) []byte {
	modulus := len(padded) % blowfish.BlockSize
	if modulus != 0 {
		padlen := blowfish.BlockSize - modulus
		for i := 0; i < padlen; i++ {
			padded = append(padded, 0)
		}
	}
	return padded
}

type blowfishCipher struct {
	cipher *blowfish.Cipher
}

func (b *blowfishCipher) Encrypt(source []byte) []byte {
	paddedSource := blowfishChecksizeAndPad(source)
	ciphertext := make([]byte, blowfish.BlockSize+len(paddedSource))
	eiv := ciphertext[:blowfish.BlockSize]
	encodedBlackEncryptor := cipher.NewCBCEncrypter(b.cipher, eiv)
	encodedBlackEncryptor.CryptBlocks(ciphertext[blowfish.BlockSize:], paddedSource)
	return ciphertext
}

func (b *blowfishCipher) Decrypt(encrypted []byte) []byte {
	div := encrypted[:blowfish.BlockSize]
	decrypted := encrypted[blowfish.BlockSize:]
	if len(decrypted)%blowfish.BlockSize != 0 {
		panic("decrypted is not a multiple of blowfish.BlockSize")
	}
	dcbc := cipher.NewCBCDecrypter(b.cipher, div)
	dcbc.CryptBlocks(decrypted, decrypted)
	var result = make([]byte, 0)
	for _, b := range decrypted {
		if b == 0x0 {
			break
		}
		result = append(result, b)
	}
	return result
}

func NewBlowfishCipher(key []byte) (Cipher, error) {
	var passwordCipher, err = blowfish.NewCipher(key)
	if err != nil {
		return nil, err
	}
	return &blowfishCipher{
		cipher: passwordCipher,
	}, nil
}