Search in sources :

Example 61 with ASN1OctetString

use of org.bouncycastle.asn1.ASN1OctetString in project XobotOS by xamarin.

the class PublicKeyFactory method createKey.

/**
     * Create a public key from the passed in SubjectPublicKeyInfo
     * 
     * @param keyInfo the SubjectPublicKeyInfo containing the key data
     * @return the appropriate key parameter
     * @throws IOException on an error decoding the key
     */
public static AsymmetricKeyParameter createKey(SubjectPublicKeyInfo keyInfo) throws IOException {
    AlgorithmIdentifier algId = keyInfo.getAlgorithmId();
    if (algId.getObjectId().equals(PKCSObjectIdentifiers.rsaEncryption) || algId.getObjectId().equals(X509ObjectIdentifiers.id_ea_rsa)) {
        RSAPublicKeyStructure pubKey = new RSAPublicKeyStructure((ASN1Sequence) keyInfo.getPublicKey());
        return new RSAKeyParameters(false, pubKey.getModulus(), pubKey.getPublicExponent());
    } else if (algId.getObjectId().equals(X9ObjectIdentifiers.dhpublicnumber)) {
        DHPublicKey dhPublicKey = DHPublicKey.getInstance(keyInfo.getPublicKey());
        BigInteger y = dhPublicKey.getY().getValue();
        DHDomainParameters dhParams = DHDomainParameters.getInstance(keyInfo.getAlgorithmId().getParameters());
        BigInteger p = dhParams.getP().getValue();
        BigInteger g = dhParams.getG().getValue();
        BigInteger q = dhParams.getQ().getValue();
        BigInteger j = null;
        if (dhParams.getJ() != null) {
            j = dhParams.getJ().getValue();
        }
        DHValidationParameters validation = null;
        DHValidationParms dhValidationParms = dhParams.getValidationParms();
        if (dhValidationParms != null) {
            byte[] seed = dhValidationParms.getSeed().getBytes();
            BigInteger pgenCounter = dhValidationParms.getPgenCounter().getValue();
            // TODO Check pgenCounter size?
            validation = new DHValidationParameters(seed, pgenCounter.intValue());
        }
        return new DHPublicKeyParameters(y, new DHParameters(p, g, q, j, validation));
    } else if (algId.getObjectId().equals(PKCSObjectIdentifiers.dhKeyAgreement)) {
        DHParameter params = new DHParameter((ASN1Sequence) keyInfo.getAlgorithmId().getParameters());
        DERInteger derY = (DERInteger) keyInfo.getPublicKey();
        BigInteger lVal = params.getL();
        int l = lVal == null ? 0 : lVal.intValue();
        DHParameters dhParams = new DHParameters(params.getP(), params.getG(), null, l);
        return new DHPublicKeyParameters(derY.getValue(), dhParams);
    } else // END android-removed
    if (algId.getObjectId().equals(X9ObjectIdentifiers.id_dsa) || algId.getObjectId().equals(OIWObjectIdentifiers.dsaWithSHA1)) {
        DERInteger derY = (DERInteger) keyInfo.getPublicKey();
        DEREncodable de = keyInfo.getAlgorithmId().getParameters();
        DSAParameters parameters = null;
        if (de != null) {
            DSAParameter params = DSAParameter.getInstance(de.getDERObject());
            parameters = new DSAParameters(params.getP(), params.getQ(), params.getG());
        }
        return new DSAPublicKeyParameters(derY.getValue(), parameters);
    } else if (algId.getObjectId().equals(X9ObjectIdentifiers.id_ecPublicKey)) {
        X962Parameters params = new X962Parameters((DERObject) keyInfo.getAlgorithmId().getParameters());
        ECDomainParameters dParams = null;
        if (params.isNamedCurve()) {
            DERObjectIdentifier oid = (DERObjectIdentifier) params.getParameters();
            X9ECParameters ecP = X962NamedCurves.getByOID(oid);
            if (ecP == null) {
                ecP = SECNamedCurves.getByOID(oid);
                if (ecP == null) {
                    ecP = NISTNamedCurves.getByOID(oid);
                // BEGIN android-removed
                // if (ecP == null)
                // {
                //     ecP = TeleTrusTNamedCurves.getByOID(oid);
                // }
                // END android-removed
                }
            }
            dParams = new ECDomainParameters(ecP.getCurve(), ecP.getG(), ecP.getN(), ecP.getH(), ecP.getSeed());
        } else {
            X9ECParameters ecP = new X9ECParameters((ASN1Sequence) params.getParameters());
            dParams = new ECDomainParameters(ecP.getCurve(), ecP.getG(), ecP.getN(), ecP.getH(), ecP.getSeed());
        }
        DERBitString bits = keyInfo.getPublicKeyData();
        byte[] data = bits.getBytes();
        ASN1OctetString key = new DEROctetString(data);
        X9ECPoint derQ = new X9ECPoint(dParams.getCurve(), key);
        return new ECPublicKeyParameters(derQ.getPoint(), dParams);
    } else {
        throw new RuntimeException("algorithm identifier in key not recognised");
    }
}
Also used : ASN1OctetString(org.bouncycastle.asn1.ASN1OctetString) DHPublicKeyParameters(org.bouncycastle.crypto.params.DHPublicKeyParameters) ECDomainParameters(org.bouncycastle.crypto.params.ECDomainParameters) DHPublicKey(org.bouncycastle.asn1.x9.DHPublicKey) X9ECParameters(org.bouncycastle.asn1.x9.X9ECParameters) DHValidationParms(org.bouncycastle.asn1.x9.DHValidationParms) ECPublicKeyParameters(org.bouncycastle.crypto.params.ECPublicKeyParameters) RSAKeyParameters(org.bouncycastle.crypto.params.RSAKeyParameters) DEROctetString(org.bouncycastle.asn1.DEROctetString) AlgorithmIdentifier(org.bouncycastle.asn1.x509.AlgorithmIdentifier) DERInteger(org.bouncycastle.asn1.DERInteger) X962Parameters(org.bouncycastle.asn1.x9.X962Parameters) RSAPublicKeyStructure(org.bouncycastle.asn1.x509.RSAPublicKeyStructure) DHValidationParameters(org.bouncycastle.crypto.params.DHValidationParameters) DSAParameter(org.bouncycastle.asn1.x509.DSAParameter) DHParameter(org.bouncycastle.asn1.pkcs.DHParameter) DSAPublicKeyParameters(org.bouncycastle.crypto.params.DSAPublicKeyParameters) DHParameters(org.bouncycastle.crypto.params.DHParameters) DERBitString(org.bouncycastle.asn1.DERBitString) DERObjectIdentifier(org.bouncycastle.asn1.DERObjectIdentifier) X9ECPoint(org.bouncycastle.asn1.x9.X9ECPoint) X9ECPoint(org.bouncycastle.asn1.x9.X9ECPoint) DEREncodable(org.bouncycastle.asn1.DEREncodable) BigInteger(java.math.BigInteger) DHDomainParameters(org.bouncycastle.asn1.x9.DHDomainParameters) DSAParameters(org.bouncycastle.crypto.params.DSAParameters)

