eds.component.encryption.EncryptionUtility.java Source code

Java tutorial

Introduction

Here is the source code for eds.component.encryption.EncryptionUtility.java

Source

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package eds.component.encryption;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import org.apache.commons.codec.binary.Hex;

/**
 *
 * @author LeeKiatHaw
 */
public class EncryptionUtility {

    public static String getHash(String transactionId, EncryptionType type) {
        String secureHash = transactionId;
        MessageDigest md;
        String hashedID = "";
        byte[] hash;
        try {
            //md = MessageDigest.getInstance("SHA-256");
            md = MessageDigest.getInstance(type.toString());
            hash = md.digest(secureHash.getBytes("UTF-8"));
            hashedID = new String(Hex.encodeHex(hash));//String.format("%032x", new BigInteger(hash));;//String.format("%032x", Arrays.toString(hash));
        } catch (NoSuchAlgorithmException | UnsupportedEncodingException ex) {
            throw new RuntimeException("No such algorithm or encoding method: " + ex.getMessage());
        }

        return hashedID;
    }

    public static String hashText(String text, EncryptionType type) {
        byte[] hash;
        MessageDigest md;
        try {
            //md = MessageDigest.getInstance("SHA-256");
            md = MessageDigest.getInstance(type.toString());
            hash = md.digest(text.getBytes("UTF-8"));
            String hashedText = new String(Hex.encodeHex(hash));//String.format("%032x", new BigInteger(hash));;//String.format("%032x", Arrays.toString(hash));

            return hashedText;
        } catch (NoSuchAlgorithmException | UnsupportedEncodingException ex) {
            throw new RuntimeException("No such algorithm or encoding method: " + ex.getMessage());
        }
    }
}