使用Java中的BlowFish加密

以下代码可以正常使用BlowFish加密来加密字符串。

// create a key generator based upon the Blowfish cipher KeyGenerator keygenerator = KeyGenerator.getInstance("Blowfish"); // create a key SecretKey secretkey = keygenerator.generateKey(); // create a cipher based upon Blowfish Cipher cipher = Cipher.getInstance("Blowfish"); // initialise cipher to with secret key cipher.init(Cipher.ENCRYPT_MODE, secretkey); // get the text to encrypt String inputText = "MyTextToEncrypt"; // encrypt message byte[] encrypted = cipher.doFinal(inputText.getBytes()); 

如果我想定义自己的密钥,我该怎么做?

 String Key = "Something"; byte[] KeyData = Key.getBytes(); SecretKeySpec KS = new SecretKeySpec(KeyData, "Blowfish"); Cipher cipher = Cipher.getInstance("Blowfish"); cipher.init(Cipher.ENCRYPT_MODE, KS); 

Blowfish的密钥大小必须为32 – 448位。 因此,有必要根据位数(32位为4字节)制作字节数组,反之亦然。

你也可以试试这个

 String key = "you_key_here"; SecretKey secret_key = new SecretKeySpec(key.getBytes(), ALGORITM); 

还有一点点。

  String strkey="MY KEY"; SecretKeySpec key = new SecretKeySpec(strkey.getBytes("UTF-8"), "Blowfish"); Cipher cipher = Cipher.getInstance("Blowfish"); if ( cipher == null || key == null) { throw new Exception("Invalid key or cypher"); } cipher.init(Cipher.ENCRYPT_MODE, key); String encryptedData =new String(cipher.doFinal(to_encrypt.getBytes("UTF-8")); 

解密:

  SecretKeySpec key = new SecretKeySpec(strkey.getBytes("UTF-8"), "Blowfish"); Cipher cipher = Cipher.getInstance("Blowfish"); cipher.init(Cipher.DECRYPT_MODE, key); byte[] decrypted = cipher.doFinal(encryptedData); return new String(decrypted);