Search in sources :

Example 16 with ASN1Set

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

the class SignerInfoGenerator method generate.

public SignerInfo generate(ASN1ObjectIdentifier contentType) throws CMSException {
    try {
        /* RFC 3852 5.4
             * The result of the message digest calculation process depends on
             * whether the signedAttrs field is present.  When the field is absent,
             * the result is just the message digest of the content as described
             *
             * above.  When the field is present, however, the result is the message
             * digest of the complete DER encoding of the SignedAttrs value
             * contained in the signedAttrs field.
             */
        ASN1Set signedAttr = null;
        AlgorithmIdentifier digestAlg = null;
        if (sAttrGen != null) {
            digestAlg = digester.getAlgorithmIdentifier();
            calculatedDigest = digester.getDigest();
            Map parameters = getBaseParameters(contentType, digester.getAlgorithmIdentifier(), calculatedDigest);
            AttributeTable signed = sAttrGen.getAttributes(Collections.unmodifiableMap(parameters));
            signedAttr = getAttributeSet(signed);
            // sig must be composed from the DER encoding.
            OutputStream sOut = signer.getOutputStream();
            sOut.write(signedAttr.getEncoded(ASN1Encoding.DER));
            sOut.close();
        } else {
            if (digester != null) {
                digestAlg = digester.getAlgorithmIdentifier();
                calculatedDigest = digester.getDigest();
            } else {
                digestAlg = digAlgFinder.find(signer.getAlgorithmIdentifier());
                calculatedDigest = null;
            }
        }
        byte[] sigBytes = signer.getSignature();
        ASN1Set unsignedAttr = null;
        if (unsAttrGen != null) {
            Map parameters = getBaseParameters(contentType, digestAlg, calculatedDigest);
            parameters.put(CMSAttributeTableGenerator.SIGNATURE, sigBytes.clone());
            AttributeTable unsigned = unsAttrGen.getAttributes(Collections.unmodifiableMap(parameters));
            unsignedAttr = getAttributeSet(unsigned);
        }
        AlgorithmIdentifier digestEncryptionAlgorithm = sigEncAlgFinder.findEncryptionAlgorithm(signer.getAlgorithmIdentifier());
        return new SignerInfo(signerIdentifier, digestAlg, signedAttr, digestEncryptionAlgorithm, new DEROctetString(sigBytes), unsignedAttr);
    } catch (IOException e) {
        throw new CMSException("encoding error.", e);
    }
}
Also used : SignerInfo(org.bouncycastle.asn1.cms.SignerInfo) ASN1Set(org.bouncycastle.asn1.ASN1Set) OutputStream(java.io.OutputStream) TeeOutputStream(org.bouncycastle.util.io.TeeOutputStream) AttributeTable(org.bouncycastle.asn1.cms.AttributeTable) IOException(java.io.IOException) HashMap(java.util.HashMap) Map(java.util.Map) DEROctetString(org.bouncycastle.asn1.DEROctetString) AlgorithmIdentifier(org.bouncycastle.asn1.x509.AlgorithmIdentifier)

Example 17 with ASN1Set

use of org.bouncycastle.asn1.ASN1Set 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 18 with ASN1Set

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

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();
        SignatureAlgorithmIdentifierFinder sigAlgFinder = new DefaultSignatureAlgorithmIdentifierFinder();
        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 : DefaultSignatureAlgorithmIdentifierFinder(org.bouncycastle.operator.DefaultSignatureAlgorithmIdentifierFinder) SignatureAlgorithmIdentifierFinder(org.bouncycastle.operator.SignatureAlgorithmIdentifierFinder) ArrayList(java.util.ArrayList) ASN1OctetString(org.bouncycastle.asn1.ASN1OctetString) DefaultSignatureAlgorithmIdentifierFinder(org.bouncycastle.operator.DefaultSignatureAlgorithmIdentifierFinder) SignerInfo(org.bouncycastle.asn1.cms.SignerInfo) ASN1Set(org.bouncycastle.asn1.ASN1Set) ArrayList(java.util.ArrayList) List(java.util.List) ASN1ObjectIdentifier(org.bouncycastle.asn1.ASN1ObjectIdentifier)

