// 
// Decompiled by Procyon v0.6.0
// 

package org.bouncycastle.cert.cmp;

import java.io.OutputStream;
import java.io.IOException;
import org.bouncycastle.cms.CMSException;
import org.bouncycastle.util.Arrays;
import org.bouncycastle.cms.CMSEnvelopedData;
import org.bouncycastle.asn1.ASN1Encodable;
import org.bouncycastle.asn1.cms.ContentInfo;
import org.bouncycastle.asn1.pkcs.PKCSObjectIdentifiers;
import org.bouncycastle.cms.RecipientInformation;
import org.bouncycastle.cms.Recipient;
import org.bouncycastle.asn1.cmp.PKIHeader;
import org.bouncycastle.operator.DigestCalculator;
import org.bouncycastle.asn1.cmp.Challenge;

public class ChallengeContent
{
    private final Challenge challenge;
    private final DigestCalculator owfCalc;
    
    ChallengeContent(final Challenge challenge, final DigestCalculator owfCalc) {
        this.challenge = challenge;
        this.owfCalc = owfCalc;
    }
    
    public byte[] extractChallenge(final PKIHeader pkiHeader, final Recipient recipient) throws CMPException {
        try {
            final Challenge.Rand instance = Challenge.Rand.getInstance(new CMSEnvelopedData(new ContentInfo(PKCSObjectIdentifiers.envelopedData, this.challenge.getEncryptedRand())).getRecipientInfos().getRecipients().iterator().next().getContent(recipient));
            if (!Arrays.constantTimeAreEqual(instance.getSender().getEncoded(), pkiHeader.getSender().getEncoded())) {
                throw new CMPChallengeFailedException("incorrect sender found");
            }
            final OutputStream outputStream = this.owfCalc.getOutputStream();
            outputStream.write(instance.getInt().getEncoded());
            outputStream.close();
            if (!Arrays.constantTimeAreEqual(this.challenge.getWitness(), this.owfCalc.getDigest())) {
                throw new CMPChallengeFailedException("corrupted challenge found");
            }
            return instance.getInt().getValue().toByteArray();
        }
        catch (final CMSException ex) {
            throw new CMPException(ex.getMessage(), ex);
        }
        catch (final IOException ex2) {
            throw new CMPException(ex2.getMessage(), ex2);
        }
    }
}
