Search in sources :

Example 1 with DERBMPString

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

the class PKCS12KeyStoreSpi method doStore.

private void doStore(OutputStream stream, char[] password, boolean useDEREncoding) throws IOException {
    if (password == null) {
        throw new NullPointerException("No password supplied for PKCS#12 KeyStore.");
    }
    //
    // handle the key
    //
    ASN1EncodableVector keyS = new ASN1EncodableVector();
    Enumeration ks = keys.keys();
    while (ks.hasMoreElements()) {
        byte[] kSalt = new byte[SALT_SIZE];
        random.nextBytes(kSalt);
        String name = (String) ks.nextElement();
        PrivateKey privKey = (PrivateKey) keys.get(name);
        PKCS12PBEParams kParams = new PKCS12PBEParams(kSalt, MIN_ITERATIONS);
        byte[] kBytes = wrapKey(keyAlgorithm.getId(), privKey, kParams, password);
        AlgorithmIdentifier kAlgId = new AlgorithmIdentifier(keyAlgorithm, kParams.toASN1Primitive());
        org.bouncycastle.asn1.pkcs.EncryptedPrivateKeyInfo kInfo = new org.bouncycastle.asn1.pkcs.EncryptedPrivateKeyInfo(kAlgId, kBytes);
        boolean attrSet = false;
        ASN1EncodableVector kName = new ASN1EncodableVector();
        if (privKey instanceof PKCS12BagAttributeCarrier) {
            PKCS12BagAttributeCarrier bagAttrs = (PKCS12BagAttributeCarrier) privKey;
            //
            // make sure we are using the local alias on store
            //
            DERBMPString nm = (DERBMPString) bagAttrs.getBagAttribute(pkcs_9_at_friendlyName);
            if (nm == null || !nm.getString().equals(name)) {
                bagAttrs.setBagAttribute(pkcs_9_at_friendlyName, new DERBMPString(name));
            }
            //
            if (bagAttrs.getBagAttribute(pkcs_9_at_localKeyId) == null) {
                Certificate ct = engineGetCertificate(name);
                bagAttrs.setBagAttribute(pkcs_9_at_localKeyId, createSubjectKeyId(ct.getPublicKey()));
            }
            Enumeration e = bagAttrs.getBagAttributeKeys();
            while (e.hasMoreElements()) {
                ASN1ObjectIdentifier oid = (ASN1ObjectIdentifier) e.nextElement();
                ASN1EncodableVector kSeq = new ASN1EncodableVector();
                kSeq.add(oid);
                kSeq.add(new DERSet(bagAttrs.getBagAttribute(oid)));
                attrSet = true;
                kName.add(new DERSequence(kSeq));
            }
        }
        if (!attrSet) {
            //
            // set a default friendly name (from the key id) and local id
            //
            ASN1EncodableVector kSeq = new ASN1EncodableVector();
            Certificate ct = engineGetCertificate(name);
            kSeq.add(pkcs_9_at_localKeyId);
            kSeq.add(new DERSet(createSubjectKeyId(ct.getPublicKey())));
            kName.add(new DERSequence(kSeq));
            kSeq = new ASN1EncodableVector();
            kSeq.add(pkcs_9_at_friendlyName);
            kSeq.add(new DERSet(new DERBMPString(name)));
            kName.add(new DERSequence(kSeq));
        }
        SafeBag kBag = new SafeBag(pkcs8ShroudedKeyBag, kInfo.toASN1Primitive(), new DERSet(kName));
        keyS.add(kBag);
    }
    byte[] keySEncoded = new DERSequence(keyS).getEncoded(ASN1Encoding.DER);
    BEROctetString keyString = new BEROctetString(keySEncoded);
    //
    // certificate processing
    //
    byte[] cSalt = new byte[SALT_SIZE];
    random.nextBytes(cSalt);
    ASN1EncodableVector certSeq = new ASN1EncodableVector();
    PKCS12PBEParams cParams = new PKCS12PBEParams(cSalt, MIN_ITERATIONS);
    AlgorithmIdentifier cAlgId = new AlgorithmIdentifier(certAlgorithm, cParams.toASN1Primitive());
    Hashtable doneCerts = new Hashtable();
    Enumeration cs = keys.keys();
    while (cs.hasMoreElements()) {
        try {
            String name = (String) cs.nextElement();
            Certificate cert = engineGetCertificate(name);
            boolean cAttrSet = false;
            CertBag cBag = new CertBag(x509Certificate, new DEROctetString(cert.getEncoded()));
            ASN1EncodableVector fName = new ASN1EncodableVector();
            if (cert instanceof PKCS12BagAttributeCarrier) {
                PKCS12BagAttributeCarrier bagAttrs = (PKCS12BagAttributeCarrier) cert;
                //
                // make sure we are using the local alias on store
                //
                DERBMPString nm = (DERBMPString) bagAttrs.getBagAttribute(pkcs_9_at_friendlyName);
                if (nm == null || !nm.getString().equals(name)) {
                    bagAttrs.setBagAttribute(pkcs_9_at_friendlyName, new DERBMPString(name));
                }
                //
                if (bagAttrs.getBagAttribute(pkcs_9_at_localKeyId) == null) {
                    bagAttrs.setBagAttribute(pkcs_9_at_localKeyId, createSubjectKeyId(cert.getPublicKey()));
                }
                Enumeration e = bagAttrs.getBagAttributeKeys();
                while (e.hasMoreElements()) {
                    ASN1ObjectIdentifier oid = (ASN1ObjectIdentifier) e.nextElement();
                    ASN1EncodableVector fSeq = new ASN1EncodableVector();
                    fSeq.add(oid);
                    fSeq.add(new DERSet(bagAttrs.getBagAttribute(oid)));
                    fName.add(new DERSequence(fSeq));
                    cAttrSet = true;
                }
            }
            if (!cAttrSet) {
                ASN1EncodableVector fSeq = new ASN1EncodableVector();
                fSeq.add(pkcs_9_at_localKeyId);
                fSeq.add(new DERSet(createSubjectKeyId(cert.getPublicKey())));
                fName.add(new DERSequence(fSeq));
                fSeq = new ASN1EncodableVector();
                fSeq.add(pkcs_9_at_friendlyName);
                fSeq.add(new DERSet(new DERBMPString(name)));
                fName.add(new DERSequence(fSeq));
            }
            SafeBag sBag = new SafeBag(certBag, cBag.toASN1Primitive(), new DERSet(fName));
            certSeq.add(sBag);
            doneCerts.put(cert, cert);
        } catch (CertificateEncodingException e) {
            throw new IOException("Error encoding certificate: " + e.toString());
        }
    }
    cs = certs.keys();
    while (cs.hasMoreElements()) {
        try {
            String certId = (String) cs.nextElement();
            Certificate cert = (Certificate) certs.get(certId);
            boolean cAttrSet = false;
            if (keys.get(certId) != null) {
                continue;
            }
            CertBag cBag = new CertBag(x509Certificate, new DEROctetString(cert.getEncoded()));
            ASN1EncodableVector fName = new ASN1EncodableVector();
            if (cert instanceof PKCS12BagAttributeCarrier) {
                PKCS12BagAttributeCarrier bagAttrs = (PKCS12BagAttributeCarrier) cert;
                //
                // make sure we are using the local alias on store
                //
                DERBMPString nm = (DERBMPString) bagAttrs.getBagAttribute(pkcs_9_at_friendlyName);
                if (nm == null || !nm.getString().equals(certId)) {
                    bagAttrs.setBagAttribute(pkcs_9_at_friendlyName, new DERBMPString(certId));
                }
                Enumeration e = bagAttrs.getBagAttributeKeys();
                while (e.hasMoreElements()) {
                    ASN1ObjectIdentifier oid = (ASN1ObjectIdentifier) e.nextElement();
                    // If we find one, we'll prune it out.
                    if (oid.equals(PKCSObjectIdentifiers.pkcs_9_at_localKeyId)) {
                        continue;
                    }
                    ASN1EncodableVector fSeq = new ASN1EncodableVector();
                    fSeq.add(oid);
                    fSeq.add(new DERSet(bagAttrs.getBagAttribute(oid)));
                    fName.add(new DERSequence(fSeq));
                    cAttrSet = true;
                }
            }
            if (!cAttrSet) {
                ASN1EncodableVector fSeq = new ASN1EncodableVector();
                fSeq.add(pkcs_9_at_friendlyName);
                fSeq.add(new DERSet(new DERBMPString(certId)));
                fName.add(new DERSequence(fSeq));
            }
            SafeBag sBag = new SafeBag(certBag, cBag.toASN1Primitive(), new DERSet(fName));
            certSeq.add(sBag);
            doneCerts.put(cert, cert);
        } catch (CertificateEncodingException e) {
            throw new IOException("Error encoding certificate: " + e.toString());
        }
    }
    cs = chainCerts.keys();
    while (cs.hasMoreElements()) {
        try {
            CertId certId = (CertId) cs.nextElement();
            Certificate cert = (Certificate) chainCerts.get(certId);
            if (doneCerts.get(cert) != null) {
                continue;
            }
            CertBag cBag = new CertBag(x509Certificate, new DEROctetString(cert.getEncoded()));
            ASN1EncodableVector fName = new ASN1EncodableVector();
            if (cert instanceof PKCS12BagAttributeCarrier) {
                PKCS12BagAttributeCarrier bagAttrs = (PKCS12BagAttributeCarrier) cert;
                Enumeration e = bagAttrs.getBagAttributeKeys();
                while (e.hasMoreElements()) {
                    ASN1ObjectIdentifier oid = (ASN1ObjectIdentifier) e.nextElement();
                    // If we find one, we'll prune it out.
                    if (oid.equals(PKCSObjectIdentifiers.pkcs_9_at_localKeyId)) {
                        continue;
                    }
                    ASN1EncodableVector fSeq = new ASN1EncodableVector();
                    fSeq.add(oid);
                    fSeq.add(new DERSet(bagAttrs.getBagAttribute(oid)));
                    fName.add(new DERSequence(fSeq));
                }
            }
            SafeBag sBag = new SafeBag(certBag, cBag.toASN1Primitive(), new DERSet(fName));
            certSeq.add(sBag);
        } catch (CertificateEncodingException e) {
            throw new IOException("Error encoding certificate: " + e.toString());
        }
    }
    byte[] certSeqEncoded = new DERSequence(certSeq).getEncoded(ASN1Encoding.DER);
    byte[] certBytes = cryptData(true, cAlgId, password, false, certSeqEncoded);
    EncryptedData cInfo = new EncryptedData(data, cAlgId, new BEROctetString(certBytes));
    ContentInfo[] info = new ContentInfo[] { new ContentInfo(data, keyString), new ContentInfo(encryptedData, cInfo.toASN1Primitive()) };
    AuthenticatedSafe auth = new AuthenticatedSafe(info);
    ByteArrayOutputStream bOut = new ByteArrayOutputStream();
    DEROutputStream asn1Out;
    if (useDEREncoding) {
        asn1Out = new DEROutputStream(bOut);
    } else {
        asn1Out = new BEROutputStream(bOut);
    }
    asn1Out.writeObject(auth);
    byte[] pkg = bOut.toByteArray();
    ContentInfo mainInfo = new ContentInfo(data, new BEROctetString(pkg));
    //
    // create the mac
    //
    byte[] mSalt = new byte[20];
    int itCount = MIN_ITERATIONS;
    random.nextBytes(mSalt);
    byte[] data = ((ASN1OctetString) mainInfo.getContent()).getOctets();
    MacData mData;
    try {
        byte[] res = calculatePbeMac(id_SHA1, mSalt, itCount, password, false, data);
        AlgorithmIdentifier algId = new AlgorithmIdentifier(id_SHA1, DERNull.INSTANCE);
        DigestInfo dInfo = new DigestInfo(algId, res);
        mData = new MacData(dInfo, mSalt, itCount);
    } catch (Exception e) {
        throw new IOException("error constructing MAC: " + e.toString());
    }
    //
    // output the Pfx
    //
    Pfx pfx = new Pfx(mainInfo, mData);
    if (useDEREncoding) {
        asn1Out = new DEROutputStream(stream);
    } else {
        asn1Out = new BEROutputStream(stream);
    }
    asn1Out.writeObject(pfx);
}
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) DERSet(org.bouncycastle.asn1.DERSet) PKCS12BagAttributeCarrier(org.bouncycastle.jce.interfaces.PKCS12BagAttributeCarrier) DEROctetString(org.bouncycastle.asn1.DEROctetString) AlgorithmIdentifier(org.bouncycastle.asn1.x509.AlgorithmIdentifier) DERSequence(org.bouncycastle.asn1.DERSequence) BEROctetString(org.bouncycastle.asn1.BEROctetString) ContentInfo(org.bouncycastle.asn1.pkcs.ContentInfo) ASN1EncodableVector(org.bouncycastle.asn1.ASN1EncodableVector) EncryptedData(org.bouncycastle.asn1.pkcs.EncryptedData) MacData(org.bouncycastle.asn1.pkcs.MacData) Enumeration(java.util.Enumeration) DERBMPString(org.bouncycastle.asn1.DERBMPString) Pfx(org.bouncycastle.asn1.pkcs.Pfx) Hashtable(java.util.Hashtable) BEROutputStream(org.bouncycastle.asn1.BEROutputStream) CertificateEncodingException(java.security.cert.CertificateEncodingException) IOException(java.io.IOException) ByteArrayOutputStream(java.io.ByteArrayOutputStream) 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) CertBag(org.bouncycastle.asn1.pkcs.CertBag) PKCS12PBEParams(org.bouncycastle.asn1.pkcs.PKCS12PBEParams) DigestInfo(org.bouncycastle.asn1.x509.DigestInfo) ASN1ObjectIdentifier(org.bouncycastle.asn1.ASN1ObjectIdentifier) X509Certificate(java.security.cert.X509Certificate) Certificate(java.security.cert.Certificate) DEROutputStream(org.bouncycastle.asn1.DEROutputStream)

