Search in sources :

Example 51 with ASN1Set

use of com.unboundid.asn1.ASN1Set in project LinLong-Java by zhenwei1108.

the class CMSSignedData method getSignerInfos.

/**
 * return the collection of signers that are associated with the signatures for the message.
 */
public SignerInformationStore getSignerInfos() {
    if (signerInfoStore == null) {
        ASN1Set s = signedData.getSignerInfos();
        List signerInfos = new ArrayList();
        for (int i = 0; i != s.size(); i++) {
            SignerInfo info = SignerInfo.getInstance(s.getObjectAt(i));
            ASN1ObjectIdentifier contentType = signedData.getEncapContentInfo().getContentType();
            if (hashes == null) {
                signerInfos.add(new SignerInformation(info, contentType, signedContent, null));
            } else {
                Object obj = hashes.keySet().iterator().next();
                byte[] hash = (obj instanceof String) ? (byte[]) hashes.get(info.getDigestAlgorithm().getAlgorithm().getId()) : (byte[]) hashes.get(info.getDigestAlgorithm().getAlgorithm());
                signerInfos.add(new SignerInformation(info, contentType, null, hash));
            }
        }
        signerInfoStore = new SignerInformationStore(signerInfos);
    }
    return signerInfoStore;
}
Also used : SignerInfo(com.github.zhenwei.pkix.util.asn1.cms.SignerInfo) ASN1Set(com.github.zhenwei.core.asn1.ASN1Set) ArrayList(java.util.ArrayList) ArrayList(java.util.ArrayList) List(java.util.List) ASN1OctetString(com.github.zhenwei.core.asn1.ASN1OctetString) ASN1ObjectIdentifier(com.github.zhenwei.core.asn1.ASN1ObjectIdentifier)

Example 52 with ASN1Set

use of com.unboundid.asn1.ASN1Set in project LinLong-Java by zhenwei1108.

the class CMSSignedData method addDigestAlgorithm.

/**
 * Return a new CMSSignedData which guarantees to have the passed in digestAlgorithm in it.
 *
 * @param signedData      the signed data object to be used as a base.
 * @param digestAlgorithm the digest algorithm to be added to the signed data.
 * @return a new signed data object.
 */
public static CMSSignedData addDigestAlgorithm(CMSSignedData signedData, AlgorithmIdentifier digestAlgorithm) {
    Set<AlgorithmIdentifier> digestAlgorithms = signedData.getDigestAlgorithmIDs();
    AlgorithmIdentifier digestAlg = CMSSignedHelper.INSTANCE.fixDigestAlgID(digestAlgorithm, dgstAlgFinder);
    // 
    if (digestAlgorithms.contains(digestAlg)) {
        return signedData;
    }
    // 
    // copy
    // 
    CMSSignedData cms = new CMSSignedData(signedData);
    // 
    // build up the new set
    // 
    Set<AlgorithmIdentifier> digestAlgs = new HashSet<AlgorithmIdentifier>();
    Iterator it = digestAlgorithms.iterator();
    while (it.hasNext()) {
        digestAlgs.add(CMSSignedHelper.INSTANCE.fixDigestAlgID((AlgorithmIdentifier) it.next(), dgstAlgFinder));
    }
    digestAlgs.add(digestAlg);
    ASN1Set digests = CMSUtils.convertToBERSet(digestAlgs);
    ASN1Sequence sD = (ASN1Sequence) signedData.signedData.toASN1Primitive();
    ASN1EncodableVector vec = new ASN1EncodableVector();
    // 
    // signers are the last item in the sequence.
    // 
    // version
    vec.add(sD.getObjectAt(0));
    vec.add(digests);
    for (int i = 2; i != sD.size(); i++) {
        vec.add(sD.getObjectAt(i));
    }
    cms.signedData = SignedData.getInstance(new BERSequence(vec));
    // 
    // replace the contentInfo with the new one
    // 
    cms.contentInfo = new ContentInfo(cms.contentInfo.getContentType(), cms.signedData);
    return cms;
}
Also used : ASN1Sequence(com.github.zhenwei.core.asn1.ASN1Sequence) ASN1Set(com.github.zhenwei.core.asn1.ASN1Set) ContentInfo(com.github.zhenwei.pkix.util.asn1.cms.ContentInfo) BERSequence(com.github.zhenwei.core.asn1.BERSequence) Iterator(java.util.Iterator) ASN1EncodableVector(com.github.zhenwei.core.asn1.ASN1EncodableVector) AlgorithmIdentifier(com.github.zhenwei.core.asn1.x509.AlgorithmIdentifier) HashSet(java.util.HashSet)

