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?
Blowfish is the first symmetric encryption algorithm created by Bruce Schneier in 1993. Symmetric encryption uses a single encryption key to both encrypt and decrypt data. The sensitive data and the symmetric encryption key are utilized within the encryption algorithm to turn the sensitive data into ciphertext.
Blowfish and AES, on the other hand, are Symmetric Ciphers, that is, it uses only one key for both encryption and decryption. While Blowfish is the Fastest Encryption algorithm [2] , AES is the most secure and efficient in encrypting data [3].
The Advanced Encryption Standard (AES, Rijndael) is a block cipher encryption and decryption algorithm, the most used encryption algorithm in the worldwide. The AES processes block of 128 bits using a secret key of 128, 192, or 256 bits.
AES and Blowfish is a symmetric key algorithm is very fast and powerful. With the utilization of a large block size of AES and Blowfish to encrypt keys, AES security will be much more robust and complicated to attacked. So, it will be difficult for hackers to perform Man in the Middle (MitM) attacks.
String Key = "Something";
byte[] KeyData = Key.getBytes();
SecretKeySpec KS = new SecretKeySpec(KeyData, "Blowfish");
Cipher cipher = Cipher.getInstance("Blowfish");
cipher.init(Cipher.ENCRYPT_MODE, KS);
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With