Search in sources :

Example 21 with ASN1Set

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

the class JDKPKCS12KeyStore 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 = new Pfx(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.getObjectId(), 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.getObjectId(), 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 = new AuthenticatedSafe((ASN1Sequence) 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 = new SafeBag((ASN1Sequence) seq.getObjectAt(j));
                    if (b.getBagId().equals(pkcs8ShroudedKeyBag)) {
                        org.bouncycastle.asn1.pkcs.EncryptedPrivateKeyInfo eIn = new org.bouncycastle.asn1.pkcs.EncryptedPrivateKeyInfo((ASN1Sequence) 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();
                                DERObjectIdentifier aOid = (DERObjectIdentifier) sq.getObjectAt(0);
                                ASN1Set attrSet = (ASN1Set) sq.getObjectAt(1);
                                DERObject attr = null;
                                if (attrSet.size() > 0) {
                                    attr = (DERObject) attrSet.getObjectAt(0);
                                    DEREncodable existing = bagAttr.getBagAttribute(aOid);
                                    if (existing != null) {
                                        // OK, but the value has to be the same
                                        if (!existing.getDERObject().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 = new EncryptedData((ASN1Sequence) c[i].getContent());
                byte[] octets = cryptData(false, d.getEncryptionAlgorithm(), password, wrongPKCS12Zero, d.getContent().getOctets());
                ASN1Sequence seq = (ASN1Sequence) ASN1Object.fromByteArray(octets);
                for (int j = 0; j != seq.size(); j++) {
                    SafeBag b = new SafeBag((ASN1Sequence) seq.getObjectAt(j));
                    if (b.getBagId().equals(certBag)) {
                        chain.addElement(b);
                    } else if (b.getBagId().equals(pkcs8ShroudedKeyBag)) {
                        org.bouncycastle.asn1.pkcs.EncryptedPrivateKeyInfo eIn = new org.bouncycastle.asn1.pkcs.EncryptedPrivateKeyInfo((ASN1Sequence) 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();
                            DERObjectIdentifier aOid = (DERObjectIdentifier) sq.getObjectAt(0);
                            ASN1Set attrSet = (ASN1Set) sq.getObjectAt(1);
                            DERObject attr = null;
                            if (attrSet.size() > 0) {
                                attr = (DERObject) attrSet.getObjectAt(0);
                                DEREncodable existing = bagAttr.getBagAttribute(aOid);
                                if (existing != null) {
                                    // OK, but the value has to be the same
                                    if (!existing.getDERObject().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 pIn = new org.bouncycastle.asn1.pkcs.PrivateKeyInfo((ASN1Sequence) b.getBagValue());
                        PrivateKey privKey = JDKKeyFactory.createPrivateKeyFromPrivateKeyInfo(pIn);
                        //
                        // 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();
                            DERObjectIdentifier aOid = (DERObjectIdentifier) sq.getObjectAt(0);
                            ASN1Set attrSet = (ASN1Set) sq.getObjectAt(1);
                            DERObject attr = null;
                            if (attrSet.size() > 0) {
                                attr = (DERObject) attrSet.getObjectAt(0);
                                DEREncodable existing = bagAttr.getBagAttribute(aOid);
                                if (existing != null) {
                                    // OK, but the value has to be the same
                                    if (!existing.getDERObject().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 = new CertBag((ASN1Sequence) 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();
                DERObjectIdentifier oid = (DERObjectIdentifier) sq.getObjectAt(0);
                DERObject attr = (DERObject) ((ASN1Set) sq.getObjectAt(1)).getObjectAt(0);
                PKCS12BagAttributeCarrier bagAttr = null;
                if (cert instanceof PKCS12BagAttributeCarrier) {
                    bagAttr = (PKCS12BagAttributeCarrier) cert;
                    DEREncodable existing = bagAttr.getBagAttribute(oid);
                    if (existing != null) {
                        // OK, but the value has to be the same
                        if (!existing.getDERObject().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) BERConstructedOctetString(org.bouncycastle.asn1.BERConstructedOctetString) DEROctetString(org.bouncycastle.asn1.DEROctetString) PKCS12BagAttributeCarrier(org.bouncycastle.jce.interfaces.PKCS12BagAttributeCarrier) AlgorithmIdentifier(org.bouncycastle.asn1.x509.AlgorithmIdentifier) DERObject(org.bouncycastle.asn1.DERObject) BufferedInputStream(java.io.BufferedInputStream) ContentInfo(org.bouncycastle.asn1.pkcs.ContentInfo) 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) 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) 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) DEREncodable(org.bouncycastle.asn1.DEREncodable) X509Certificate(java.security.cert.X509Certificate) Certificate(java.security.cert.Certificate)

Example 22 with ASN1Set

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

the class SplitProviderDirectSignedDataGenerator method generate.

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

Example 23 with ASN1Set

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

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 24 with ASN1Set

use of org.bouncycastle.asn1.ASN1Set in project ddf by codice.

the class KeystoreEditor method importASN1CertificatesToStore.

private boolean importASN1CertificatesToStore(KeyStore store, boolean setEntry, ASN1Set certificates) throws KeystoreEditorException {
    Enumeration certificateEnumeration = certificates.getObjects();
    try {
        while (certificateEnumeration.hasMoreElements()) {
            ASN1Primitive asn1Primitive = ((ASN1Encodable) certificateEnumeration.nextElement()).toASN1Primitive();
            org.bouncycastle.asn1.x509.Certificate instance = org.bouncycastle.asn1.x509.Certificate.getInstance(asn1Primitive);
            CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509", "BC");
            Certificate certificate = certificateFactory.generateCertificate(new ByteArrayInputStream(instance.getEncoded()));
            X500Name x500name = new JcaX509CertificateHolder((X509Certificate) certificate).getSubject();
            RDN cn = x500name.getRDNs(BCStyle.CN)[0];
            store.setCertificateEntry(IETFUtils.valueToString(cn.getFirst().getValue()), certificate);
            setEntry = true;
        }
    } catch (CertificateException | NoSuchProviderException | KeyStoreException | IOException e) {
        throw new KeystoreEditorException("Unable to import ASN1 certificates to store", e);
    }
    return setEntry;
}
Also used : Enumeration(java.util.Enumeration) CertificateException(java.security.cert.CertificateException) X500Name(org.bouncycastle.asn1.x500.X500Name) KeyStoreException(java.security.KeyStoreException) IOException(java.io.IOException) CertificateFactory(java.security.cert.CertificateFactory) JcaX509CertificateHolder(org.bouncycastle.cert.jcajce.JcaX509CertificateHolder) X509Certificate(java.security.cert.X509Certificate) ByteArrayInputStream(java.io.ByteArrayInputStream) ASN1Encodable(org.bouncycastle.asn1.ASN1Encodable) NoSuchProviderException(java.security.NoSuchProviderException) ASN1Primitive(org.bouncycastle.asn1.ASN1Primitive) RDN(org.bouncycastle.asn1.x500.RDN) X509Certificate(java.security.cert.X509Certificate) Certificate(java.security.cert.Certificate)

Example 25 with ASN1Set

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

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)

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