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

import java.io.File;
import java.util.Date;

import javax.crypto.SecretKey;

import org.bouncycastle.util.encoders.Base64;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import be.fgov.ehealth.etee.crypto.encrypt.DataSealer;
import be.fgov.ehealth.etee.crypto.encrypt.DataSealerException;
import be.fgov.ehealth.etee.crypto.policies.EncryptionCredential;
import be.fgov.ehealth.etee.crypto.utils.SecretKeyUtils;


/**
 * An example that illustrates the actions at Alice's (sender) side in order to protect a message for an unknown addressee.
 *
 * @author jeh
 */
public class SealForUnknown extends AbstractExample {

    private static final Logger LOGGER = LoggerFactory.getLogger(SealForUnknown.class);

    @Test
    public final void sealMessageForUnknown() throws DataSealerException {
        // 0. During initialisation, Alice creates her DataSealer that she can use to seal data.
        DataSealer alicesDataSealer = initSealing();

        // 1. Here Alice has a message for an unknown addressee that must be
        // sealed to secure its confidentiality, integrity and authenticity.
        byte[] messageToProtect = getMessageToProtect();

        // 2. Get a new key and it's ID from the KGSS web service.
        String base64EncodedKek = getNewKekFromKgss();
        String kekId = getNewKekIdFromKgss();
        SecretKey kek = SecretKeyUtils.getSecretKey(base64EncodedKek);

        // 3. Seal the dataToBeSealed
        byte[] sealedData = alicesDataSealer.seal(messageToProtect, EncryptionCredential.create(kek, kekId));

        // 4. Write the sealed data to your transportation medium
        // 4.1. As binary in a file...
        File cmsFile = writeToTransportMedium(sealedData, "target/message_from_alice_for_unknown.msg");
        LOGGER.info("The sealed data is written in file: " + cmsFile.getAbsolutePath());

        // 4.2 Or as Base64 encoded binary text...
        byte[] encodedSealedData = Base64.encode(sealedData);
        LOGGER.info("base64-encoded sealedData : " + new String(encodedSealedData));
    }

    private static byte[] getMessageToProtect() {
        return String.format("This is a secret message from Alice for an unknown addressee written at %s", new Date()).getBytes();
    }
}