Example 53 with ASN1Set

use of com.unboundid.asn1.ASN1Set in project LinLong-Java by zhenwei1108.

the class CMSSignedDataGenerator method generate.

/**
 * Generate a CMS Signed Data object which can be carrying a detached CMS signature, or have
 * encapsulated data, depending on the value of the encapsulated parameter.
 *
 * @param content     the content to be signed.
 * @param encapsulate true if the content should be encapsulated in the signature, false
 *                    otherwise.
 */
public CMSSignedData generate(// FIXME Avoid accessing more than once to support CMSProcessableInputStream
CMSTypedData content, boolean encapsulate) throws CMSException {
    if (!signerInfs.isEmpty()) {
        throw new IllegalStateException("this method can only be used with SignerInfoGenerator");
    }
    // TODO
    // if (signerInfs.isEmpty())
    // {
    // /* RFC 3852 5.2
    // * "In the degenerate case where there are no signers, the
    // * EncapsulatedContentInfo value being "signed" is irrelevant.  In this
    // * case, the content type within the EncapsulatedContentInfo value being
    // * "signed" MUST be id-data (as defined in section 4), and the content
    // * field of the EncapsulatedContentInfo value MUST be omitted."
    // */
    // if (encapsulate)
    // {
    // throw new IllegalArgumentException("no signers, encapsulate must be false");
    // }
    // if (!DATA.equals(eContentType))
    // {
    // throw new IllegalArgumentException("no signers, eContentType must be id-data");
    // }
    // }
    // 
    // if (!DATA.equals(eContentType))
    // {
    // /* RFC 3852 5.3
    // * [The 'signedAttrs']...
    // * field is optional, but it MUST be present if the content type of
    // * the EncapsulatedContentInfo value being signed is not id-data.
    // */
    // // TODO signedAttrs must be present for all signers
    // }
    Set<AlgorithmIdentifier> digestAlgs = new LinkedHashSet<AlgorithmIdentifier>();
    ASN1EncodableVector signerInfos = new ASN1EncodableVector();
    // clear the current preserved digest state
    digests.clear();
    // 
    for (Iterator it = _signers.iterator(); it.hasNext(); ) {
        SignerInformation signer = (SignerInformation) it.next();
        CMSUtils.addDigestAlgs(digestAlgs, signer, digestAlgIdFinder);
        // TODO Verify the content type and calculated digest match the precalculated SignerInfo
        signerInfos.add(signer.toASN1Structure());
    }
    // 
    // add the SignerInfo objects
    // 
    ASN1ObjectIdentifier contentTypeOID = content.getContentType();
    ASN1OctetString octs = null;
    if (content.getContent() != null) {
        ByteArrayOutputStream bOut = null;
        if (encapsulate) {
            bOut = new ByteArrayOutputStream();
        }
        OutputStream cOut = CMSUtils.attachSignersToOutputStream(signerGens, bOut);
        // Just in case it's unencapsulated and there are no signers!
        cOut = CMSUtils.getSafeOutputStream(cOut);
        try {
            content.write(cOut);
            cOut.close();
        } catch (IOException e) {
            throw new CMSException("data processing exception: " + e.getMessage(), e);
        }
        if (encapsulate) {
            octs = new BEROctetString(bOut.toByteArray());
        }
    }
    for (Iterator it = signerGens.iterator(); it.hasNext(); ) {
        SignerInfoGenerator sGen = (SignerInfoGenerator) it.next();
        SignerInfo inf = sGen.generate(contentTypeOID);
        digestAlgs.add(inf.getDigestAlgorithm());
        signerInfos.add(inf);
        byte[] calcDigest = sGen.getCalculatedDigest();
        if (calcDigest != null) {
            digests.put(inf.getDigestAlgorithm().getAlgorithm().getId(), calcDigest);
        }
    }
    ASN1Set certificates = null;
    if (certs.size() != 0) {
        certificates = CMSUtils.createBerSetFromList(certs);
    }
    ASN1Set certrevlist = null;
    if (crls.size() != 0) {
        certrevlist = CMSUtils.createBerSetFromList(crls);
    }
    ContentInfo encInfo = new ContentInfo(contentTypeOID, octs);
    SignedData sd = new SignedData(CMSUtils.convertToBERSet(digestAlgs), encInfo, certificates, certrevlist, new DERSet(signerInfos));
    ContentInfo contentInfo = new ContentInfo(CMSObjectIdentifiers.signedData, sd);
    return new CMSSignedData(content, contentInfo);
}
Also used : LinkedHashSet(java.util.LinkedHashSet) ASN1OctetString(com.github.zhenwei.core.asn1.ASN1OctetString) SignedData(com.github.zhenwei.pkix.util.asn1.cms.SignedData) OutputStream(java.io.OutputStream) ByteArrayOutputStream(java.io.ByteArrayOutputStream) ByteArrayOutputStream(java.io.ByteArrayOutputStream) IOException(java.io.IOException) DERSet(com.github.zhenwei.core.asn1.DERSet) AlgorithmIdentifier(com.github.zhenwei.core.asn1.x509.AlgorithmIdentifier) SignerInfo(com.github.zhenwei.pkix.util.asn1.cms.SignerInfo) BEROctetString(com.github.zhenwei.core.asn1.BEROctetString) ASN1Set(com.github.zhenwei.core.asn1.ASN1Set) ContentInfo(com.github.zhenwei.pkix.util.asn1.cms.ContentInfo) Iterator(java.util.Iterator) ASN1EncodableVector(com.github.zhenwei.core.asn1.ASN1EncodableVector) ASN1ObjectIdentifier(com.github.zhenwei.core.asn1.ASN1ObjectIdentifier)

