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

import java.io.File;
import java.io.IOException;
import java.security.KeyStoreException;
import java.util.Date;

import org.apache.log4j.Logger;
import org.bouncycastle.util.encoders.Base64;
import org.junit.Test;

import be.fgov.ehealth.etee.crypto.encrypt.DataSealer;
import be.fgov.ehealth.etee.crypto.encrypt.DataSealerException;
import be.fgov.ehealth.etee.crypto.encrypt.EncryptionToken;


/**
 * An example that illustrates the actions at Alice's (sender) side  in order to protect an authenticated message,
 * encrypted for Bob's (recipient) eyes only.
 * 
 * @author jeh
 */
public class SealExampleTest extends AbstractExample {

    private static final Logger LOGGER = Logger.getLogger(SealExampleTest.class);
    
    @Test
    public final void sealMessageFromAliceToBob() throws KeyStoreException, IOException, 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 Bob that must be
        // sealed to secure its confidentiality, integrity and authenticity.
        byte[] messageFromAliceToBob = getMessageToProtect();

        // 2. Get the public encryption key of the addressee, Bob, from the ETK-DEPOT web service.
        EncryptionToken bobsEtk = getBobsEtkFromEtkDepot();

        // 3. Seal the dataToBeSealed
        byte[] sealedData = alicesDataSealer.seal(bobsEtk, messageFromAliceToBob);

        // 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_bob.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 Bob written at %s", new Date()).getBytes();
    }
}
