Created by
Ruben Fernandez
| package com.easypaymentsgateway.utils;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import org.apache.commons.codec.binary.Base64;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.easypaymentsgateway.exceptions.EncryptionException;
import com.easypaymentsgateway.exceptions.EncryptionException.ErrorCode;
public class EncryptionUtils {
/**
* Logger
*/
private static Logger logger = LoggerFactory.getLogger(EncryptionUtils.class);
private static final String AES = "AES";
public static String SHA256 = "SHA-256";
/**
* Encrypts using AES algorithm
*
* @param input
* @param key
* @return
*/
public static String encrypt(String input, String key) {
byte[] crypted = null;
try {
SecretKeySpec skey = new SecretKeySpec(key.getBytes(), AES);
Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, skey);
crypted = cipher.doFinal(input.getBytes());
} catch (Exception e) {
logger.error("Unable to encrypt: ", e);
}
return new String(Base64.encodeBase64(crypted));
}
/**
* Method that encrypts the message using an algorithm
*
* @param message
* to encrypt
* @param algorithm
* used to encrypt
* @return Message encrypted
* @throws NoSuchAlgorithmException
*/
public static String hashMessage(String message, String algorithm) {
byte[] digest = null;
byte[] buffer = message.getBytes();
MessageDigest messageDigest;
try {
messageDigest = MessageDigest.getInstance(algorithm);
messageDigest.reset();
messageDigest.update(buffer);
digest = messageDigest.digest();
} catch (NoSuchAlgorithmException e) {
throw new EncryptionException(ErrorCode.UNABLE_TO_FIND_HASH_ALGORITHM, "Internal error found");
}
return toHexadecimal(digest);
}
/**
* Convert digest Hexadecimal
*
* @param digest
* @return
*/
private static String toHexadecimal(byte[] digest) {
StringBuilder hash = new StringBuilder();
for (byte aux : digest) {
int b = aux & 0xff;
if (Integer.toHexString(b).length() == 1)
hash.append("0");
hash.append(Integer.toHexString(b));
}
return hash.toString();
}
}
|