关于javax.crypto的使用,这里不再介绍,参考上一篇blog。
这里说一下另一个问题。
在使用这个密码包的时候,以上一篇中代码所示,通过接口keygen.generateKey()生成的密钥每次都会重新生成,导致上一篇中代码只能够作为demo演示而用,在实际使用中则出现很多问题。
以Blowfish为例,如果能够按照下面的形式封装和使用,则非常好了。
String sk = BlowfishUtil.generatorKey();
BlowfishUtil u = new BlowfishUtil(sk);
String cipher = u.encrypt(msg);String plain = u.decrypt(cipher);
好了,废话不多说,直接上code。
package encryption_schema;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.KeyGenerator;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import utils.Base64Utils;
public class BlowFishUtil {
// SecretKey 负责保存对称密钥
private SecretKey deskey;
// Cipher负责完成加密或解密工作
private Cipher c;
// 该字节数组负责保存加密的结果
private byte[] cipherByte;
public BlowFishUtil(String key) throws NoSuchAlgorithmException, NoSuchPaddingException {
byte[] bKey = Base64Utils.base64Decode(key);
deskey = new SecretKeySpec(bKey, "Blo