package util

import ( "crypto/cipher" "crypto/rand" "errors" "fmt"

"golang.org/x/crypto/blowfish"

)

// generateKey generates a new Blowfish key with the given key size in bytes. func generateKey(keySize int) ([]byte, error) { key := make([]byte, keySize) _, err := rand.Read(key) if err != nil { return nil, fmt.Errorf("failed to generate key: %w", err) } return key, nil }

// newCipher returns a new Blowfish cipher block. func newCipher(key []byte) (cipher.Block, error) { cipher, err := blowfish.NewCipher(key) if err != nil { return nil, fmt.Errorf("failed to create Blowfish cipher: %w", err) } return cipher, nil }

// E encrypts the plain text using Blowfish encryption with the given key and nonce. func E(plain []byte, key, nonce []byte) ([]byte, error) { // Generate a new Blowfish key if not provided. if key == nil { var err error key, err = generateKey(16) if err != nil { return nil, fmt.Errorf("failed to generate key: %w", err) } }

// Generate a new nonce if not provided.
if nonce == nil {
	nonce = make([]byte, 12)
	_, err := rand.Read(nonce)
	if err != nil {
		return nil, fmt.Errorf("failed to generate nonce: %w", err)
	}
}

cipherBlock, err := newCipher(key)
if err != nil {
	return nil, fmt.Errorf("failed to create Blowfish cipher block: %w", err)
}

// Use CTR mode for encryption.
stream := cipher.NewCTR(cipherBlock, nonce)

// Encrypt the plain text.
cipherText := make([]byte, len(plain))
stream.XORKeyStream(cipherText, plain)

// Prepend the nonce to the cipher text for use in decryption.
return append(nonce, cipherText...), nil

}

// D decrypts the cipher text using Blowfish decryption with the given key and nonce. func D(cipherText []byte, key, nonce []byte) ([]byte, error) { if len(cipherText) < 12 { return nil, errors.New("cipher text too short") }

// Extract the nonce and cipher text from the input.
nonce = cipherText[:12]
cipherText = cipherText[12:]

cipherBlock, err := newCipher(key)
if err != nil {
	return nil, fmt.Errorf("failed to create Blowfish cipher block: %w", err)
}

// Use CTR mode for decryption.
stream := cipher.NewCTR(cipherBlock, nonce)

// Decrypt the cipher text.
plainText := make([]byte, len(cipherText))
stream.XORKeyStream(plainText, cipherText)

return plainText, nil

}

将加密方式替换为Blowfish加密算法package utilimport 	cryptoaes	cryptocipherfunc newAeadkey byte cipherAEAD error 	block err = aesNewCipherkey	if err != nil 		return nil err		aead err = cipherNewGCMblock	if err !=

原文地址: http://www.cveoy.top/t/topic/ZQZ 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录