Example 62 with ASN1OctetString

use of org.bouncycastle.asn1.ASN1OctetString in project nhin-d by DirectProject.

the class SMIMECryptographerImpl method logDigests.

protected void logDigests(SignerInformation sigInfo) {
    // will fail
    if (this.m_logDigest && sigInfo != null) {
        try {
            //get the digests
            final Attribute digAttr = sigInfo.getSignedAttributes().get(CMSAttributes.messageDigest);
            final DERObject hashObj = digAttr.getAttrValues().getObjectAt(0).getDERObject();
            final byte[] signedDigest = ((ASN1OctetString) hashObj).getOctets();
            final String signedDigestHex = org.apache.commons.codec.binary.Hex.encodeHexString(signedDigest);
            LOGGER.info("Signed Message Digest: " + signedDigestHex);
            // should have the computed digest now
            final byte[] digest = sigInfo.getContentDigest();
            final String digestHex = org.apache.commons.codec.binary.Hex.encodeHexString(digest);
            LOGGER.info("Computed Message Digest: " + digestHex);
        } catch (Throwable t) {
        /* no-op.... logging digests is a quiet operation */
        }
    }
}
Also used : ASN1OctetString(org.bouncycastle.asn1.ASN1OctetString) DERObject(org.bouncycastle.asn1.DERObject) Attribute(org.bouncycastle.asn1.cms.Attribute) SMIMECapabilitiesAttribute(org.bouncycastle.asn1.smime.SMIMECapabilitiesAttribute) ASN1OctetString(org.bouncycastle.asn1.ASN1OctetString)

