Java encrypt class

A simple implementation of an encryption class to be used in Java applications for either encrypting strings and calculating files’ fingerprint.

import java.io.FileInputStream;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class Encrypt {

   private FileInputStream fis;

   public Encrypt() { }

   public String encryptString(String input, String salt, String algorithm) {
      String output = null;
      String fullInput = null;

      if (!salt.equals(null)) {
         fullInput = salt + input;
      } else {
         fullInput = input;
      }

      try {
         MessageDigest digest = MessageDigest.getInstance(algorithm);
         digest.update(fullInput.getBytes(), 0, fullInput.length());
         output = new BigInteger(1, digest.digest()).toString(16);
      } catch (NoSuchAlgorithmException ex) {
         ex.printStackTrace();
      }
      return output;
   }

   // Based on: http://www.mkyong.com/java/how-to-generate-a-file-checksum-value-in-java/
   public String calculateFingerprint(String fileName, String algorithm) {
      StringBuffer sb = new StringBuffer();
      try {
         MessageDigest md = MessageDigest.getInstance(algorithm);
         fis = new FileInputStream(fileName);
         byte[] dataBytes = new byte[1024];
         int nread = 0;
         while ((nread = fis.read(dataBytes)) != -1) { md.update(dataBytes, 0, nread); }
         byte[] mdbytes = md.digest();
         for (int i = 0; i < mdbytes.length; i++) {
            sb.append(Integer.toString((mdbytes[i] & 0xff) + 0x100, 16).substring(1));
         }
      } catch (Exception ex) {
         ex.printStackTrace();
      }
      return sb.toString();
   }
}

Link to GiHub repository. The class is intended to be used as a library within Java applications.

Example for encrypting a string:

Encrypt en = new Encrypt();
String encryptedString = en.encryptString(textField.getText().toString(), \
"salt goes here if you want", "md5")));

Example for calculating the fingerprint of a file:

Encrypt en = new Encrypt();
String fingerPrint = en.calculateFingerprint("/path/to/file", sha1);
Advertisement

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s