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

package org.bouncycastle.operator.jcajce;

import org.bouncycastle.asn1.nist.NISTObjectIdentifiers;
import org.bouncycastle.asn1.DERNull;
import java.util.HashSet;
import org.bouncycastle.asn1.pkcs.RSAESOAEPparams;
import org.bouncycastle.asn1.DEROctetString;
import org.bouncycastle.asn1.ASN1Encodable;
import java.security.spec.MGF1ParameterSpec;
import org.bouncycastle.asn1.pkcs.PKCSObjectIdentifiers;
import javax.crypto.spec.PSource;
import javax.crypto.spec.OAEPParameterSpec;
import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.KeyAgreement;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.ProviderException;
import java.security.GeneralSecurityException;
import java.security.InvalidKeyException;
import org.bouncycastle.asn1.ASN1Primitive;
import org.bouncycastle.asn1.oiw.OIWObjectIdentifiers;
import org.bouncycastle.operator.OperatorException;
import org.bouncycastle.asn1.cryptopro.GostR3410KeyTransport;
import org.bouncycastle.asn1.cryptopro.Gost2814789EncryptedKey;
import org.bouncycastle.util.Arrays;
import javax.crypto.spec.SecretKeySpec;
import org.bouncycastle.jcajce.spec.GOST28147WrapParameterSpec;
import java.security.Key;
import org.bouncycastle.jcajce.spec.UserKeyingMaterialSpec;
import org.bouncycastle.asn1.cryptopro.CryptoProObjectIdentifiers;
import org.bouncycastle.asn1.cryptopro.GostR3410TransportParameters;
import org.bouncycastle.asn1.rosstandart.RosstandartObjectIdentifiers;
import java.security.interfaces.ECPublicKey;
import org.bouncycastle.crypto.CryptoServicesRegistrar;
import org.bouncycastle.operator.GenericKey;
import org.bouncycastle.jcajce.util.NamedJcaJceHelper;
import org.bouncycastle.jcajce.util.ProviderJcaJceHelper;
import java.security.Provider;
import java.security.spec.InvalidParameterSpecException;
import java.security.spec.AlgorithmParameterSpec;
import java.security.AlgorithmParameters;
import org.bouncycastle.asn1.x509.AlgorithmIdentifier;
import java.security.cert.X509Certificate;
import java.util.HashMap;
import org.bouncycastle.jcajce.util.JcaJceHelper;
import org.bouncycastle.jcajce.util.DefaultJcaJceHelper;
import org.bouncycastle.asn1.x509.SubjectPublicKeyInfo;
import org.bouncycastle.asn1.ASN1ObjectIdentifier;
import java.security.SecureRandom;
import java.security.PublicKey;
import java.util.Map;
import java.util.Set;
import org.bouncycastle.operator.AsymmetricKeyWrapper;

public class JceAsymmetricKeyWrapper extends AsymmetricKeyWrapper
{
    private static final Set gostAlgs;
    private OperatorHelper helper;
    private Map extraMappings;
    private PublicKey publicKey;
    private SecureRandom random;
    private static final Map digests;
    
    static boolean isGOST(final ASN1ObjectIdentifier asn1ObjectIdentifier) {
        return JceAsymmetricKeyWrapper.gostAlgs.contains(asn1ObjectIdentifier);
    }
    
    public JceAsymmetricKeyWrapper(final PublicKey publicKey) {
        super(SubjectPublicKeyInfo.getInstance(publicKey.getEncoded()).getAlgorithm());
        this.helper = new OperatorHelper(new DefaultJcaJceHelper());
        this.extraMappings = new HashMap();
        this.publicKey = publicKey;
    }
    
    public JceAsymmetricKeyWrapper(final X509Certificate x509Certificate) {
        this(x509Certificate.getPublicKey());
    }
    
    public JceAsymmetricKeyWrapper(final AlgorithmIdentifier algorithmIdentifier, final PublicKey publicKey) {
        super(algorithmIdentifier);
        this.helper = new OperatorHelper(new DefaultJcaJceHelper());
        this.extraMappings = new HashMap();
        this.publicKey = publicKey;
    }
    