Example 63 with ASN1OctetString

use of org.bouncycastle.asn1.ASN1OctetString in project nhin-d by DirectProject.

the class SplitProviderDirectSignedDataGenerator method generate.

/**
	 * {@inheritDoc}
	 */
@Override
public CMSSignedData generate(String signedContentType, CMSProcessable content, boolean encapsulate, String sigProvider, boolean addDefaultAttributes) throws NoSuchAlgorithmException, NoSuchProviderException, CMSException {
    final ASN1EncodableVector digestAlgs = new ASN1EncodableVector();
    final ASN1EncodableVector signerInfos = new ASN1EncodableVector();
    // clear the current preserved digest state
    _digests.clear();
    //
    // add the SignerInfo objects
    //
    DERObjectIdentifier contentTypeOID;
    boolean isCounterSignature;
    if (signedContentType != null) {
        contentTypeOID = new DERObjectIdentifier(signedContentType);
        isCounterSignature = false;
    } else {
        contentTypeOID = CMSObjectIdentifiers.data;
        isCounterSignature = true;
    }
    for (DirectTargetedSignerInf signer : privateSigners) {
        AlgorithmIdentifier digAlgId;
        try {
            digAlgId = new AlgorithmIdentifier(new DERObjectIdentifier(signer.digestOID), new DERNull());
            digestAlgs.add(digAlgId);
            try {
                signerInfos.add(signer.toSignerInfo(contentTypeOID, content, rand, sigProvider, digestProvider, addDefaultAttributes, isCounterSignature));
            } catch (ClassCastException e) {
                // try again with the digest provider... the key may need to use a different provider than the sig provider
                signerInfos.add(signer.toSignerInfo(contentTypeOID, content, rand, digestProvider, digestProvider, addDefaultAttributes, isCounterSignature));
            }
        } catch (IOException e) {
            throw new CMSException("encoding error.", e);
        } catch (InvalidKeyException e) {
            throw new CMSException("key inappropriate for signature.", e);
        } catch (SignatureException e) {
            throw new CMSException("error creating signature.", e);
        } catch (CertificateEncodingException e) {
            throw new CMSException("error creating sid.", e);
        }
    }
    ASN1Set certificates = null;
    if (_certs.size() != 0) {
        certificates = createBerSetFromList(_certs);
    }
    ASN1Set certrevlist = null;
    if (_crls.size() != 0) {
        certrevlist = createBerSetFromList(_crls);
    }
    ContentInfo encInfo;
    if (encapsulate) {
        ByteArrayOutputStream bOut = new ByteArrayOutputStream();
        try {
            content.write(bOut);
        } catch (IOException e) {
            throw new CMSException("encapsulation error.", e);
        }
        ASN1OctetString octs = new BERConstructedOctetString(bOut.toByteArray());
        encInfo = new ContentInfo(contentTypeOID, octs);
    } else {
        encInfo = new ContentInfo(contentTypeOID, null);
    }
    SignedData sd = new SignedData(new DERSet(digestAlgs), encInfo, certificates, certrevlist, new DERSet(signerInfos));
    ContentInfo contentInfo = new ContentInfo(PKCSObjectIdentifiers.signedData, sd);
    return new CMSSignedData(content, contentInfo);
}
Also used : ASN1OctetString(org.bouncycastle.asn1.ASN1OctetString) SignedData(org.bouncycastle.asn1.cms.SignedData) CMSSignedData(org.bouncycastle.cms.CMSSignedData) CertificateEncodingException(java.security.cert.CertificateEncodingException) IOException(java.io.IOException) SignatureException(java.security.SignatureException) ByteArrayOutputStream(java.io.ByteArrayOutputStream) InvalidKeyException(java.security.InvalidKeyException) DERObjectIdentifier(org.bouncycastle.asn1.DERObjectIdentifier) DERSet(org.bouncycastle.asn1.DERSet) CMSSignedData(org.bouncycastle.cms.CMSSignedData) AlgorithmIdentifier(org.bouncycastle.asn1.x509.AlgorithmIdentifier) ASN1Set(org.bouncycastle.asn1.ASN1Set) ContentInfo(org.bouncycastle.asn1.cms.ContentInfo) DERNull(org.bouncycastle.asn1.DERNull) ASN1EncodableVector(org.bouncycastle.asn1.ASN1EncodableVector) BERConstructedOctetString(org.bouncycastle.asn1.BERConstructedOctetString) CMSException(org.bouncycastle.cms.CMSException)