Example 19 with ASN1Set

use of org.bouncycastle.asn1.ASN1Set in project android_frameworks_base by AOSPA.

the class ESTHandler method buildCSR.

private byte[] buildCSR(ByteBuffer octetBuffer, OMADMAdapter omadmAdapter, HTTPHandler httpHandler) throws IOException, GeneralSecurityException {
    //Security.addProvider(new BouncyCastleProvider());
    Log.d(TAG, "/csrattrs:");
    /*
        byte[] octets = new byte[octetBuffer.remaining()];
        octetBuffer.duplicate().get(octets);
        for (byte b : octets) {
            System.out.printf("%02x ", b & 0xff);
        }
        */
    Collection<Asn1Object> csrs = Asn1Decoder.decode(octetBuffer);
    for (Asn1Object asn1Object : csrs) {
        Log.d(TAG, asn1Object.toString());
    }
    if (csrs.size() != 1) {
        throw new IOException("Unexpected object count in CSR attributes response: " + csrs.size());
    }
    Asn1Object sequence = csrs.iterator().next();
    if (sequence.getClass() != Asn1Constructed.class) {
        throw new IOException("Unexpected CSR attribute container: " + sequence);
    }
    String keyAlgo = null;
    Asn1Oid keyAlgoOID = null;
    String sigAlgo = null;
    String curveName = null;
    Asn1Oid pubCrypto = null;
    int keySize = -1;
    Map<Asn1Oid, ASN1Encodable> idAttributes = new HashMap<>();
    for (Asn1Object child : sequence.getChildren()) {
        if (child.getTag() == Asn1Decoder.TAG_OID) {
            Asn1Oid oid = (Asn1Oid) child;
            OidMappings.SigEntry sigEntry = OidMappings.getSigEntry(oid);
            if (sigEntry != null) {
                sigAlgo = sigEntry.getSigAlgo();
                keyAlgoOID = sigEntry.getKeyAlgo();
                keyAlgo = OidMappings.getJCEName(keyAlgoOID);
            } else if (oid.equals(OidMappings.sPkcs9AtChallengePassword)) {
                byte[] tlsUnique = httpHandler.getTLSUnique();
                if (tlsUnique != null) {
                    idAttributes.put(oid, new DERPrintableString(Base64.encodeToString(tlsUnique, Base64.DEFAULT)));
                } else {
                    Log.w(TAG, "Cannot retrieve TLS unique channel binding");
                }
            }
        } else if (child.getTag() == Asn1Decoder.TAG_SEQ) {
            Asn1Oid oid = null;
            Set<Asn1Oid> oidValues = new HashSet<>();
            List<Asn1Object> values = new ArrayList<>();
            for (Asn1Object attributeSeq : child.getChildren()) {
                if (attributeSeq.getTag() == Asn1Decoder.TAG_OID) {
                    oid = (Asn1Oid) attributeSeq;
                } else if (attributeSeq.getTag() == Asn1Decoder.TAG_SET) {
                    for (Asn1Object value : attributeSeq.getChildren()) {
                        if (value.getTag() == Asn1Decoder.TAG_OID) {
                            oidValues.add((Asn1Oid) value);
                        } else {
                            values.add(value);
                        }
                    }
                }
            }
            if (oid == null) {
                throw new IOException("Invalid attribute, no OID");
            }
            if (oid.equals(OidMappings.sExtensionRequest)) {
                for (Asn1Oid subOid : oidValues) {
                    if (OidMappings.isIDAttribute(subOid)) {
                        if (subOid.equals(OidMappings.sMAC)) {
                            idAttributes.put(subOid, new DERIA5String(omadmAdapter.getMAC()));
                        } else if (subOid.equals(OidMappings.sIMEI)) {
                            idAttributes.put(subOid, new DERIA5String(omadmAdapter.getImei()));
                        } else if (subOid.equals(OidMappings.sMEID)) {
                            idAttributes.put(subOid, new DERBitString(omadmAdapter.getMeid()));
                        } else if (subOid.equals(OidMappings.sDevID)) {
                            idAttributes.put(subOid, new DERPrintableString(omadmAdapter.getDevID()));
                        }
                    }
                }
            } else if (OidMappings.getCryptoID(oid) != null) {
                pubCrypto = oid;
                if (!values.isEmpty()) {
                    for (Asn1Object value : values) {
                        if (value.getTag() == Asn1Decoder.TAG_INTEGER) {
                            keySize = (int) ((Asn1Integer) value).getValue();
                        }
                    }
                }
                if (oid.equals(OidMappings.sAlgo_EC)) {
                    if (oidValues.isEmpty()) {
                        throw new IOException("No ECC curve name provided");
                    }
                    for (Asn1Oid value : oidValues) {
                        curveName = OidMappings.getJCEName(value);
                        if (curveName != null) {
                            break;
                        }
                    }
                    if (curveName == null) {
                        throw new IOException("Found no ECC curve for " + oidValues);
                    }
                }
            }
        }
    }
    if (keyAlgoOID == null) {
        throw new IOException("No public key algorithm specified");
    }
    if (pubCrypto != null && !pubCrypto.equals(keyAlgoOID)) {
        throw new IOException("Mismatching key algorithms");
    }
    if (keyAlgoOID.equals(OidMappings.sAlgo_RSA)) {
        if (keySize < MinRSAKeySize) {
            if (keySize >= 0) {
                Log.i(TAG, "Upgrading suggested RSA key size from " + keySize + " to " + MinRSAKeySize);
            }
            keySize = MinRSAKeySize;
        }
    }
    Log.d(TAG, String.format("pub key '%s', signature '%s', ECC curve '%s', id-atts %s", keyAlgo, sigAlgo, curveName, idAttributes));
    /*
          Ruckus:
            SEQUENCE:
              OID=1.2.840.113549.1.1.11 (algo_id_sha256WithRSAEncryption)

          RFC-7030:
            SEQUENCE:
              OID=1.2.840.113549.1.9.7 (challengePassword)
              SEQUENCE:
                OID=1.2.840.10045.2.1 (algo_id_ecPublicKey)
                SET:
                  OID=1.3.132.0.34 (secp384r1)
              SEQUENCE:
                OID=1.2.840.113549.1.9.14 (extensionRequest)
                SET:
                  OID=1.3.6.1.1.1.1.22 (mac-address)
              OID=1.2.840.10045.4.3.3 (eccdaWithSHA384)

              1L, 3L, 6L, 1L, 1L, 1L, 1L, 22
         */
    // ECC Does not appear to be supported currently
    KeyPairGenerator kpg = KeyPairGenerator.getInstance(keyAlgo);
    if (curveName != null) {
        AlgorithmParameters algorithmParameters = AlgorithmParameters.getInstance(keyAlgo);
        algorithmParameters.init(new ECNamedCurveGenParameterSpec(curveName));
        kpg.initialize(algorithmParameters.getParameterSpec(ECNamedCurveGenParameterSpec.class));
    } else {
        kpg.initialize(keySize);
    }
    KeyPair kp = kpg.generateKeyPair();
    X500Principal subject = new X500Principal("CN=Android, O=Google, C=US");
    mClientKey = kp.getPrivate();
    // !!! Map the idAttributes into an ASN1Set of values to pass to
    // the PKCS10CertificationRequest - this code is using outdated BC classes and
    // has *not* been tested.
    ASN1Set attributes;
    if (!idAttributes.isEmpty()) {
        ASN1EncodableVector payload = new DEREncodableVector();
        for (Map.Entry<Asn1Oid, ASN1Encodable> entry : idAttributes.entrySet()) {
            DERObjectIdentifier type = new DERObjectIdentifier(entry.getKey().toOIDString());
            ASN1Set values = new DERSet(entry.getValue());
            Attribute attribute = new Attribute(type, values);
            payload.add(attribute);
        }
        attributes = new DERSet(payload);
    } else {
        attributes = null;
    }
    return new PKCS10CertificationRequest(sigAlgo, subject, kp.getPublic(), attributes, mClientKey).getEncoded();
}
Also used : DERSet(com.android.org.bouncycastle.asn1.DERSet) ASN1Set(com.android.org.bouncycastle.asn1.ASN1Set) Set(java.util.Set) HashSet(java.util.HashSet) HashMap(java.util.HashMap) Attribute(com.android.org.bouncycastle.asn1.x509.Attribute) DERBitString(com.android.org.bouncycastle.asn1.DERBitString) DERPrintableString(com.android.org.bouncycastle.asn1.DERPrintableString) DERIA5String(com.android.org.bouncycastle.asn1.DERIA5String) DERSet(com.android.org.bouncycastle.asn1.DERSet) DERIA5String(com.android.org.bouncycastle.asn1.DERIA5String) Asn1Integer(com.android.hotspot2.asn1.Asn1Integer) DERPrintableString(com.android.org.bouncycastle.asn1.DERPrintableString) ASN1EncodableVector(com.android.org.bouncycastle.asn1.ASN1EncodableVector) List(java.util.List) ArrayList(java.util.ArrayList) ASN1Encodable(com.android.org.bouncycastle.asn1.ASN1Encodable) PKCS10CertificationRequest(com.android.org.bouncycastle.jce.PKCS10CertificationRequest) Asn1Oid(com.android.hotspot2.asn1.Asn1Oid) KeyPair(java.security.KeyPair) ECNamedCurveGenParameterSpec(com.android.org.bouncycastle.jce.spec.ECNamedCurveGenParameterSpec) DEREncodableVector(com.android.org.bouncycastle.asn1.DEREncodableVector) DERBitString(com.android.org.bouncycastle.asn1.DERBitString) IOException(java.io.IOException) KeyPairGenerator(java.security.KeyPairGenerator) DERObjectIdentifier(com.android.org.bouncycastle.asn1.DERObjectIdentifier) Asn1Object(com.android.hotspot2.asn1.Asn1Object) OidMappings(com.android.hotspot2.asn1.OidMappings) ASN1Set(com.android.org.bouncycastle.asn1.ASN1Set) X500Principal(javax.security.auth.x500.X500Principal) Map(java.util.Map) HashMap(java.util.HashMap) AlgorithmParameters(java.security.AlgorithmParameters)