    public JceAsymmetricKeyWrapper(final AlgorithmParameters algorithmParameters, final PublicKey publicKey) throws InvalidParameterSpecException {
        super(extractAlgID(publicKey, algorithmParameters.getParameterSpec(AlgorithmParameterSpec.class)));
        this.helper = new OperatorHelper(new DefaultJcaJceHelper());
        this.extraMappings = new HashMap();
        this.publicKey = publicKey;
    }
    
    public JceAsymmetricKeyWrapper(final AlgorithmParameterSpec algorithmParameterSpec, final PublicKey publicKey) {
        super(extractAlgID(publicKey, algorithmParameterSpec));
        this.helper = new OperatorHelper(new DefaultJcaJceHelper());
        this.extraMappings = new HashMap();
        this.publicKey = publicKey;
    }
    
    public JceAsymmetricKeyWrapper setProvider(final Provider provider) {
        this.helper = new OperatorHelper(new ProviderJcaJceHelper(provider));
        return this;
    }
    
    public JceAsymmetricKeyWrapper setProvider(final String s) {
        this.helper = new OperatorHelper(new NamedJcaJceHelper(s));
        return this;
    }
    
    public JceAsymmetricKeyWrapper setSecureRandom(final SecureRandom random) {
        this.random = random;
        return this;
    }
    
    public JceAsymmetricKeyWrapper setAlgorithmMapping(final ASN1ObjectIdentifier asn1ObjectIdentifier, final String s) {
        this.extraMappings.put(asn1ObjectIdentifier, s);
        return this;
    }
    
    @Override
    public byte[] generateWrappedKey(final GenericKey genericKey) throws OperatorException {
        byte[] array = null;
        if (isGOST(this.getAlgorithmIdentifier().getAlgorithm())) {
            try {
                this.random = CryptoServicesRegistrar.getSecureRandom(this.random);
                final KeyPairGenerator keyPairGenerator = this.helper.createKeyPairGenerator(this.getAlgorithmIdentifier().getAlgorithm());
                keyPairGenerator.initialize(((ECPublicKey)this.publicKey).getParams(), this.random);
                final KeyPair generateKeyPair = keyPairGenerator.generateKeyPair();
                final byte[] bytes = new byte[8];
                this.random.nextBytes(bytes);
                final SubjectPublicKeyInfo instance = SubjectPublicKeyInfo.getInstance(generateKeyPair.getPublic().getEncoded());
                GostR3410TransportParameters gostR3410TransportParameters;
                if (instance.getAlgorithm().getAlgorithm().on(RosstandartObjectIdentifiers.id_tc26)) {
                    gostR3410TransportParameters = new GostR3410TransportParameters(RosstandartObjectIdentifiers.id_tc26_gost_28147_param_Z, instance, bytes);
                }
                else {
                    gostR3410TransportParameters = new GostR3410TransportParameters(CryptoProObjectIdentifiers.id_Gost28147_89_CryptoPro_A_ParamSet, instance, bytes);
                }
                final KeyAgreement keyAgreement = this.helper.createKeyAgreement(this.getAlgorithmIdentifier().getAlgorithm());
                keyAgreement.init(generateKeyPair.getPrivate(), new UserKeyingMaterialSpec(gostR3410TransportParameters.getUkm()));
                keyAgreement.doPhase(this.publicKey, true);
                final SecretKey generateSecret = keyAgreement.generateSecret(CryptoProObjectIdentifiers.id_Gost28147_89_CryptoPro_KeyWrap.getId());
                final byte[] encoded = OperatorUtils.getJceKey(genericKey).getEncoded();
                final Cipher cipher = this.helper.createCipher(CryptoProObjectIdentifiers.id_Gost28147_89_CryptoPro_KeyWrap);
                cipher.init(3, generateSecret, new GOST28147WrapParameterSpec(gostR3410TransportParameters.getEncryptionParamSet(), gostR3410TransportParameters.getUkm()));
                final byte[] wrap = cipher.wrap(new SecretKeySpec(encoded, "GOST"));
                return new GostR3410KeyTransport(new Gost2814789EncryptedKey(Arrays.copyOfRange(wrap, 0, 32), Arrays.copyOfRange(wrap, 32, 36)), gostR3410TransportParameters).getEncoded();
            }
            catch (final Exception ex) {
                throw new OperatorException("exception wrapping key: " + ex.getMessage(), ex);
            }
        }
        final Cipher asymmetricWrapper = this.helper.createAsymmetricWrapper(this.getAlgorithmIdentifier(), this.extraMappings);
        AlgorithmParameters algorithmParameters = null;
        try {
            if (!this.getAlgorithmIdentifier().getAlgorithm().equals(OIWObjectIdentifiers.elGamalAlgorithm)) {
                algorithmParameters = this.helper.createAlgorithmParameters(this.getAlgorithmIdentifier());
            }
            if (algorithmParameters != null) {
                asymmetricWrapper.init(3, this.publicKey, algorithmParameters, this.random);
            }
            else {
                asymmetricWrapper.init(3, this.publicKey, this.random);
            }
            array = asymmetricWrapper.wrap(OperatorUtils.getJceKey(genericKey));
        }
        catch (final InvalidKeyException ex2) {}
        catch (final GeneralSecurityException ex3) {}
        catch (final IllegalStateException ex4) {}
        catch (final UnsupportedOperationException ex5) {}
        catch (final ProviderException ex6) {}
        if (array == null) {
            try {
                if (algorithmParameters != null) {
                    asymmetricWrapper.init(1, this.publicKey, algorithmParameters, this.random);
                }
                else {
                    asymmetricWrapper.init(1, this.publicKey, this.random);
                }
                array = asymmetricWrapper.doFinal(OperatorUtils.getJceKey(genericKey).getEncoded());
            }
            catch (final InvalidKeyException ex7) {
                throw new OperatorException("unable to encrypt contents key", ex7);
            }
            catch (final GeneralSecurityException ex8) {
                throw new OperatorException("unable to encrypt contents key", ex8);
            }
        }
        return array;
    }
    
