Untitled

mail@pastecode.io avatar
unknown
plain_text
a month ago
1.8 kB
3
Indexable
Never
package com.kmbl.offercommon.utils;

import lombok.experimental.UtilityClass;

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

import static com.kmbl.offercommon.constant.OfferValidationConstants.MD5;
import static com.kmbl.offercommon.constant.OfferValidationConstants.SHA256;

@UtilityClass
public class EncryptionUtils {
    public String getSHA256Hash (String input) {
        if(Objects.isNull(input) || input.isEmpty())
            return "";
        try {
            MessageDigest messageDigest = MessageDigest.getInstance(SHA256);
            byte[] encodedHash = messageDigest.digest(
                    input.getBytes(StandardCharsets.UTF_8));
            return bytesToHex(encodedHash);
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException(e);
        }
    }

    public String getMD5Hash (String key) {
        try {
            MessageDigest md = MessageDigest.getInstance(MD5);
            md.update(key.getBytes());
            byte[] digest = md.digest();
            StringBuilder hexString = new StringBuilder();
            for (byte b : digest) {
                hexString.append(String.format("%02x", b));
            }
            return hexString.toString();
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException(e);
        }
    }

    private static String bytesToHex(byte[] hash) {
        StringBuilder hexString = new StringBuilder(2 * hash.length);
        for (byte b : hash) {
            String hex = Integer.toHexString(0xff & b);
            if (hex.length() == 1) {
                hexString.append('0');
            }
            hexString.append(hex);
        }
        return hexString.toString();
    }
}
Leave a Comment