15

以下代码适用于我使用 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

4 回答 4

31
String Key = "Something";
byte[] KeyData = Key.getBytes();
SecretKeySpec KS = new SecretKeySpec(KeyData, "Blowfish");
Cipher cipher = Cipher.getInstance("Blowfish");
cipher.init(Cipher.ENCRYPT_MODE, KS);
于 2011-03-09T11:33:53.867 回答
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);
于 2016-02-10T14:57:52.900 回答
0

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

于 2013-03-19T18:11:36.757 回答
0

你也可以试试这个

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

还有一点在这里

于 2013-08-02T12:18:36.780 回答