Example 64 with ASN1OctetString

use of org.bouncycastle.asn1.ASN1OctetString in project robovm by robovm.

the class PKCS12KeyStoreSpi method engineGetCertificateChain.

public Certificate[] engineGetCertificateChain(String alias) {
    if (alias == null) {
        throw new IllegalArgumentException("null alias passed to getCertificateChain.");
    }
    if (!engineIsKeyEntry(alias)) {
        return null;
    }
    Certificate c = engineGetCertificate(alias);
    if (c != null) {
        Vector cs = new Vector();
        while (c != null) {
            X509Certificate x509c = (X509Certificate) c;
            Certificate nextC = null;
            byte[] bytes = x509c.getExtensionValue(Extension.authorityKeyIdentifier.getId());
            if (bytes != null) {
                try {
                    ASN1InputStream aIn = new ASN1InputStream(bytes);
                    byte[] authBytes = ((ASN1OctetString) aIn.readObject()).getOctets();
                    aIn = new ASN1InputStream(authBytes);
                    AuthorityKeyIdentifier id = AuthorityKeyIdentifier.getInstance(aIn.readObject());
                    if (id.getKeyIdentifier() != null) {
                        nextC = (Certificate) chainCerts.get(new CertId(id.getKeyIdentifier()));
                    }
                } catch (IOException e) {
                    throw new RuntimeException(e.toString());
                }
            }
            if (nextC == null) {
                //
                // no authority key id, try the Issuer DN
                //
                Principal i = x509c.getIssuerDN();
                Principal s = x509c.getSubjectDN();
                if (!i.equals(s)) {
                    Enumeration e = chainCerts.keys();
                    while (e.hasMoreElements()) {
                        X509Certificate crt = (X509Certificate) chainCerts.get(e.nextElement());
                        Principal sub = crt.getSubjectDN();
                        if (sub.equals(i)) {
                            try {
                                x509c.verify(crt.getPublicKey());
                                nextC = crt;
                                break;
                            } catch (Exception ex) {
                            // continue
                            }
                        }
                    }
                }
            }
            cs.addElement(c);
            if (// self signed - end of the chain
            nextC != c) {
                c = nextC;
            } else {
                c = null;
            }
        }
        Certificate[] certChain = new Certificate[cs.size()];
        for (int i = 0; i != certChain.length; i++) {
            certChain[i] = (Certificate) cs.elementAt(i);
        }
        return certChain;
    }
    return null;
}
Also used : ASN1OctetString(org.bouncycastle.asn1.ASN1OctetString) ASN1InputStream(org.bouncycastle.asn1.ASN1InputStream) Enumeration(java.util.Enumeration) AuthorityKeyIdentifier(org.bouncycastle.asn1.x509.AuthorityKeyIdentifier) IOException(java.io.IOException) X509Certificate(java.security.cert.X509Certificate) KeyStoreException(java.security.KeyStoreException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) CertificateEncodingException(java.security.cert.CertificateEncodingException) UnrecoverableKeyException(java.security.UnrecoverableKeyException) IOException(java.io.IOException) CertificateException(java.security.cert.CertificateException) Vector(java.util.Vector) ASN1EncodableVector(org.bouncycastle.asn1.ASN1EncodableVector) Principal(java.security.Principal) X509Certificate(java.security.cert.X509Certificate) Certificate(java.security.cert.Certificate)

Example 65 with ASN1OctetString

use of org.bouncycastle.asn1.ASN1OctetString in project robovm by robovm.

the class PKCS12KeyStoreSpi method engineLoad.

