Blowfish算法是由Bruce Schneier于1993年设计的一种对称密钥加密算法。它采用分组加密的方式,每次处理64比特的数据块,并使用一个变长的密钥(32到448比特)进行加密和解密操作。
以下使用java举例
通过javax.crypto包实现
package com.dreams.February;
import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.SecretKeySpec;
import java.util.Base64;
public class BlowfishExample {
public static void main(String[] args) throws Exception {
String message = "Hello, Dreams!";
String secretKey = "MySecretKey";
System.out.println("加密前: " + message);
byte[] keyData = secretKey.getBytes("UTF-8");
SecretKey key = new SecretKeySpec(keyData, "Blowfish");
// 加密
Cipher cipher = Cipher.getInstance("Blowfish/ECB/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, key);
byte[] encrypted = cipher.doFinal(message.getBytes("UTF-8"));
String encryptedText = Base64.getEncoder().encodeToString(encrypted);
System.out.println("加密后: " + encryptedText);
// 解密
cipher.init(Cipher.DECRYPT_MODE, key);
byte[] decrypted = cipher.doFinal(Base64.getDecoder().decode(encryptedText));
String decryptedText = new String(decrypted, "UTF-8");
System.out.println("解密后: " + decryptedText);
}
}运行如下:

如果在web服务中,我们不推荐使用Base64编码存储密码,这样就可以使用Blowfish密码加密
比如Spring Security框架提供BCryptPasswordEncoder用于对用户密码进行哈希加密和验证。
示例代码如下:
public static void main(String[] args) {
String password = "123456";
PasswordEncoder encoder = new BCryptPasswordEncoder();
for (int i = 0; i < 5; i++) {
// 加密密码
String encodedPassword = encoder.encode(password);
System.out.print("Encoded password: " + encodedPassword + " ");
// 验证密码
boolean isMatch = encoder.matches(password, encodedPassword);
System.out.println("Password match: " + isMatch);
}
}这里不需要指定secretKey,所以每次生成的加密都不一样
运行如下:

安全!


