Encryption with BlowFish in Java

本秂侑毒 提交于 2019-12-29 03:22:47

问题


Following code works fine for me to encrypt a string with the BlowFish encryption.

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

If I want to define my own secret key, how do I do that?


回答1:


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



回答2:


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

DECRYPTION:

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



回答3:


Key size of Blowfish must be 32 - 448 bit. So it is necessary to make a byte array according to the bit number (4 byte for 32 bit) and vice-verse.




回答4:


Also you can try this

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

and a little bit more here.



来源:https://stackoverflow.com/questions/5244950/encryption-with-blowfish-in-java

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!