public void engineLoad(InputStream stream, char[] password) throws IOException {
    if (// just initialising
    stream == null) {
        return;
    }
    if (password == null) {
        throw new NullPointerException("No password supplied for PKCS#12 KeyStore.");
    }
    BufferedInputStream bufIn = new BufferedInputStream(stream);
    bufIn.mark(10);
    int head = bufIn.read();
    if (head != 0x30) {
        throw new IOException("stream does not represent a PKCS12 key store");
    }
    bufIn.reset();
    ASN1InputStream bIn = new ASN1InputStream(bufIn);
    ASN1Sequence obj = (ASN1Sequence) bIn.readObject();
    Pfx bag = Pfx.getInstance(obj);
    ContentInfo info = bag.getAuthSafe();
    Vector chain = new Vector();
    boolean unmarkedKey = false;
    boolean wrongPKCS12Zero = false;
    if (// check the mac code
    bag.getMacData() != null) {
        MacData mData = bag.getMacData();
        DigestInfo dInfo = mData.getMac();
        AlgorithmIdentifier algId = dInfo.getAlgorithmId();
        byte[] salt = mData.getSalt();
        int itCount = mData.getIterationCount().intValue();
        byte[] data = ((ASN1OctetString) info.getContent()).getOctets();
        try {
            byte[] res = calculatePbeMac(algId.getAlgorithm(), salt, itCount, password, false, data);
            byte[] dig = dInfo.getDigest();
            if (!Arrays.constantTimeAreEqual(res, dig)) {
                if (password.length > 0) {
                    throw new IOException("PKCS12 key store mac invalid - wrong password or corrupted file.");
                }
                // Try with incorrect zero length password
                res = calculatePbeMac(algId.getAlgorithm(), salt, itCount, password, true, data);
                if (!Arrays.constantTimeAreEqual(res, dig)) {
                    throw new IOException("PKCS12 key store mac invalid - wrong password or corrupted file.");
                }
                wrongPKCS12Zero = true;
            }
        } catch (IOException e) {
            throw e;
        } catch (Exception e) {
            throw new IOException("error constructing MAC: " + e.toString());
        }
    }
    keys = new IgnoresCaseHashtable();
    localIds = new Hashtable();
    if (info.getContentType().equals(data)) {
        bIn = new ASN1InputStream(((ASN1OctetString) info.getContent()).getOctets());
        AuthenticatedSafe authSafe = AuthenticatedSafe.getInstance(bIn.readObject());
        ContentInfo[] c = authSafe.getContentInfo();
        for (int i = 0; i != c.length; i++) {
            if (c[i].getContentType().equals(data)) {
                ASN1InputStream dIn = new ASN1InputStream(((ASN1OctetString) c[i].getContent()).getOctets());
                ASN1Sequence seq = (ASN1Sequence) dIn.readObject();
                for (int j = 0; j != seq.size(); j++) {
                    SafeBag b = SafeBag.getInstance(seq.getObjectAt(j));
                    if (b.getBagId().equals(pkcs8ShroudedKeyBag)) {
                        org.bouncycastle.asn1.pkcs.EncryptedPrivateKeyInfo eIn = org.bouncycastle.asn1.pkcs.EncryptedPrivateKeyInfo.getInstance(b.getBagValue());
                        PrivateKey privKey = unwrapKey(eIn.getEncryptionAlgorithm(), eIn.getEncryptedData(), password, wrongPKCS12Zero);
                        //
                        // set the attributes on the key
                        //
                        PKCS12BagAttributeCarrier bagAttr = (PKCS12BagAttributeCarrier) privKey;
                        String alias = null;
                        ASN1OctetString localId = null;
                        if (b.getBagAttributes() != null) {
                            Enumeration e = b.getBagAttributes().getObjects();
                            while (e.hasMoreElements()) {
                                ASN1Sequence sq = (ASN1Sequence) e.nextElement();
                                ASN1ObjectIdentifier aOid = (ASN1ObjectIdentifier) sq.getObjectAt(0);
                                ASN1Set attrSet = (ASN1Set) sq.getObjectAt(1);
                                ASN1Primitive attr = null;
                                if (attrSet.size() > 0) {
                                    attr = (ASN1Primitive) attrSet.getObjectAt(0);
                                    ASN1Encodable existing = bagAttr.getBagAttribute(aOid);
                                    if (existing != null) {
                                        // OK, but the value has to be the same
                                        if (!existing.toASN1Primitive().equals(attr)) {
                                            throw new IOException("attempt to add existing attribute with different value");
                                        }
                                    } else {
                                        bagAttr.setBagAttribute(aOid, attr);
                                    }
                                }
                                if (aOid.equals(pkcs_9_at_friendlyName)) {
                                    alias = ((DERBMPString) attr).getString();
                                    keys.put(alias, privKey);
                                } else if (aOid.equals(pkcs_9_at_localKeyId)) {
                                    localId = (ASN1OctetString) attr;
                                }
                            }
                        }
                        if (localId != null) {
                            String name = new String(Hex.encode(localId.getOctets()));
                            if (alias == null) {
                                keys.put(name, privKey);
                            } else {
                                localIds.put(alias, name);
                            }
                        } else {
                            unmarkedKey = true;
                            keys.put("unmarked", privKey);
                        }
                    } else if (b.getBagId().equals(certBag)) {
                        chain.addElement(b);
                    } else {
                        System.out.println("extra in data " + b.getBagId());
                        System.out.println(ASN1Dump.dumpAsString(b));
                    }
                }
            } else if (c[i].getContentType().equals(encryptedData)) {
                EncryptedData d = EncryptedData.getInstance(c[i].getContent());
                byte[] octets = cryptData(false, d.getEncryptionAlgorithm(), password, wrongPKCS12Zero, d.getContent().getOctets());
                ASN1Sequence seq = (ASN1Sequence) ASN1Primitive.fromByteArray(octets);
                for (int j = 0; j != seq.size(); j++) {
                    SafeBag b = SafeBag.getInstance(seq.getObjectAt(j));
                    if (b.getBagId().equals(certBag)) {
                        chain.addElement(b);
                    } else if (b.getBagId().equals(pkcs8ShroudedKeyBag)) {
                        org.bouncycastle.asn1.pkcs.EncryptedPrivateKeyInfo eIn = org.bouncycastle.asn1.pkcs.EncryptedPrivateKeyInfo.getInstance(b.getBagValue());
                        PrivateKey privKey = unwrapKey(eIn.getEncryptionAlgorithm(), eIn.getEncryptedData(), password, wrongPKCS12Zero);
                        //
                        // set the attributes on the key
                        //
                        PKCS12BagAttributeCarrier bagAttr = (PKCS12BagAttributeCarrier) privKey;
                        String alias = null;
                        ASN1OctetString localId = null;
                        Enumeration e = b.getBagAttributes().getObjects();
                        while (e.hasMoreElements()) {
                            ASN1Sequence sq = (ASN1Sequence) e.nextElement();
                            ASN1ObjectIdentifier aOid = (ASN1ObjectIdentifier) sq.getObjectAt(0);
                            ASN1Set attrSet = (ASN1Set) sq.getObjectAt(1);
                            ASN1Primitive attr = null;
                            if (attrSet.size() > 0) {
                                attr = (ASN1Primitive) attrSet.getObjectAt(0);
                                ASN1Encodable existing = bagAttr.getBagAttribute(aOid);
                                if (existing != null) {
                                    // OK, but the value has to be the same
                                    if (!existing.toASN1Primitive().equals(attr)) {
                                        throw new IOException("attempt to add existing attribute with different value");
                                    }
                                } else {
                                    bagAttr.setBagAttribute(aOid, attr);
                                }
                            }
                            if (aOid.equals(pkcs_9_at_friendlyName)) {
                                alias = ((DERBMPString) attr).getString();
                                keys.put(alias, privKey);
                            } else if (aOid.equals(pkcs_9_at_localKeyId)) {
                                localId = (ASN1OctetString) attr;
                            }
                        }
                        String name = new String(Hex.encode(localId.getOctets()));
                        if (alias == null) {
                            keys.put(name, privKey);
                        } else {
                            localIds.put(alias, name);
                        }
                    } else if (b.getBagId().equals(keyBag)) {
                        org.bouncycastle.asn1.pkcs.PrivateKeyInfo kInfo = org.bouncycastle.asn1.pkcs.PrivateKeyInfo.getInstance(b.getBagValue());
                        PrivateKey privKey = BouncyCastleProvider.getPrivateKey(kInfo);
                        //
                        // set the attributes on the key
                        //
                        PKCS12BagAttributeCarrier bagAttr = (PKCS12BagAttributeCarrier) privKey;
                        String alias = null;
                        ASN1OctetString localId = null;
                        Enumeration e = b.getBagAttributes().getObjects();
                        while (e.hasMoreElements()) {
                            ASN1Sequence sq = (ASN1Sequence) e.nextElement();
                            ASN1ObjectIdentifier aOid = (ASN1ObjectIdentifier) sq.getObjectAt(0);
                            ASN1Set attrSet = (ASN1Set) sq.getObjectAt(1);
                            ASN1Primitive attr = null;
                            if (attrSet.size() > 0) {
                                attr = (ASN1Primitive) attrSet.getObjectAt(0);
                                ASN1Encodable existing = bagAttr.getBagAttribute(aOid);
                                if (existing != null) {
                                    // OK, but the value has to be the same
                                    if (!existing.toASN1Primitive().equals(attr)) {
                                        throw new IOException("attempt to add existing attribute with different value");
                                    }
                                } else {
                                    bagAttr.setBagAttribute(aOid, attr);
                                }
                            }
                            if (aOid.equals(pkcs_9_at_friendlyName)) {
                                alias = ((DERBMPString) attr).getString();
                                keys.put(alias, privKey);
                            } else if (aOid.equals(pkcs_9_at_localKeyId)) {
                                localId = (ASN1OctetString) attr;
                            }
                        }
                        String name = new String(Hex.encode(localId.getOctets()));
                        if (alias == null) {
                            keys.put(name, privKey);
                        } else {
                            localIds.put(alias, name);
                        }
                    } else {
                        System.out.println("extra in encryptedData " + b.getBagId());
                        System.out.println(ASN1Dump.dumpAsString(b));
                    }
                }
            } else {
                System.out.println("extra " + c[i].getContentType().getId());
                System.out.println("extra " + ASN1Dump.dumpAsString(c[i].getContent()));
            }
        }
    }
    certs = new IgnoresCaseHashtable();
    chainCerts = new Hashtable();
    keyCerts = new Hashtable();
    for (int i = 0; i != chain.size(); i++) {
        SafeBag b = (SafeBag) chain.elementAt(i);
        CertBag cb = CertBag.getInstance(b.getBagValue());
        if (!cb.getCertId().equals(x509Certificate)) {
            throw new RuntimeException("Unsupported certificate type: " + cb.getCertId());
        }
        Certificate cert;
        try {
            ByteArrayInputStream cIn = new ByteArrayInputStream(((ASN1OctetString) cb.getCertValue()).getOctets());
            cert = certFact.generateCertificate(cIn);
        } catch (Exception e) {
            throw new RuntimeException(e.toString());
        }
        //
        // set the attributes
        //
        ASN1OctetString localId = null;
        String alias = null;
        if (b.getBagAttributes() != null) {
            Enumeration e = b.getBagAttributes().getObjects();
            while (e.hasMoreElements()) {
                ASN1Sequence sq = (ASN1Sequence) e.nextElement();
                ASN1ObjectIdentifier oid = (ASN1ObjectIdentifier) sq.getObjectAt(0);
                ASN1Primitive attr = (ASN1Primitive) ((ASN1Set) sq.getObjectAt(1)).getObjectAt(0);
                PKCS12BagAttributeCarrier bagAttr = null;
                if (cert instanceof PKCS12BagAttributeCarrier) {
                    bagAttr = (PKCS12BagAttributeCarrier) cert;
                    ASN1Encodable existing = bagAttr.getBagAttribute(oid);
                    if (existing != null) {
                        // OK, but the value has to be the same
                        if (!existing.toASN1Primitive().equals(attr)) {
                            throw new IOException("attempt to add existing attribute with different value");
                        }
                    } else {
                        bagAttr.setBagAttribute(oid, attr);
                    }
                }
                if (oid.equals(pkcs_9_at_friendlyName)) {
                    alias = ((DERBMPString) attr).getString();
                } else if (oid.equals(pkcs_9_at_localKeyId)) {
                    localId = (ASN1OctetString) attr;
                }
            }
        }
        chainCerts.put(new CertId(cert.getPublicKey()), cert);
        if (unmarkedKey) {
            if (keyCerts.isEmpty()) {
                String name = new String(Hex.encode(createSubjectKeyId(cert.getPublicKey()).getKeyIdentifier()));
                keyCerts.put(name, cert);
                keys.put(name, keys.remove("unmarked"));
            }
        } else {
            //
            if (localId != null) {
                String name = new String(Hex.encode(localId.getOctets()));
                keyCerts.put(name, cert);
            }
            if (alias != null) {
                certs.put(alias, cert);
            }
        }
    }
}
Also used : ASN1OctetString(org.bouncycastle.asn1.ASN1OctetString) PrivateKey(java.security.PrivateKey) AuthenticatedSafe(org.bouncycastle.asn1.pkcs.AuthenticatedSafe) ASN1OctetString(org.bouncycastle.asn1.ASN1OctetString) DERBMPString(org.bouncycastle.asn1.DERBMPString) DEROctetString(org.bouncycastle.asn1.DEROctetString) BEROctetString(org.bouncycastle.asn1.BEROctetString) PKCS12BagAttributeCarrier(org.bouncycastle.jce.interfaces.PKCS12BagAttributeCarrier) AlgorithmIdentifier(org.bouncycastle.asn1.x509.AlgorithmIdentifier) BufferedInputStream(java.io.BufferedInputStream) ContentInfo(org.bouncycastle.asn1.pkcs.ContentInfo) ASN1Encodable(org.bouncycastle.asn1.ASN1Encodable) EncryptedData(org.bouncycastle.asn1.pkcs.EncryptedData) Vector(java.util.Vector) ASN1EncodableVector(org.bouncycastle.asn1.ASN1EncodableVector) MacData(org.bouncycastle.asn1.pkcs.MacData) ASN1InputStream(org.bouncycastle.asn1.ASN1InputStream) Pfx(org.bouncycastle.asn1.pkcs.Pfx) Enumeration(java.util.Enumeration) DERBMPString(org.bouncycastle.asn1.DERBMPString) Hashtable(java.util.Hashtable) IOException(java.io.IOException) SafeBag(org.bouncycastle.asn1.pkcs.SafeBag) KeyStoreException(java.security.KeyStoreException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) CertificateEncodingException(java.security.cert.CertificateEncodingException) UnrecoverableKeyException(java.security.UnrecoverableKeyException) IOException(java.io.IOException) CertificateException(java.security.cert.CertificateException) ASN1Sequence(org.bouncycastle.asn1.ASN1Sequence) CertBag(org.bouncycastle.asn1.pkcs.CertBag) ASN1Set(org.bouncycastle.asn1.ASN1Set) ByteArrayInputStream(java.io.ByteArrayInputStream) DigestInfo(org.bouncycastle.asn1.x509.DigestInfo) ASN1Primitive(org.bouncycastle.asn1.ASN1Primitive) ASN1ObjectIdentifier(org.bouncycastle.asn1.ASN1ObjectIdentifier) X509Certificate(java.security.cert.X509Certificate) Certificate(java.security.cert.Certificate)

