String Encryption using SHA-256

This document introduces a way to implement an encryption algorithm for hashing strings

Andrew L. Mackey

Overview

Security is an important concern for an organization that manages data. The following code demonstrates how to implement the SHA-256 encryption algorithm to encrypt strings using a one-way hash.

 

Java Source Code

In this example, the method encryptString() accepts a string (e.g. a password) as a parameter. The method returns a hashed value for the input string. We can save the hashed value of the password (e.g. encryptPassword("mysecretpass")) and compare all new user input by hashing the input and comparing it to the hash value that was saved.

import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
	*
	* @author amackey
	*
	*/
public class UAFSEncryptionUtility {

	/**
		* This method will accept a string to be encrypted as a parameter and
		* return the one-way hashed value using the SHA-256 encryption algorithm.
		* @param valueToEncrypt
		* @return
		*/

	public static String encryptString(String valueToEncrypt) {
		StringBuffer output = new StringBuffer();

		try {
			MessageDigest digest = MessageDigest.getInstance("SHA-256");
			byte[] hash = digest.digest(valueToEncrypt.getBytes(StandardCharsets.UTF_8));


			for (int i = 0; i < hash.length; i++) {
				String hex = Integer.toHexString(0xff & hash[i]);

				if (hex.length() == 1)
					output.append('0');

				output.append(hex);
			}
		} catch(NoSuchAlgorithmException ex) {
			ex.printStackTrace();
		}

		return output.toString();
	}




	public static void main(String[] args) {

		String mypassword = "secretpassword";
		String encrypted = encryptString("secretpassword");

		System.out.println( "Password:   " + mypassword );
		System.out.println( "Encrypted:  " + encrypted  );

	}

}