    private static AlgorithmIdentifier extractAlgID(final PublicKey publicKey, final AlgorithmParameterSpec algorithmParameterSpec) {
        if (!(algorithmParameterSpec instanceof OAEPParameterSpec)) {
            throw new IllegalArgumentException("unknown spec: " + algorithmParameterSpec.getClass().getName());
        }
        final OAEPParameterSpec oaepParameterSpec = (OAEPParameterSpec)algorithmParameterSpec;
        if (!oaepParameterSpec.getMGFAlgorithm().equals(OAEPParameterSpec.DEFAULT.getMGFAlgorithm())) {
            throw new IllegalArgumentException("unknown MGF: " + oaepParameterSpec.getMGFAlgorithm());
        }
        if (oaepParameterSpec.getPSource() instanceof PSource.PSpecified) {
            return new AlgorithmIdentifier(PKCSObjectIdentifiers.id_RSAES_OAEP, new RSAESOAEPparams(getDigest(oaepParameterSpec.getDigestAlgorithm()), new AlgorithmIdentifier(PKCSObjectIdentifiers.id_mgf1, getDigest(((MGF1ParameterSpec)oaepParameterSpec.getMGFParameters()).getDigestAlgorithm())), new AlgorithmIdentifier(PKCSObjectIdentifiers.id_pSpecified, new DEROctetString(((PSource.PSpecified)oaepParameterSpec.getPSource()).getValue()))));
        }
        throw new IllegalArgumentException("unknown PSource: " + oaepParameterSpec.getPSource().getAlgorithm());
    }
    
    private static AlgorithmIdentifier getDigest(final String str) {
        final AlgorithmIdentifier algorithmIdentifier = JceAsymmetricKeyWrapper.digests.get(str);
        if (algorithmIdentifier != null) {
            return algorithmIdentifier;
        }
        throw new IllegalArgumentException("unknown digest name: " + str);
    }
    
