package egovframework.com.its.web.server.util;

import lombok.extern.slf4j.Slf4j;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.util.Base64;

@Slf4j
public class SHA256 {

    private static final String algorithm = "SHA-256";
    private static final String saltAlgorithm = "SHA1PRNG";

    public static String encrypt(String text) throws RuntimeException {
        StringBuilder sb = new StringBuilder();
        try {
            MessageDigest md = MessageDigest.getInstance(algorithm);
            md.update(text.getBytes());
            byte[] data = md.digest();
            for (byte b : data) {
                sb.append(String.format("%02x", b & 0xFF));
            }
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException();
        }
        return sb.toString();
    }

    public static String getSalt() throws RuntimeException {
        String salt;
        try {
            SecureRandom random = SecureRandom.getInstance(saltAlgorithm);
            byte[] data = new byte[20];
            random.nextBytes(data);
            salt = new String(Base64.getEncoder().encode(data));
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException();
        }
        return salt;
    }

}