Example 54 with ASN1Set

use of com.unboundid.asn1.ASN1Set in project LinLong-Java by zhenwei1108.

the class CMSAuthenticatedDataGenerator method generate.

/**
 * Generate an authenticated data object from the passed in typedData and MacCalculator.
 *
 * @param typedData        the data to have a MAC attached.
 * @param macCalculator    the calculator of the MAC to be attached.
 * @param digestCalculator calculator for computing digest of the encapsulated data.
 * @return the resulting CMSAuthenticatedData object.
 * @throws CMSException on failure in encoding data or processing recipients.
 */
public CMSAuthenticatedData generate(CMSTypedData typedData, MacCalculator macCalculator, final DigestCalculator digestCalculator) throws CMSException {
    ASN1EncodableVector recipientInfos = new ASN1EncodableVector();
    ASN1OctetString encContent;
    ASN1OctetString macResult;
    for (Iterator it = recipientInfoGenerators.iterator(); it.hasNext(); ) {
        RecipientInfoGenerator recipient = (RecipientInfoGenerator) it.next();
        recipientInfos.add(recipient.generate(macCalculator.getKey()));
    }
    AuthenticatedData authData;
    if (digestCalculator != null) {
        try {
            ByteArrayOutputStream bOut = new ByteArrayOutputStream();
            OutputStream out = new TeeOutputStream(digestCalculator.getOutputStream(), bOut);
            typedData.write(out);
            out.close();
            encContent = new BEROctetString(bOut.toByteArray());
        } catch (IOException e) {
            throw new CMSException("unable to perform digest calculation: " + e.getMessage(), e);
        }
        Map parameters = Collections.unmodifiableMap(getBaseParameters(typedData.getContentType(), digestCalculator.getAlgorithmIdentifier(), macCalculator.getAlgorithmIdentifier(), digestCalculator.getDigest()));
        if (authGen == null) {
            authGen = new DefaultAuthenticatedAttributeTableGenerator();
        }
        ASN1Set authed = new DERSet(authGen.getAttributes(parameters).toASN1EncodableVector());
        try {
            OutputStream mOut = macCalculator.getOutputStream();
            mOut.write(authed.getEncoded(ASN1Encoding.DER));
            mOut.close();
            macResult = new DEROctetString(macCalculator.getMac());
        } catch (IOException e) {
            throw new CMSException("unable to perform MAC calculation: " + e.getMessage(), e);
        }
        ASN1Set unauthed = (unauthGen != null) ? new BERSet(unauthGen.getAttributes(parameters).toASN1EncodableVector()) : null;
        ContentInfo eci = new ContentInfo(typedData.getContentType(), encContent);
        authData = new AuthenticatedData(originatorInfo, new DERSet(recipientInfos), macCalculator.getAlgorithmIdentifier(), digestCalculator.getAlgorithmIdentifier(), eci, authed, macResult, unauthed);
    } else {
        try {
            ByteArrayOutputStream bOut = new ByteArrayOutputStream();
            OutputStream mOut = new TeeOutputStream(bOut, macCalculator.getOutputStream());
            typedData.write(mOut);
            mOut.close();
            encContent = new BEROctetString(bOut.toByteArray());
            macResult = new DEROctetString(macCalculator.getMac());
        } catch (IOException e) {
            throw new CMSException("unable to perform MAC calculation: " + e.getMessage(), e);
        }
        ASN1Set unauthed = (unauthGen != null) ? new BERSet(unauthGen.getAttributes(Collections.EMPTY_MAP).toASN1EncodableVector()) : null;
        ContentInfo eci = new ContentInfo(typedData.getContentType(), encContent);
        authData = new AuthenticatedData(originatorInfo, new DERSet(recipientInfos), macCalculator.getAlgorithmIdentifier(), null, eci, null, macResult, unauthed);
    }
    ContentInfo contentInfo = new ContentInfo(CMSObjectIdentifiers.authenticatedData, authData);
    return new CMSAuthenticatedData(contentInfo, new DigestCalculatorProvider() {

        public DigestCalculator get(AlgorithmIdentifier digestAlgorithmIdentifier) throws OperatorCreationException {
            return digestCalculator;
        }
    });
}
Also used : ASN1OctetString(com.github.zhenwei.core.asn1.ASN1OctetString) BERSet(com.github.zhenwei.core.asn1.BERSet) TeeOutputStream(com.github.zhenwei.core.util.io.TeeOutputStream) OutputStream(java.io.OutputStream) TeeOutputStream(com.github.zhenwei.core.util.io.TeeOutputStream) ByteArrayOutputStream(java.io.ByteArrayOutputStream) DigestCalculator(com.github.zhenwei.pkix.operator.DigestCalculator) ByteArrayOutputStream(java.io.ByteArrayOutputStream) IOException(java.io.IOException) DERSet(com.github.zhenwei.core.asn1.DERSet) DEROctetString(com.github.zhenwei.core.asn1.DEROctetString) AlgorithmIdentifier(com.github.zhenwei.core.asn1.x509.AlgorithmIdentifier) BEROctetString(com.github.zhenwei.core.asn1.BEROctetString) ASN1Set(com.github.zhenwei.core.asn1.ASN1Set) DigestCalculatorProvider(com.github.zhenwei.pkix.operator.DigestCalculatorProvider) ContentInfo(com.github.zhenwei.pkix.util.asn1.cms.ContentInfo) AuthenticatedData(com.github.zhenwei.pkix.util.asn1.cms.AuthenticatedData) Iterator(java.util.Iterator) ASN1EncodableVector(com.github.zhenwei.core.asn1.ASN1EncodableVector) OperatorCreationException(com.github.zhenwei.pkix.operator.OperatorCreationException) Map(java.util.Map)

