使用Java中的BlowFish加密

时间:2011-03-09 11:13:08

标签: 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());

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

4 个答案:

答案 0 :(得分:27)

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

答案 1 :(得分:1)

   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);

答案 2 :(得分:0)

Blowfish的密钥大小必须为32 - 448位。所以有必要根据位数(32位为4字节)制作一个字节数组,反之亦然。

答案 3 :(得分:0)

你也可以试试这个

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

再多一点here