    static {
        (gostAlgs = new HashSet()).add(CryptoProObjectIdentifiers.gostR3410_2001_CryptoPro_ESDH);
        JceAsymmetricKeyWrapper.gostAlgs.add(CryptoProObjectIdentifiers.gostR3410_2001);
        JceAsymmetricKeyWrapper.gostAlgs.add(RosstandartObjectIdentifiers.id_tc26_agreement_gost_3410_12_256);
        JceAsymmetricKeyWrapper.gostAlgs.add(RosstandartObjectIdentifiers.id_tc26_agreement_gost_3410_12_512);
        JceAsymmetricKeyWrapper.gostAlgs.add(RosstandartObjectIdentifiers.id_tc26_gost_3410_12_256);
        JceAsymmetricKeyWrapper.gostAlgs.add(RosstandartObjectIdentifiers.id_tc26_gost_3410_12_512);
        (digests = new HashMap()).put("SHA1", new AlgorithmIdentifier(OIWObjectIdentifiers.idSHA1, DERNull.INSTANCE));
        JceAsymmetricKeyWrapper.digests.put("SHA-1", new AlgorithmIdentifier(OIWObjectIdentifiers.idSHA1, DERNull.INSTANCE));
        JceAsymmetricKeyWrapper.digests.put("SHA224", new AlgorithmIdentifier(NISTObjectIdentifiers.id_sha224, DERNull.INSTANCE));
        JceAsymmetricKeyWrapper.digests.put("SHA-224", new AlgorithmIdentifier(NISTObjectIdentifiers.id_sha224, DERNull.INSTANCE));
        JceAsymmetricKeyWrapper.digests.put("SHA256", new AlgorithmIdentifier(NISTObjectIdentifiers.id_sha256, DERNull.INSTANCE));
        JceAsymmetricKeyWrapper.digests.put("SHA-256", new AlgorithmIdentifier(NISTObjectIdentifiers.id_sha256, DERNull.INSTANCE));
        JceAsymmetricKeyWrapper.digests.put("SHA384", new AlgorithmIdentifier(NISTObjectIdentifiers.id_sha384, DERNull.INSTANCE));
        JceAsymmetricKeyWrapper.digests.put("SHA-384", new AlgorithmIdentifier(NISTObjectIdentifiers.id_sha384, DERNull.INSTANCE));
        JceAsymmetricKeyWrapper.digests.put("SHA512", new AlgorithmIdentifier(NISTObjectIdentifiers.id_sha512, DERNull.INSTANCE));
        JceAsymmetricKeyWrapper.digests.put("SHA-512", new AlgorithmIdentifier(NISTObjectIdentifiers.id_sha512, DERNull.INSTANCE));
        JceAsymmetricKeyWrapper.digests.put("SHA512/224", new AlgorithmIdentifier(NISTObjectIdentifiers.id_sha512_224, DERNull.INSTANCE));
        JceAsymmetricKeyWrapper.digests.put("SHA-512/224", new AlgorithmIdentifier(NISTObjectIdentifiers.id_sha512_224, DERNull.INSTANCE));
        JceAsymmetricKeyWrapper.digests.put("SHA-512(224)", new AlgorithmIdentifier(NISTObjectIdentifiers.id_sha512_224, DERNull.INSTANCE));
        JceAsymmetricKeyWrapper.digests.put("SHA512/256", new AlgorithmIdentifier(NISTObjectIdentifiers.id_sha512_256, DERNull.INSTANCE));
        JceAsymmetricKeyWrapper.digests.put("SHA-512/256", new AlgorithmIdentifier(NISTObjectIdentifiers.id_sha512_256, DERNull.INSTANCE));
        JceAsymmetricKeyWrapper.digests.put("SHA-512(256)", new AlgorithmIdentifier(NISTObjectIdentifiers.id_sha512_256, DERNull.INSTANCE));
    }
}