Example 2 with DERBMPString

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

the class ASN1Dump method _dumpAsString.

/**
     * dump a DER object as a formatted string with indentation
     *
     * @param obj the ASN1Primitive to be dumped out.
     */
static void _dumpAsString(String indent, boolean verbose, ASN1Primitive obj, StringBuffer buf) {
    String nl = System.getProperty("line.separator");
    if (obj instanceof ASN1Sequence) {
        Enumeration e = ((ASN1Sequence) obj).getObjects();
        String tab = indent + TAB;
        buf.append(indent);
        if (obj instanceof BERSequence) {
            buf.append("BER Sequence");
        } else if (obj instanceof DERSequence) {
            buf.append("DER Sequence");
        } else {
            buf.append("Sequence");
        }
        buf.append(nl);
        while (e.hasMoreElements()) {
            Object o = e.nextElement();
            if (o == null || o.equals(DERNull.INSTANCE)) {
                buf.append(tab);
                buf.append("NULL");
                buf.append(nl);
            } else if (o instanceof ASN1Primitive) {
                _dumpAsString(tab, verbose, (ASN1Primitive) o, buf);
            } else {
                _dumpAsString(tab, verbose, ((ASN1Encodable) o).toASN1Primitive(), buf);
            }
        }
    } else if (obj instanceof ASN1TaggedObject) {
        String tab = indent + TAB;
        buf.append(indent);
        if (obj instanceof BERTaggedObject) {
            buf.append("BER Tagged [");
        } else {
            buf.append("Tagged [");
        }
        ASN1TaggedObject o = (ASN1TaggedObject) obj;
        buf.append(Integer.toString(o.getTagNo()));
        buf.append(']');
        if (!o.isExplicit()) {
            buf.append(" IMPLICIT ");
        }
        buf.append(nl);
        if (o.isEmpty()) {
            buf.append(tab);
            buf.append("EMPTY");
            buf.append(nl);
        } else {
            _dumpAsString(tab, verbose, o.getObject(), buf);
        }
    } else if (obj instanceof ASN1Set) {
        Enumeration e = ((ASN1Set) obj).getObjects();
        String tab = indent + TAB;
        buf.append(indent);
        if (obj instanceof BERSet) {
            buf.append("BER Set");
        } else {
            buf.append("DER Set");
        }
        buf.append(nl);
        while (e.hasMoreElements()) {
            Object o = e.nextElement();
            if (o == null) {
                buf.append(tab);
                buf.append("NULL");
                buf.append(nl);
            } else if (o instanceof ASN1Primitive) {
                _dumpAsString(tab, verbose, (ASN1Primitive) o, buf);
            } else {
                _dumpAsString(tab, verbose, ((ASN1Encodable) o).toASN1Primitive(), buf);
            }
        }
    } else if (obj instanceof ASN1OctetString) {
        ASN1OctetString oct = (ASN1OctetString) obj;
        if (obj instanceof BEROctetString || obj instanceof BERConstructedOctetString) {
            buf.append(indent + "BER Constructed Octet String" + "[" + oct.getOctets().length + "] ");
        } else {
            buf.append(indent + "DER Octet String" + "[" + oct.getOctets().length + "] ");
        }
        if (verbose) {
            buf.append(dumpBinaryDataAsString(indent, oct.getOctets()));
        } else {
            buf.append(nl);
        }
    } else if (obj instanceof ASN1ObjectIdentifier) {
        buf.append(indent + "ObjectIdentifier(" + ((ASN1ObjectIdentifier) obj).getId() + ")" + nl);
    } else if (obj instanceof DERBoolean) {
        buf.append(indent + "Boolean(" + ((DERBoolean) obj).isTrue() + ")" + nl);
    } else if (obj instanceof ASN1Integer) {
        buf.append(indent + "Integer(" + ((ASN1Integer) obj).getValue() + ")" + nl);
    } else if (obj instanceof DERBitString) {
        DERBitString bt = (DERBitString) obj;
        buf.append(indent + "DER Bit String" + "[" + bt.getBytes().length + ", " + bt.getPadBits() + "] ");
        if (verbose) {
            buf.append(dumpBinaryDataAsString(indent, bt.getBytes()));
        } else {
            buf.append(nl);
        }
    } else if (obj instanceof DERIA5String) {
        buf.append(indent + "IA5String(" + ((DERIA5String) obj).getString() + ") " + nl);
    } else if (obj instanceof DERUTF8String) {
        buf.append(indent + "UTF8String(" + ((DERUTF8String) obj).getString() + ") " + nl);
    } else if (obj instanceof DERPrintableString) {
        buf.append(indent + "PrintableString(" + ((DERPrintableString) obj).getString() + ") " + nl);
    } else if (obj instanceof DERVisibleString) {
        buf.append(indent + "VisibleString(" + ((DERVisibleString) obj).getString() + ") " + nl);
    } else if (obj instanceof DERBMPString) {
        buf.append(indent + "BMPString(" + ((DERBMPString) obj).getString() + ") " + nl);
    } else if (obj instanceof DERT61String) {
        buf.append(indent + "T61String(" + ((DERT61String) obj).getString() + ") " + nl);
    } else if (obj instanceof DERUTCTime) {
        buf.append(indent + "UTCTime(" + ((DERUTCTime) obj).getTime() + ") " + nl);
    } else if (obj instanceof DERGeneralizedTime) {
        buf.append(indent + "GeneralizedTime(" + ((DERGeneralizedTime) obj).getTime() + ") " + nl);
    } else if (obj instanceof BERApplicationSpecific) {
        buf.append(outputApplicationSpecific("BER", indent, verbose, obj, nl));
    } else if (obj instanceof DERApplicationSpecific) {
        buf.append(outputApplicationSpecific("DER", indent, verbose, obj, nl));
    } else if (obj instanceof DEREnumerated) {
        DEREnumerated en = (DEREnumerated) obj;
        buf.append(indent + "DER Enumerated(" + en.getValue() + ")" + nl);
    } else if (obj instanceof DERExternal) {
        DERExternal ext = (DERExternal) obj;
        buf.append(indent + "External " + nl);
        String tab = indent + TAB;
        if (ext.getDirectReference() != null) {
            buf.append(tab + "Direct Reference: " + ext.getDirectReference().getId() + nl);
        }
        if (ext.getIndirectReference() != null) {
            buf.append(tab + "Indirect Reference: " + ext.getIndirectReference().toString() + nl);
        }
        if (ext.getDataValueDescriptor() != null) {
            _dumpAsString(tab, verbose, ext.getDataValueDescriptor(), buf);
        }
        buf.append(tab + "Encoding: " + ext.getEncoding() + nl);
        _dumpAsString(tab, verbose, ext.getExternalContent(), buf);
    } else {
        buf.append(indent + obj.toString() + nl);
    }
}
Also used : ASN1OctetString(org.bouncycastle.asn1.ASN1OctetString) DERUTF8String(org.bouncycastle.asn1.DERUTF8String) DERApplicationSpecific(org.bouncycastle.asn1.DERApplicationSpecific) ASN1TaggedObject(org.bouncycastle.asn1.ASN1TaggedObject) DERBitString(org.bouncycastle.asn1.DERBitString) BERConstructedOctetString(org.bouncycastle.asn1.BERConstructedOctetString) BEROctetString(org.bouncycastle.asn1.BEROctetString) ASN1OctetString(org.bouncycastle.asn1.ASN1OctetString) DERBMPString(org.bouncycastle.asn1.DERBMPString) DERIA5String(org.bouncycastle.asn1.DERIA5String) DERUTF8String(org.bouncycastle.asn1.DERUTF8String) DERT61String(org.bouncycastle.asn1.DERT61String) DERPrintableString(org.bouncycastle.asn1.DERPrintableString) DERVisibleString(org.bouncycastle.asn1.DERVisibleString) DERSequence(org.bouncycastle.asn1.DERSequence) DERIA5String(org.bouncycastle.asn1.DERIA5String) BEROctetString(org.bouncycastle.asn1.BEROctetString) DERGeneralizedTime(org.bouncycastle.asn1.DERGeneralizedTime) DERUTCTime(org.bouncycastle.asn1.DERUTCTime) DERExternal(org.bouncycastle.asn1.DERExternal) DERPrintableString(org.bouncycastle.asn1.DERPrintableString) DERVisibleString(org.bouncycastle.asn1.DERVisibleString) BERTaggedObject(org.bouncycastle.asn1.BERTaggedObject) BERApplicationSpecific(org.bouncycastle.asn1.BERApplicationSpecific) ASN1Encodable(org.bouncycastle.asn1.ASN1Encodable) BERConstructedOctetString(org.bouncycastle.asn1.BERConstructedOctetString) DERBoolean(org.bouncycastle.asn1.DERBoolean) BERSet(org.bouncycastle.asn1.BERSet) Enumeration(java.util.Enumeration) DERBMPString(org.bouncycastle.asn1.DERBMPString) BERSequence(org.bouncycastle.asn1.BERSequence) DERBitString(org.bouncycastle.asn1.DERBitString) ASN1Integer(org.bouncycastle.asn1.ASN1Integer) ASN1Sequence(org.bouncycastle.asn1.ASN1Sequence) DEREnumerated(org.bouncycastle.asn1.DEREnumerated) ASN1Set(org.bouncycastle.asn1.ASN1Set) DERT61String(org.bouncycastle.asn1.DERT61String) BERTaggedObject(org.bouncycastle.asn1.BERTaggedObject) ASN1TaggedObject(org.bouncycastle.asn1.ASN1TaggedObject) ASN1Primitive(org.bouncycastle.asn1.ASN1Primitive) ASN1ObjectIdentifier(org.bouncycastle.asn1.ASN1ObjectIdentifier)

