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

package org.bouncycastle.its.jcajce;

import org.bouncycastle.jcajce.util.NamedJcaJceHelper;
import org.bouncycastle.jcajce.util.ProviderJcaJceHelper;
import java.security.Provider;
import org.bouncycastle.util.Arrays;
import javax.crypto.Cipher;
import java.security.spec.AlgorithmParameterSpec;
import java.security.Key;
import org.bouncycastle.jcajce.spec.IESKEMParameterSpec;
import javax.crypto.SecretKey;
import org.bouncycastle.jcajce.util.JcaJceHelper;
import java.security.PrivateKey;
import org.bouncycastle.its.operator.ETSIDataDecryptor;

public class JcaETSIDataDecryptor implements ETSIDataDecryptor
{
    private final PrivateKey privateKey;
    private final JcaJceHelper helper;
    private final byte[] recipientHash;
    private SecretKey secretKey;
    
    JcaETSIDataDecryptor(final PrivateKey privateKey, final byte[] recipientHash, final JcaJceHelper helper) {
        this.secretKey = null;
        this.privateKey = privateKey;
        this.helper = helper;
        this.recipientHash = recipientHash;
    }
    
    @Override
    public byte[] decrypt(final byte[] wrappedKey, final byte[] input, final byte[] array) {
        try {
            final Cipher cipher = this.helper.createCipher("ETSIKEMwithSHA256");
            cipher.init(4, this.privateKey, new IESKEMParameterSpec(this.recipientHash));
            this.secretKey = (SecretKey)cipher.unwrap(wrappedKey, "AES", 3);
            final Cipher cipher2 = this.helper.createCipher("CCM");
            cipher2.init(2, this.secretKey, ClassUtil.getGCMSpec(array, 128));
            return cipher2.doFinal(input);
        }
        catch (final Exception cause) {
            throw new RuntimeException(cause.getMessage(), cause);
        }
    }
    
    @Override
    public byte[] getKey() {
        if (this.secretKey == null) {
            throw new IllegalStateException("no secret key recovered");
        }
        return this.secretKey.getEncoded();
    }
    
    public static Builder builder(final PrivateKey privateKey, final byte[] array) {
        return new Builder(privateKey, array);
    }
    
    public static class Builder
    {
        private JcaJceHelper provider;
        private final byte[] recipientHash;
        private final PrivateKey key;
        
        public Builder(final PrivateKey key, final byte[] array) {
            this.key = key;
            this.recipientHash = Arrays.clone(array);
        }
        
        public Builder provider(final Provider provider) {
            this.provider = new ProviderJcaJceHelper(provider);
            return this;
        }
        
        public Builder provider(final String s) {
            this.provider = new NamedJcaJceHelper(s);
            return this;
        }
        
        public JcaETSIDataDecryptor build() {
            return new JcaETSIDataDecryptor(this.key, this.recipientHash, this.provider);
        }
    }
}
