package org.bouncycastle.cms;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.security.AlgorithmParameters;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.Key;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;

import org.bouncycastle.asn1.ASN1OutputStream;
import org.bouncycastle.asn1.cms.EncryptedContentInfo;
import org.bouncycastle.asn1.cms.KEKIdentifier;
import org.bouncycastle.asn1.cms.KEKRecipientInfo;
import org.bouncycastle.asn1.x509.AlgorithmIdentifier;


/**
 * the RecipientInfo class for a recipient who has been sent a message
 * encrypted using a secret key known to the other side.
 */
public class KEKRecipientInformation
    extends RecipientInformation
{
    private KEKRecipientInfo        info;
    private EncryptedContentInfo    data;

    public KEKRecipientInformation(
        KEKRecipientInfo        info,
        EncryptedContentInfo    data)
    {
        super(AlgorithmIdentifier.getInstance(info.getKeyEncryptionAlgorithm()));
        
        this.info = info;
        this.rid = new RecipientId();
        this.data = data;

        KEKIdentifier       kekId = info.getKekid();

        rid.setKeyIdentifier(kekId.getKeyIdentifier().getOctets());
    }

    /**
     * decrypt the content and return it as a byte array.
     */
    public byte[] getContent(
        Key      key,
        String   prov)
        throws CMSException, NoSuchProviderException
    {
        try
        {
            byte[]              encryptedKey = info.getEncryptedKey().getOctets();

            Cipher  keyCipher = Cipher.getInstance(keyEncAlg.getObjectId().getId(), prov);

            keyCipher.init(Cipher.UNWRAP_MODE, key);

            byte[]              enc = data.getEncryptedContent().getOctets();
            AlgorithmIdentifier aid = data.getContentEncryptionAlgorithm();
            String              alg = aid.getObjectId().getId();
            Key                 sKey = keyCipher.unwrap(
                                        encryptedKey, alg, Cipher.SECRET_KEY);
            Cipher              cipher = Cipher.getInstance(alg, prov);

            if (aid.getParameters() != null)
            {
                AlgorithmParameters     params = AlgorithmParameters.getInstance(alg, prov);

                ByteArrayOutputStream   bOut = new ByteArrayOutputStream();
                ASN1OutputStream        aOut = new ASN1OutputStream(bOut);

                aOut.writeObject(aid.getParameters());

                params.init(bOut.toByteArray(), "ASN.1");

                cipher.init(Cipher.DECRYPT_MODE, sKey, params);
            }
            else
            {
                cipher.init(Cipher.DECRYPT_MODE, sKey);
            }

            return cipher.doFinal(enc);
        }
        catch (NoSuchAlgorithmException e)
        {
            throw new CMSException("can't find algorithm.", e);
        }
        catch (IllegalBlockSizeException e)
        {
            throw new CMSException("illegal blocksize in message.", e);
        }
        catch (InvalidKeyException e)
        {
            throw new CMSException("key invalid in message.", e);
        }
        catch (NoSuchPaddingException e)
        {
            throw new CMSException("required padding not supported.", e);
        }
        catch (BadPaddingException e)
        {
            throw new CMSException("bad padding in message.", e);
        }
        catch (InvalidAlgorithmParameterException e)
        {
            throw new CMSException("algorithm parameters invalid.", e);
        }
        catch (IOException e)
        {
            throw new CMSException("error decoding algorithm parameters.", e);
        }
    }
}