Example 3 with DERBMPString

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

the class JDKPKCS12KeyStore method doStore.

private void doStore(OutputStream stream, char[] password, boolean useDEREncoding) throws IOException {
    if (password == null) {
        throw new NullPointerException("No password supplied for PKCS#12 KeyStore.");
    }
    //
    // handle the key
    //
    ASN1EncodableVector keyS = new ASN1EncodableVector();
    Enumeration ks = keys.keys();
    while (ks.hasMoreElements()) {
        byte[] kSalt = new byte[SALT_SIZE];
        random.nextBytes(kSalt);
        String name = (String) ks.nextElement();
        PrivateKey privKey = (PrivateKey) keys.get(name);
        PKCS12PBEParams kParams = new PKCS12PBEParams(kSalt, MIN_ITERATIONS);
        byte[] kBytes = wrapKey(keyAlgorithm.getId(), privKey, kParams, password);
        AlgorithmIdentifier kAlgId = new AlgorithmIdentifier(keyAlgorithm, kParams.getDERObject());
        org.bouncycastle.asn1.pkcs.EncryptedPrivateKeyInfo kInfo = new org.bouncycastle.asn1.pkcs.EncryptedPrivateKeyInfo(kAlgId, kBytes);
        boolean attrSet = false;
        ASN1EncodableVector kName = new ASN1EncodableVector();
        if (privKey instanceof PKCS12BagAttributeCarrier) {
            PKCS12BagAttributeCarrier bagAttrs = (PKCS12BagAttributeCarrier) privKey;
            //
            // make sure we are using the local alias on store
            //
            DERBMPString nm = (DERBMPString) bagAttrs.getBagAttribute(pkcs_9_at_friendlyName);
            if (nm == null || !nm.getString().equals(name)) {
                bagAttrs.setBagAttribute(pkcs_9_at_friendlyName, new DERBMPString(name));
            }
            //
            if (bagAttrs.getBagAttribute(pkcs_9_at_localKeyId) == null) {
                Certificate ct = engineGetCertificate(name);
                bagAttrs.setBagAttribute(pkcs_9_at_localKeyId, createSubjectKeyId(ct.getPublicKey()));
            }
            Enumeration e = bagAttrs.getBagAttributeKeys();
            while (e.hasMoreElements()) {
                DERObjectIdentifier oid = (DERObjectIdentifier) e.nextElement();
                ASN1EncodableVector kSeq = new ASN1EncodableVector();
                kSeq.add(oid);
                kSeq.add(new DERSet(bagAttrs.getBagAttribute(oid)));
                attrSet = true;
                kName.add(new DERSequence(kSeq));
            }
        }
        if (!attrSet) {
            //
            // set a default friendly name (from the key id) and local id
            //
            ASN1EncodableVector kSeq = new ASN1EncodableVector();
            Certificate ct = engineGetCertificate(name);
            kSeq.add(pkcs_9_at_localKeyId);
            kSeq.add(new DERSet(createSubjectKeyId(ct.getPublicKey())));
            kName.add(new DERSequence(kSeq));
            kSeq = new ASN1EncodableVector();
            kSeq.add(pkcs_9_at_friendlyName);
            kSeq.add(new DERSet(new DERBMPString(name)));
            kName.add(new DERSequence(kSeq));
        }
        SafeBag kBag = new SafeBag(pkcs8ShroudedKeyBag, kInfo.getDERObject(), new DERSet(kName));
        keyS.add(kBag);
    }
    byte[] keySEncoded = new DERSequence(keyS).getDEREncoded();
    BERConstructedOctetString keyString = new BERConstructedOctetString(keySEncoded);
    //
    // certificate processing
    //
    byte[] cSalt = new byte[SALT_SIZE];
    random.nextBytes(cSalt);
    ASN1EncodableVector certSeq = new ASN1EncodableVector();
    PKCS12PBEParams cParams = new PKCS12PBEParams(cSalt, MIN_ITERATIONS);
    AlgorithmIdentifier cAlgId = new AlgorithmIdentifier(certAlgorithm, cParams.getDERObject());
    Hashtable doneCerts = new Hashtable();
    Enumeration cs = keys.keys();
    while (cs.hasMoreElements()) {
        try {
            String name = (String) cs.nextElement();
            Certificate cert = engineGetCertificate(name);
            boolean cAttrSet = false;
            CertBag cBag = new CertBag(x509Certificate, new DEROctetString(cert.getEncoded()));
            ASN1EncodableVector fName = new ASN1EncodableVector();
            if (cert instanceof PKCS12BagAttributeCarrier) {
                PKCS12BagAttributeCarrier bagAttrs = (PKCS12BagAttributeCarrier) cert;
                //
                // make sure we are using the local alias on store
                //
                DERBMPString nm = (DERBMPString) bagAttrs.getBagAttribute(pkcs_9_at_friendlyName);
                if (nm == null || !nm.getString().equals(name)) {
                    bagAttrs.setBagAttribute(pkcs_9_at_friendlyName, new DERBMPString(name));
                }
                //
                if (bagAttrs.getBagAttribute(pkcs_9_at_localKeyId) == null) {
                    bagAttrs.setBagAttribute(pkcs_9_at_localKeyId, createSubjectKeyId(cert.getPublicKey()));
                }
                Enumeration e = bagAttrs.getBagAttributeKeys();
                while (e.hasMoreElements()) {
                    DERObjectIdentifier oid = (DERObjectIdentifier) e.nextElement();
                    ASN1EncodableVector fSeq = new ASN1EncodableVector();
                    fSeq.add(oid);
                    fSeq.add(new DERSet(bagAttrs.getBagAttribute(oid)));
                    fName.add(new DERSequence(fSeq));
                    cAttrSet = true;
                }
            }
            if (!cAttrSet) {
                ASN1EncodableVector fSeq = new ASN1EncodableVector();
                fSeq.add(pkcs_9_at_localKeyId);
                fSeq.add(new DERSet(createSubjectKeyId(cert.getPublicKey())));
                fName.add(new DERSequence(fSeq));
                fSeq = new ASN1EncodableVector();
                fSeq.add(pkcs_9_at_friendlyName);
                fSeq.add(new DERSet(new DERBMPString(name)));
                fName.add(new DERSequence(fSeq));
            }
            SafeBag sBag = new SafeBag(certBag, cBag.getDERObject(), new DERSet(fName));
            certSeq.add(sBag);
            doneCerts.put(cert, cert);
        } catch (CertificateEncodingException e) {
            throw new IOException("Error encoding certificate: " + e.toString());
        }
    }
    cs = certs.keys();
    while (cs.hasMoreElements()) {
        try {
            String certId = (String) cs.nextElement();
            Certificate cert = (Certificate) certs.get(certId);
            boolean cAttrSet = false;
            if (keys.get(certId) != null) {
                continue;
            }
            CertBag cBag = new CertBag(x509Certificate, new DEROctetString(cert.getEncoded()));
            ASN1EncodableVector fName = new ASN1EncodableVector();
            if (cert instanceof PKCS12BagAttributeCarrier) {
                PKCS12BagAttributeCarrier bagAttrs = (PKCS12BagAttributeCarrier) cert;
                //
                // make sure we are using the local alias on store
                //
                DERBMPString nm = (DERBMPString) bagAttrs.getBagAttribute(pkcs_9_at_friendlyName);
                if (nm == null || !nm.getString().equals(certId)) {
                    bagAttrs.setBagAttribute(pkcs_9_at_friendlyName, new DERBMPString(certId));
                }
                Enumeration e = bagAttrs.getBagAttributeKeys();
                while (e.hasMoreElements()) {
                    DERObjectIdentifier oid = (DERObjectIdentifier) e.nextElement();
                    // If we find one, we'll prune it out.
                    if (oid.equals(PKCSObjectIdentifiers.pkcs_9_at_localKeyId)) {
                        continue;
                    }
                    ASN1EncodableVector fSeq = new ASN1EncodableVector();
                    fSeq.add(oid);
                    fSeq.add(new DERSet(bagAttrs.getBagAttribute(oid)));
                    fName.add(new DERSequence(fSeq));
                    cAttrSet = true;
                }
            }
            if (!cAttrSet) {
                ASN1EncodableVector fSeq = new ASN1EncodableVector();
                fSeq.add(pkcs_9_at_friendlyName);
                fSeq.add(new DERSet(new DERBMPString(certId)));
                fName.add(new DERSequence(fSeq));
            }
            SafeBag sBag = new SafeBag(certBag, cBag.getDERObject(), new DERSet(fName));
            certSeq.add(sBag);
            doneCerts.put(cert, cert);
        } catch (CertificateEncodingException e) {
            throw new IOException("Error encoding certificate: " + e.toString());
        }
    }
    cs = chainCerts.keys();
    while (cs.hasMoreElements()) {
        try {
            CertId certId = (CertId) cs.nextElement();
            Certificate cert = (Certificate) chainCerts.get(certId);
            if (doneCerts.get(cert) != null) {
                continue;
            }
            CertBag cBag = new CertBag(x509Certificate, new DEROctetString(cert.getEncoded()));
            ASN1EncodableVector fName = new ASN1EncodableVector();
            if (cert instanceof PKCS12BagAttributeCarrier) {
                PKCS12BagAttributeCarrier bagAttrs = (PKCS12BagAttributeCarrier) cert;
                Enumeration e = bagAttrs.getBagAttributeKeys();
                while (e.hasMoreElements()) {
                    DERObjectIdentifier oid = (DERObjectIdentifier) e.nextElement();
                    // If we find one, we'll prune it out.
                    if (oid.equals(PKCSObjectIdentifiers.pkcs_9_at_localKeyId)) {
                        continue;
                    }
                    ASN1EncodableVector fSeq = new ASN1EncodableVector();
                    fSeq.add(oid);
                    fSeq.add(new DERSet(bagAttrs.getBagAttribute(oid)));
                    fName.add(new DERSequence(fSeq));
                }
            }
            SafeBag sBag = new SafeBag(certBag, cBag.getDERObject(), new DERSet(fName));
            certSeq.add(sBag);
        } catch (CertificateEncodingException e) {
            throw new IOException("Error encoding certificate: " + e.toString());
        }
    }
    byte[] certSeqEncoded = new DERSequence(certSeq).getDEREncoded();
    byte[] certBytes = cryptData(true, cAlgId, password, false, certSeqEncoded);
    EncryptedData cInfo = new EncryptedData(data, cAlgId, new BERConstructedOctetString(certBytes));
    ContentInfo[] info = new ContentInfo[] { new ContentInfo(data, keyString), new ContentInfo(encryptedData, cInfo.getDERObject()) };
    AuthenticatedSafe auth = new AuthenticatedSafe(info);
    ByteArrayOutputStream bOut = new ByteArrayOutputStream();
    DEROutputStream asn1Out;
    if (useDEREncoding) {
        asn1Out = new DEROutputStream(bOut);
    } else {
        asn1Out = new BEROutputStream(bOut);
    }
    asn1Out.writeObject(auth);
    byte[] pkg = bOut.toByteArray();
    ContentInfo mainInfo = new ContentInfo(data, new BERConstructedOctetString(pkg));
    //
    // create the mac
    //
    byte[] mSalt = new byte[20];
    int itCount = MIN_ITERATIONS;
    random.nextBytes(mSalt);
    byte[] data = ((ASN1OctetString) mainInfo.getContent()).getOctets();
    MacData mData;
    try {
        byte[] res = calculatePbeMac(id_SHA1, mSalt, itCount, password, false, data);
        // BEGIN android-changed
        AlgorithmIdentifier algId = new AlgorithmIdentifier(id_SHA1, DERNull.INSTANCE);
        // END android-changed
        DigestInfo dInfo = new DigestInfo(algId, res);
        mData = new MacData(dInfo, mSalt, itCount);
    } catch (Exception e) {
        throw new IOException("error constructing MAC: " + e.toString());
    }
    //
    // output the Pfx
    //
    Pfx pfx = new Pfx(mainInfo, mData);
    if (useDEREncoding) {
        asn1Out = new DEROutputStream(stream);
    } else {
        asn1Out = new BEROutputStream(stream);
    }
    asn1Out.writeObject(pfx);
}
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) BERConstructedOctetString(org.bouncycastle.asn1.BERConstructedOctetString) DEROctetString(org.bouncycastle.asn1.DEROctetString) DERSet(org.bouncycastle.asn1.DERSet) PKCS12BagAttributeCarrier(org.bouncycastle.jce.interfaces.PKCS12BagAttributeCarrier) DEROctetString(org.bouncycastle.asn1.DEROctetString) AlgorithmIdentifier(org.bouncycastle.asn1.x509.AlgorithmIdentifier) DERSequence(org.bouncycastle.asn1.DERSequence) ContentInfo(org.bouncycastle.asn1.pkcs.ContentInfo) ASN1EncodableVector(org.bouncycastle.asn1.ASN1EncodableVector) BERConstructedOctetString(org.bouncycastle.asn1.BERConstructedOctetString) EncryptedData(org.bouncycastle.asn1.pkcs.EncryptedData) MacData(org.bouncycastle.asn1.pkcs.MacData) Enumeration(java.util.Enumeration) DERBMPString(org.bouncycastle.asn1.DERBMPString) Pfx(org.bouncycastle.asn1.pkcs.Pfx) Hashtable(java.util.Hashtable) BEROutputStream(org.bouncycastle.asn1.BEROutputStream) CertificateEncodingException(java.security.cert.CertificateEncodingException) IOException(java.io.IOException) ByteArrayOutputStream(java.io.ByteArrayOutputStream) SafeBag(org.bouncycastle.asn1.pkcs.SafeBag) DERObjectIdentifier(org.bouncycastle.asn1.DERObjectIdentifier) 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) CertBag(org.bouncycastle.asn1.pkcs.CertBag) PKCS12PBEParams(org.bouncycastle.asn1.pkcs.PKCS12PBEParams) DigestInfo(org.bouncycastle.asn1.x509.DigestInfo) X509Certificate(java.security.cert.X509Certificate) Certificate(java.security.cert.Certificate) DEROutputStream(org.bouncycastle.asn1.DEROutputStream)

