/*
 * Copyright (c) 2024. Elex. All Rights Reesrved.
 * https://www.elex-project.com/
 */

package kr.pe.elex.examples;

import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.PBEKeySpec;
import javax.crypto.spec.SecretKeySpec;
import java.security.KeyFactory;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.spec.InvalidKeySpecException;
import java.util.Base64;

public class AESKeys {
	public static SecretKey generateSecretKey() throws NoSuchAlgorithmException {
		KeyGenerator keyGenerator = KeyGenerator.getInstance("AES");
		keyGenerator.init(128, new SecureRandom());
		return keyGenerator.generateKey();
	}

	public static SecretKey generateSecretKey(char[] password, byte[] salt, int iteration) throws NoSuchAlgorithmException, InvalidKeySpecException {
		PBEKeySpec keySpec = new PBEKeySpec(password, salt, iteration);
		return SecretKeyFactory.getInstance("PBEWithHmacSHA256AndAES_128")
				.generateSecret(keySpec);
	}

	public static String encodeSecretKey(final SecretKey secretKey){
		return Base64.getEncoder().encodeToString(secretKey.getEncoded());
	}
	public static SecretKey decodeSecretKey(final String secretKey) throws NoSuchAlgorithmException, InvalidKeySpecException {
		SecretKey keySpec = new SecretKeySpec(Base64.getDecoder().decode(secretKey), "AES");
		return keySpec;
	}

	public static IvParameterSpec generateIV(byte[] iv){
		IvParameterSpec parameterSpec = new IvParameterSpec(iv);
		return parameterSpec;
	}
}
