Java - Blowfish Encryption and decryption Example

Blowfish is a symmetric-key block cipher, designed in 1993 by Bruce Schneier and included in many cipher suites and encryption products. Blowfish provides a good encryption rate in software and no effective cryptanalysis of it has been found to date. However, the Advanced Encryption Standard (AES) now receives more attention, and Schneier recommends Twofish for modern applications.


Example 1: Encryption and decryption using Blowfish
import java.io.UnsupportedEncodingException;
import java.nio.charset.Charset;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.Base64;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.SecretKeySpec;

/**
* This program demonstrates how to encrypt/decrypt
* input using the Blowfish
* Cipher with the Java Cryptography.
*/
public class BlowfishDemo {

public String encrypt(String password, String key) throws
NoSuchAlgorithmException, NoSuchPaddingException,
InvalidKeyException, IllegalBlockSizeException,
BadPaddingException, UnsupportedEncodingException {
byte[] KeyData = key.getBytes();
SecretKeySpec KS = new SecretKeySpec(KeyData, "Blowfish");
Cipher cipher = Cipher.getInstance("Blowfish");
cipher.init(Cipher.ENCRYPT_MODE, KS);
String encryptedtext = Base64.getEncoder().
encodeToString(cipher.doFinal(password.getBytes("UTF-8")));
return encryptedtext;

}

public String decrypt(String encryptedtext, String key)
throws NoSuchAlgorithmException, NoSuchPaddingException,
InvalidKeyException, IllegalBlockSizeException,
BadPaddingException {
byte[] KeyData = key.getBytes();
SecretKeySpec KS = new SecretKeySpec(KeyData, "Blowfish");
byte[] ecryptedtexttobytes = Base64.getDecoder().
decode(encryptedtext);
Cipher cipher = Cipher.getInstance("Blowfish");
cipher.init(Cipher.DECRYPT_MODE, KS);
byte[] decrypted = cipher.doFinal(ecryptedtexttobytes);
String decryptedString =
new String(decrypted, Charset.forName("UTF-8"));
return decryptedString;

}

public static void main(String[] args) throws Exception {
final String password = "Knf@123";
final String key = "knowledgefactory";
System.out.println("Password: " + password);
BlowfishDemo obj = new BlowfishDemo();
String enc_output = obj.encrypt(password, key);
System.out.println("Encrypted text: " + enc_output);
String dec_output = obj.decrypt(enc_output, key);
System.out.println("Decrypted text: " + dec_output);
}
}

Output:

Password: Knf@123
Encrypted text: 4DTHqnctCuk=
Decrypted text: Knf@123


Example 2: File Encryption and decryption using Blowfish
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.security.Key;
import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;

public class BlowfishFileEncryptionDemo {

private static final String ALGORITHM = "Blowfish";
private static String key= "knowledgefactory";
private static final String SAMPLE_FILE_PATH =
"/home/user/Desktop/cryptotest/Sample.txt";
private static final String ENCRYPTED_FILE_PATH =
"/home/user/Desktop/cryptotest/file.encrypted";
private static final String DECRYPTED_FILE_PATH =
"/home/user/Desktop/cryptotest/decryptedfile.txt";

public static void main(String[] args) {

File sampleFile = new File(SAMPLE_FILE_PATH);
File encryptedFile = new File(ENCRYPTED_FILE_PATH);
File decryptedFile = new File(DECRYPTED_FILE_PATH);

try {
BlowfishFileEncryptionDemo.encrypt(sampleFile, encryptedFile);
BlowfishFileEncryptionDemo.decrypt(encryptedFile, decryptedFile);
} catch (Exception e) {
e.printStackTrace();
}
}

public static void encrypt(File sampleFile, File outputFile)
throws Exception {
doCrypto(Cipher.ENCRYPT_MODE, sampleFile, outputFile);

}

public static void decrypt(File sampleFile, File outputFile)
throws Exception {
doCrypto(Cipher.DECRYPT_MODE, sampleFile, outputFile);

}

private static void doCrypto(int cipherMode, File sampleFile,
File outputFile) throws Exception {

Key secretKey = new SecretKeySpec(key.getBytes(), ALGORITHM);
Cipher cipher = Cipher.getInstance(ALGORITHM);
cipher.init(cipherMode, secretKey);

InputStream inputStream = new FileInputStream(sampleFile);
byte[] inputBytes = new byte[(int) sampleFile.length()];
inputStream.read(inputBytes);

byte[] outputBytes = cipher.doFinal(inputBytes);

OutputStream outputStream = new FileOutputStream(outputFile);
outputStream.write(outputBytes);

inputStream.close();
outputStream.close();

}
}

Output:



More related topics...

Popular posts from this blog

Spring boot video streaming example-HTML5

Learn Java 8 streams with an example - print odd/even numbers from Array and List

Spring Boot + Mockito simple application with 100% code coverage

Spring Boot + OpenCSV Export Data to CSV Example

Custom Exception Handling in Quarkus REST API

DataTable-Pagination example with Spring boot, jQuery and ajax

Registration and Login with Spring Boot + Spring Security + Thymeleaf

Node JS mini projects with source code - free download

Spring boot web project free download:User Registration System