Posted In: Apache, Commons, Security

How to encrypt Password/String using Apache Codec

Apache codec provide multiple methods to encrypt a string

Maven commons-codec

<dependency>
	<groupId>commons-codec</groupId>
	<artifactId>commons-codec</artifactId>
	<version>1.10</version>
</dependency>
package com.example.java.core;

import org.apache.commons.codec.digest.DigestUtils;
import org.junit.Test;

public class EncryptCodec {

	@Test
	// Calculates the SHA-1 digest and returns the value as a hex string.
	public void encrypt2() throws Exception {
		String password = "password";
		String encPassword = DigestUtils.sha1Hex(password);
		System.out.println(encPassword);
	}

	@Test
	// Calculates the MD2 digest and returns the value as a 32 character hex
	// string.
	public void encrypt3() throws Exception {
		String password = "password";
		String encPassword = DigestUtils.md2Hex(password);
		System.out.println(encPassword);
	}

	@Test
	// Calculates the SHA-256 digest and returns the value as a hex string.
	public void encrypt1() throws Exception {
		String password = "password";
		String encPassword = DigestUtils.sha256Hex(password);
		System.out.println(encPassword);
	}

	@Test
	// Calculates the SHA-384 digest and returns the value as a hex string.
	public void encrypt4() throws Exception {
		String password = "password";
		String encPassword = DigestUtils.sha384Hex(password);
		System.out.println(encPassword);
	}

	@Test
	// Calculates the SHA-512 digest and returns the value as a hex string.
	public void encrypt5() throws Exception {
		String password = "password";
		String encPassword = DigestUtils.sha512Hex(password);
		System.out.println(encPassword);
	}
}

by , on August 24th, 2017

  • Categories