Example 4 with DERBMPString

use of org.bouncycastle.asn1.DERBMPString 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)

Example 5 with DERBMPString

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

the class ASN1Dump method _dumpAsString.

/**
     * dump a DER object as a formatted string with indentation
     *
     * @param obj the DERObject to be dumped out.
     */
static void _dumpAsString(String indent, boolean verbose, DERObject obj, StringBuffer buf) {
    String nl = System.getProperty("line.separator");
    if (obj instanceof ASN1Sequence) {
        Enumeration e = ((ASN1Sequence) obj).getObjects();
        String tab = indent + TAB;
        buf.append(indent);
        if (obj instanceof BERSequence) {
            buf.append("BER Sequence");
        } else if (obj instanceof DERSequence) {
            buf.append("DER Sequence");
        } else {
            buf.append("Sequence");
        }
        buf.append(nl);
        while (e.hasMoreElements()) {
            Object o = e.nextElement();
            // BEGIN android-changed
            if (o == null || o.equals(DERNull.INSTANCE)) // END android-changed
            {
                buf.append(tab);
                buf.append("NULL");
                buf.append(nl);
            } else if (o instanceof DERObject) {
                _dumpAsString(tab, verbose, (DERObject) o, buf);
            } else {
                _dumpAsString(tab, verbose, ((DEREncodable) o).getDERObject(), buf);
            }
        }
    } else if (obj instanceof DERTaggedObject) {
        String tab = indent + TAB;
        buf.append(indent);
        if (obj instanceof BERTaggedObject) {
            buf.append("BER Tagged [");
        } else {
            buf.append("Tagged [");
        }
        DERTaggedObject o = (DERTaggedObject) obj;
        buf.append(Integer.toString(o.getTagNo()));
        buf.append(']');
        if (!o.isExplicit()) {
            buf.append(" IMPLICIT ");
        }
        buf.append(nl);
        if (o.isEmpty()) {
            buf.append(tab);
            buf.append("EMPTY");
            buf.append(nl);
        } else {
            _dumpAsString(tab, verbose, o.getObject(), buf);
        }
    } else if (obj instanceof BERSet) {
        Enumeration e = ((ASN1Set) obj).getObjects();
        String tab = indent + TAB;
        buf.append(indent);
        buf.append("BER Set");
        buf.append(nl);
        while (e.hasMoreElements()) {
            Object o = e.nextElement();
            if (o == null) {
                buf.append(tab);
                buf.append("NULL");
                buf.append(nl);
            } else if (o instanceof DERObject) {
                _dumpAsString(tab, verbose, (DERObject) o, buf);
            } else {
                _dumpAsString(tab, verbose, ((DEREncodable) o).getDERObject(), buf);
            }
        }
    } else if (obj instanceof DERSet) {
        Enumeration e = ((ASN1Set) obj).getObjects();
        String tab = indent + TAB;
        buf.append(indent);
        buf.append("DER Set");
        buf.append(nl);
        while (e.hasMoreElements()) {
            Object o = e.nextElement();
            if (o == null) {
                buf.append(tab);
                buf.append("NULL");
                buf.append(nl);
            } else if (o instanceof DERObject) {
                _dumpAsString(tab, verbose, (DERObject) o, buf);
            } else {
                _dumpAsString(tab, verbose, ((DEREncodable) o).getDERObject(), buf);
            }
        }
    } else if (obj instanceof DERObjectIdentifier) {
        buf.append(indent + "ObjectIdentifier(" + ((DERObjectIdentifier) obj).getId() + ")" + nl);
    } else if (obj instanceof DERBoolean) {
        buf.append(indent + "Boolean(" + ((DERBoolean) obj).isTrue() + ")" + nl);
    } else if (obj instanceof DERInteger) {
        buf.append(indent + "Integer(" + ((DERInteger) obj).getValue() + ")" + nl);
    } else if (obj instanceof BERConstructedOctetString) {
        ASN1OctetString oct = (ASN1OctetString) obj;
        buf.append(indent + "BER Constructed Octet String" + "[" + oct.getOctets().length + "] ");
        if (verbose) {
            buf.append(dumpBinaryDataAsString(indent, oct.getOctets()));
        } else {
            buf.append(nl);
        }
    } else if (obj instanceof DEROctetString) {
        ASN1OctetString oct = (ASN1OctetString) obj;
        buf.append(indent + "DER Octet String" + "[" + oct.getOctets().length + "] ");
        if (verbose) {
            buf.append(dumpBinaryDataAsString(indent, oct.getOctets()));
        } else {
            buf.append(nl);
        }
    } else if (obj instanceof DERBitString) {
        DERBitString bt = (DERBitString) obj;
        buf.append(indent + "DER Bit String" + "[" + bt.getBytes().length + ", " + bt.getPadBits() + "] ");
        if (verbose) {
            buf.append(dumpBinaryDataAsString(indent, bt.getBytes()));
        } else {
            buf.append(nl);
        }
    } else if (obj instanceof DERIA5String) {
        buf.append(indent + "IA5String(" + ((DERIA5String) obj).getString() + ") " + nl);
    } else if (obj instanceof DERUTF8String) {
        buf.append(indent + "UTF8String(" + ((DERUTF8String) obj).getString() + ") " + nl);
    } else if (obj instanceof DERPrintableString) {
        buf.append(indent + "PrintableString(" + ((DERPrintableString) obj).getString() + ") " + nl);
    } else if (obj instanceof DERVisibleString) {
        buf.append(indent + "VisibleString(" + ((DERVisibleString) obj).getString() + ") " + nl);
    } else if (obj instanceof DERBMPString) {
        buf.append(indent + "BMPString(" + ((DERBMPString) obj).getString() + ") " + nl);
    } else if (obj instanceof DERT61String) {
        buf.append(indent + "T61String(" + ((DERT61String) obj).getString() + ") " + nl);
    } else if (obj instanceof DERUTCTime) {
        buf.append(indent + "UTCTime(" + ((DERUTCTime) obj).getTime() + ") " + nl);
    } else if (obj instanceof DERGeneralizedTime) {
        buf.append(indent + "GeneralizedTime(" + ((DERGeneralizedTime) obj).getTime() + ") " + nl);
    } else if (obj instanceof DERUnknownTag) {
        buf.append(indent + "Unknown " + Integer.toString(((DERUnknownTag) obj).getTag(), 16) + " " + new String(Hex.encode(((DERUnknownTag) obj).getData())) + nl);
    } else if (obj instanceof BERApplicationSpecific) {
        buf.append(outputApplicationSpecific("BER", indent, verbose, obj, nl));
    } else if (obj instanceof DERApplicationSpecific) {
        buf.append(outputApplicationSpecific("DER", indent, verbose, obj, nl));
    } else if (obj instanceof DEREnumerated) {
        DEREnumerated en = (DEREnumerated) obj;
        buf.append(indent + "DER Enumerated(" + en.getValue() + ")" + nl);
    } else if (obj instanceof DERExternal) {
        DERExternal ext = (DERExternal) obj;
        buf.append(indent + "External " + nl);
        String tab = indent + TAB;
        if (ext.getDirectReference() != null) {
            buf.append(tab + "Direct Reference: " + ext.getDirectReference().getId() + nl);
        }
        if (ext.getIndirectReference() != null) {
            buf.append(tab + "Indirect Reference: " + ext.getIndirectReference().toString() + nl);
        }
        if (ext.getDataValueDescriptor() != null) {
            _dumpAsString(tab, verbose, ext.getDataValueDescriptor(), buf);
        }
        buf.append(tab + "Encoding: " + ext.getEncoding() + nl);
        _dumpAsString(tab, verbose, ext.getExternalContent(), buf);
    } else {
        buf.append(indent + obj.toString() + nl);
    }
}
Also used : ASN1OctetString(org.bouncycastle.asn1.ASN1OctetString) DERUTF8String(org.bouncycastle.asn1.DERUTF8String) DERApplicationSpecific(org.bouncycastle.asn1.DERApplicationSpecific) DERBitString(org.bouncycastle.asn1.DERBitString) BERConstructedOctetString(org.bouncycastle.asn1.BERConstructedOctetString) DEROctetString(org.bouncycastle.asn1.DEROctetString) ASN1OctetString(org.bouncycastle.asn1.ASN1OctetString) DERBMPString(org.bouncycastle.asn1.DERBMPString) DERIA5String(org.bouncycastle.asn1.DERIA5String) DERUTF8String(org.bouncycastle.asn1.DERUTF8String) DERT61String(org.bouncycastle.asn1.DERT61String) DERPrintableString(org.bouncycastle.asn1.DERPrintableString) DERVisibleString(org.bouncycastle.asn1.DERVisibleString) DERSet(org.bouncycastle.asn1.DERSet) DEROctetString(org.bouncycastle.asn1.DEROctetString) DERInteger(org.bouncycastle.asn1.DERInteger) DERSequence(org.bouncycastle.asn1.DERSequence) DERObject(org.bouncycastle.asn1.DERObject) DERIA5String(org.bouncycastle.asn1.DERIA5String) DERGeneralizedTime(org.bouncycastle.asn1.DERGeneralizedTime) DERUTCTime(org.bouncycastle.asn1.DERUTCTime) DERExternal(org.bouncycastle.asn1.DERExternal) DERPrintableString(org.bouncycastle.asn1.DERPrintableString) DERVisibleString(org.bouncycastle.asn1.DERVisibleString) BERTaggedObject(org.bouncycastle.asn1.BERTaggedObject) BERApplicationSpecific(org.bouncycastle.asn1.BERApplicationSpecific) BERConstructedOctetString(org.bouncycastle.asn1.BERConstructedOctetString) DERBoolean(org.bouncycastle.asn1.DERBoolean) BERSet(org.bouncycastle.asn1.BERSet) Enumeration(java.util.Enumeration) DERBMPString(org.bouncycastle.asn1.DERBMPString) DERTaggedObject(org.bouncycastle.asn1.DERTaggedObject) BERSequence(org.bouncycastle.asn1.BERSequence) DERBitString(org.bouncycastle.asn1.DERBitString) DERObjectIdentifier(org.bouncycastle.asn1.DERObjectIdentifier) DERUnknownTag(org.bouncycastle.asn1.DERUnknownTag) ASN1Sequence(org.bouncycastle.asn1.ASN1Sequence) DEREnumerated(org.bouncycastle.asn1.DEREnumerated) ASN1Set(org.bouncycastle.asn1.ASN1Set) DERT61String(org.bouncycastle.asn1.DERT61String) DEREncodable(org.bouncycastle.asn1.DEREncodable) DERObject(org.bouncycastle.asn1.DERObject) DERTaggedObject(org.bouncycastle.asn1.DERTaggedObject) BERTaggedObject(org.bouncycastle.asn1.BERTaggedObject)