Aggregations

ASN1OctetString (org.bouncycastle.asn1.ASN1OctetString)89 IOException (java.io.IOException)40 DEROctetString (org.bouncycastle.asn1.DEROctetString)26 ASN1ObjectIdentifier (org.bouncycastle.asn1.ASN1ObjectIdentifier)24 ASN1Sequence (org.bouncycastle.asn1.ASN1Sequence)24 ASN1InputStream (org.bouncycastle.asn1.ASN1InputStream)23 ASN1Encodable (org.bouncycastle.asn1.ASN1Encodable)17 ByteArrayInputStream (java.io.ByteArrayInputStream)16 X509Certificate (java.security.cert.X509Certificate)16 ASN1Integer (org.bouncycastle.asn1.ASN1Integer)16 ASN1EncodableVector (org.bouncycastle.asn1.ASN1EncodableVector)15 AlgorithmIdentifier (org.bouncycastle.asn1.x509.AlgorithmIdentifier)15 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)12 CertificateException (java.security.cert.CertificateException)12 Enumeration (java.util.Enumeration)12 ASN1TaggedObject (org.bouncycastle.asn1.ASN1TaggedObject)12 DERBitString (org.bouncycastle.asn1.DERBitString)12 DERBMPString (org.bouncycastle.asn1.DERBMPString)11 DERIA5String (org.bouncycastle.asn1.DERIA5String)11 DERSequence (org.bouncycastle.asn1.DERSequence)11