/*
 * Copyright (c) eHealth
 */
package be.fgov.ehealth.etee.crypto.utils;

import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;

import org.bouncycastle.util.encoders.Base64;

import be.fgov.ehealth.etee.crypto.policies.EncryptionPolicy;


/**
 * Utility methods regarding SecretKeys.
 *
 * @author jeh
 */
public class SecretKeyUtils {
    
    private static final int BYTE_SIZE_IN_BITS = 8;
    private static final int SECRET_KEY_SIZE = EncryptionPolicy.UNKNOWN_RECIPIENT.getKeksize();
    private static final String SECRET_KEY_ENCRYPTION_ALGORITHM = "AES";
    
    /**
     * Reconstructs a base64 encoded SecretKey.
     * 
     * @param base64EncodedKey A Base64 encoded SecretKey.
     * @return SecretKey
     */
    public static SecretKey getSecretKey(String base64EncodedKey) {
        SecretKey secretKey;

        byte[] kek = decodeKek(base64EncodedKey);
        assertRequiredKeySize(kek);
        secretKey = new SecretKeySpec(kek, SECRET_KEY_ENCRYPTION_ALGORITHM);
        return secretKey;
    }

    private static void assertRequiredKeySize(byte[] kek) {
        if (kek.length * BYTE_SIZE_IN_BITS != SECRET_KEY_SIZE) {
            String message = String.format("The policy requires an %s key of %d bit. This one is not %d bit long.", SECRET_KEY_ENCRYPTION_ALGORITHM, SECRET_KEY_SIZE, SECRET_KEY_SIZE);
            throw new IllegalArgumentException(message);
        }
    }

    private static byte[] decodeKek(String encodedKek) {
        try {
            return Base64.decode(encodedKek);
        } catch (Exception e) {
            throw new IllegalArgumentException("Given encoded KEK is not valid");
        }
    }
}