Aggregations

Enumeration (java.util.Enumeration)6 ASN1OctetString (org.bouncycastle.asn1.ASN1OctetString)6 DERBMPString (org.bouncycastle.asn1.DERBMPString)6 DEROctetString (org.bouncycastle.asn1.DEROctetString)5 IOException (java.io.IOException)4 KeyStoreException (java.security.KeyStoreException)4 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)4 PrivateKey (java.security.PrivateKey)4 UnrecoverableKeyException (java.security.UnrecoverableKeyException)4 Certificate (java.security.cert.Certificate)4 CertificateEncodingException (java.security.cert.CertificateEncodingException)4 CertificateException (java.security.cert.CertificateException)4 X509Certificate (java.security.cert.X509Certificate)4 Hashtable (java.util.Hashtable)4 ASN1EncodableVector (org.bouncycastle.asn1.ASN1EncodableVector)4 ASN1Sequence (org.bouncycastle.asn1.ASN1Sequence)4 ASN1Set (org.bouncycastle.asn1.ASN1Set)4 BERConstructedOctetString (org.bouncycastle.asn1.BERConstructedOctetString)4 AuthenticatedSafe (org.bouncycastle.asn1.pkcs.AuthenticatedSafe)4 CertBag (org.bouncycastle.asn1.pkcs.CertBag)4