Example 55 with ASN1Set

use of com.unboundid.asn1.ASN1Set in project LinLong-Java by zhenwei1108.

the class PKCS12KeyStoreSpi method engineLoad.

public void engineLoad(InputStream stream, char[] password) throws IOException {
    if (// just initialising
    stream == null) {
        return;
    }
    BufferedInputStream bufIn = new BufferedInputStream(stream);
    bufIn.mark(10);
    int head = bufIn.read();
    if (head < 0) {
        throw new EOFException("no data in keystore stream");
    }
    if (head != 0x30) {
        throw new IOException("stream does not represent a PKCS12 key store");
    }
    bufIn.reset();
    ASN1InputStream bIn = new ASN1InputStream(bufIn);
    Pfx bag;
    try {
        bag = Pfx.getInstance(bIn.readObject());
    } catch (Exception e) {
        throw new IOException(e.getMessage());
    }
    ContentInfo info = bag.getAuthSafe();
    Vector chain = new Vector();
    boolean unmarkedKey = false;
    boolean wrongPKCS12Zero = false;
    if (// check the mac code
    bag.getMacData() != null) {
        if (password == null) {
            throw new NullPointerException("no password supplied when one expected");
        }
        MacData mData = bag.getMacData();
        DigestInfo dInfo = mData.getMac();
        macAlgorithm = dInfo.getAlgorithmId();
        byte[] salt = mData.getSalt();
        itCount = validateIterationCount(mData.getIterationCount());
        saltLength = salt.length;
        byte[] data = ((ASN1OctetString) info.getContent()).getOctets();
        try {
            byte[] res = calculatePbeMac(macAlgorithm.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(macAlgorithm.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());
        }
    } else if (password != null && password.length != 0) {
        if (!Properties.isOverrideSet("com.github.zhenwei.pkix.pkcs12.ignore_useless_passwd")) {
            throw new IOException("password supplied for keystore that does not require one");
        }
    }
    keys = new IgnoresCaseHashtable();
    localIds = new IgnoresCaseHashtable();
    if (info.getContentType().equals(data)) {
        ASN1OctetString content = ASN1OctetString.getInstance(info.getContent());
        AuthenticatedSafe authSafe = AuthenticatedSafe.getInstance(content.getOctets());
        ContentInfo[] c = authSafe.getContentInfo();
        for (int i = 0; i != c.length; i++) {
            if (c[i].getContentType().equals(data)) {
                ASN1OctetString authSafeContent = ASN1OctetString.getInstance(c[i].getContent());
                ASN1Sequence seq = ASN1Sequence.getInstance(authSafeContent.getOctets());
                for (int j = 0; j != seq.size(); j++) {
                    SafeBag b = SafeBag.getInstance(seq.getObjectAt(j));
                    if (b.getBagId().equals(pkcs8ShroudedKeyBag)) {
                        com.github.zhenwei.core.asn1.pkcs.EncryptedPrivateKeyInfo eIn = com.github.zhenwei.core.asn1.pkcs.EncryptedPrivateKeyInfo.getInstance(b.getBagValue());
                        PrivateKey privKey = unwrapKey(eIn.getEncryptionAlgorithm(), eIn.getEncryptedData(), password, wrongPKCS12Zero);
                        // 
                        // set the attributes on the key
                        // 
                        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);
                                    if (privKey instanceof PKCS12BagAttributeCarrier) {
                                        PKCS12BagAttributeCarrier bagAttr = (PKCS12BagAttributeCarrier) privKey;
                                        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 = ((ASN1BMPString) 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.getInstance(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)) {
                        com.github.zhenwei.core.asn1.pkcs.EncryptedPrivateKeyInfo eIn = com.github.zhenwei.core.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 = ((ASN1BMPString) 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)) {
                        com.github.zhenwei.core.asn1.pkcs.PrivateKeyInfo kInfo = com.github.zhenwei.core.asn1.pkcs.PrivateKeyInfo.getInstance(b.getBagValue());
                        PrivateKey privKey = WeGooProvider.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.getInstance(e.nextElement());
                            ASN1ObjectIdentifier aOid = ASN1ObjectIdentifier.getInstance(sq.getObjectAt(0));
                            ASN1Set attrSet = ASN1Set.getInstance(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 = ((ASN1BMPString) 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.getInstance(e.nextElement());
                ASN1ObjectIdentifier oid = ASN1ObjectIdentifier.getInstance(sq.getObjectAt(0));
                ASN1Set attrSet = ASN1Set.getInstance(sq.getObjectAt(1));
                if (// sometimes this is empty!
                attrSet.size() > 0) {
                    ASN1Primitive attr = (ASN1Primitive) attrSet.getObjectAt(0);
                    PKCS12BagAttributeCarrier bagAttr = null;
                    if (cert instanceof PKCS12BagAttributeCarrier) {
                        bagAttr = (PKCS12BagAttributeCarrier) cert;
                        ASN1Encodable existing = bagAttr.getBagAttribute(oid);
                        if (existing != null) {
                            // we've found more than one - one might be incorrect
                            if (oid.equals(pkcs_9_at_localKeyId)) {
                                String id = Hex.toHexString(((ASN1OctetString) attr).getOctets());
                                if (!(keys.keys.containsKey(id) || localIds.keys.containsKey(id))) {
                                    // ignore this one - it's not valid
                                    continue;
                                }
                            }
                            // 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 = ((ASN1BMPString) 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(com.github.zhenwei.core.asn1.ASN1OctetString) PrivateKey(java.security.PrivateKey) ASN1BMPString(com.github.zhenwei.core.asn1.ASN1BMPString) AuthenticatedSafe(com.github.zhenwei.core.asn1.pkcs.AuthenticatedSafe) BEROctetString(com.github.zhenwei.core.asn1.BEROctetString) DERBMPString(com.github.zhenwei.core.asn1.DERBMPString) ASN1BMPString(com.github.zhenwei.core.asn1.ASN1BMPString) ASN1OctetString(com.github.zhenwei.core.asn1.ASN1OctetString) DEROctetString(com.github.zhenwei.core.asn1.DEROctetString) PKCS12BagAttributeCarrier(com.github.zhenwei.provider.jce.interfaces.PKCS12BagAttributeCarrier) BufferedInputStream(java.io.BufferedInputStream) ContentInfo(com.github.zhenwei.core.asn1.pkcs.ContentInfo) EOFException(java.io.EOFException) ASN1Encodable(com.github.zhenwei.core.asn1.ASN1Encodable) EncryptedData(com.github.zhenwei.core.asn1.pkcs.EncryptedData) Vector(java.util.Vector) ASN1EncodableVector(com.github.zhenwei.core.asn1.ASN1EncodableVector) MacData(com.github.zhenwei.core.asn1.pkcs.MacData) ASN1InputStream(com.github.zhenwei.core.asn1.ASN1InputStream) Pfx(com.github.zhenwei.core.asn1.pkcs.Pfx) Enumeration(java.util.Enumeration) Hashtable(java.util.Hashtable) IOException(java.io.IOException) SafeBag(com.github.zhenwei.core.asn1.pkcs.SafeBag) KeyStoreException(java.security.KeyStoreException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) InvalidKeyException(java.security.InvalidKeyException) CertificateEncodingException(java.security.cert.CertificateEncodingException) InvalidKeySpecException(java.security.spec.InvalidKeySpecException) InvalidAlgorithmParameterException(java.security.InvalidAlgorithmParameterException) IOException(java.io.IOException) EOFException(java.io.EOFException) NoSuchPaddingException(javax.crypto.NoSuchPaddingException) UnrecoverableKeyException(java.security.UnrecoverableKeyException) CertificateException(java.security.cert.CertificateException) NoSuchProviderException(java.security.NoSuchProviderException) ASN1Sequence(com.github.zhenwei.core.asn1.ASN1Sequence) CertBag(com.github.zhenwei.core.asn1.pkcs.CertBag) ASN1Set(com.github.zhenwei.core.asn1.ASN1Set) ByteArrayInputStream(java.io.ByteArrayInputStream) DigestInfo(com.github.zhenwei.core.asn1.x509.DigestInfo) ASN1Primitive(com.github.zhenwei.core.asn1.ASN1Primitive) ASN1ObjectIdentifier(com.github.zhenwei.core.asn1.ASN1ObjectIdentifier) X509Certificate(java.security.cert.X509Certificate) Certificate(java.security.cert.Certificate)

Aggregations

ASN1Set (org.bouncycastle.asn1.ASN1Set)67 ArrayList (java.util.ArrayList)51 ASN1Set (com.unboundid.asn1.ASN1Set)33 IOException (java.io.IOException)32 ASN1OctetString (com.unboundid.asn1.ASN1OctetString)30 ASN1Sequence (com.unboundid.asn1.ASN1Sequence)30 ASN1Set (com.github.zhenwei.core.asn1.ASN1Set)26 ASN1Sequence (org.bouncycastle.asn1.ASN1Sequence)22 ASN1Element (com.unboundid.asn1.ASN1Element)21 NotNull (com.unboundid.util.NotNull)21 ASN1Encodable (org.bouncycastle.asn1.ASN1Encodable)19 List (java.util.List)17 ASN1OctetString (org.bouncycastle.asn1.ASN1OctetString)17 DEROctetString (org.bouncycastle.asn1.DEROctetString)16 Enumeration (java.util.Enumeration)14 ASN1ObjectIdentifier (org.bouncycastle.asn1.ASN1ObjectIdentifier)14 OutputStream (java.io.OutputStream)12 Test (org.testng.annotations.Test)12 ASN1Enumerated (com.unboundid.asn1.ASN1Enumerated)11 X509Certificate (java.security.cert.X509Certificate)11