Example 20 with ASN1Set

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

ASN1Set (org.bouncycastle.asn1.ASN1Set)18 IOException (java.io.IOException)12 ArrayList (java.util.ArrayList)8 Enumeration (java.util.Enumeration)8 List (java.util.List)8 ASN1EncodableVector (org.bouncycastle.asn1.ASN1EncodableVector)7 ASN1OctetString (org.bouncycastle.asn1.ASN1OctetString)7 KeyPair (java.security.KeyPair)6 HashMap (java.util.HashMap)6 Map (java.util.Map)6 Asn1Integer (com.android.hotspot2.asn1.Asn1Integer)5 Asn1Object (com.android.hotspot2.asn1.Asn1Object)5 Asn1Oid (com.android.hotspot2.asn1.Asn1Oid)5 OidMappings (com.android.hotspot2.asn1.OidMappings)5 ASN1Encodable (com.android.org.bouncycastle.asn1.ASN1Encodable)5 ASN1EncodableVector (com.android.org.bouncycastle.asn1.ASN1EncodableVector)5 ASN1Set (com.android.org.bouncycastle.asn1.ASN1Set)5 DERBitString (com.android.org.bouncycastle.asn1.DERBitString)5 DEREncodableVector (com.android.org.bouncycastle.asn1.DEREncodableVector)5 DERIA5String (com.android.org.bouncycastle.asn1.DERIA5String)5