Search in sources :

Example 76 with Attribute

use of org.jdom2.Attribute in project gocd by gocd.

the class ConfigCipherUpdater method migrate.

public void migrate() {
    File cipherFile = systemEnvironment.getCipherFile();
    String timestamp = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss").format(timeProvider.currentTime());
    File backupCipherFile = new File(systemEnvironment.getConfigDir(), "cipher.original." + timestamp);
    File configFile = new File(systemEnvironment.getCruiseConfigFile());
    File backupConfigFile = new File(configFile.getParentFile(), configFile.getName() + ".original." + timestamp);
    try {
        if (!cipherFile.exists() || !FileUtils.readFileToString(cipherFile).equals(FLAWED_VALUE)) {
            return;
        }
        LOGGER.info("Found unsafe cipher {} on server, Go will make an attempt to rekey", FLAWED_VALUE);
        FileUtils.copyFile(cipherFile, backupCipherFile);
        LOGGER.info("Old cipher was successfully backed up to {}", backupCipherFile.getAbsoluteFile());
        FileUtils.copyFile(configFile, backupConfigFile);
        LOGGER.info("Old config was successfully backed up to {}", backupConfigFile.getAbsoluteFile());
        byte[] oldCipher = FileUtils.readFileToByteArray(backupCipherFile);
        new CipherProvider(systemEnvironment).resetCipher();
        byte[] newCipher = FileUtils.readFileToByteArray(cipherFile);
        if (new String(newCipher).equals(new String(oldCipher))) {
            LOGGER.warn("Unable to generate a new safe cipher. Your cipher is unsafe.");
            FileUtils.deleteQuietly(backupCipherFile);
            FileUtils.deleteQuietly(backupConfigFile);
            return;
        }
        Document document = new SAXBuilder().build(configFile);
        List<String> encryptedAttributes = Arrays.asList("encryptedPassword", "encryptedManagerPassword");
        List<String> encryptedNodes = Arrays.asList("encryptedValue");
        XPathFactory xPathFactory = XPathFactory.instance();
        for (String attributeName : encryptedAttributes) {
            XPathExpression<Element> xpathExpression = xPathFactory.compile(String.format("//*[@%s]", attributeName), Filters.element());
            List<Element> encryptedPasswordElements = xpathExpression.evaluate(document);
            for (Element element : encryptedPasswordElements) {
                Attribute encryptedPassword = element.getAttribute(attributeName);
                encryptedPassword.setValue(reEncryptUsingNewKey(oldCipher, newCipher, encryptedPassword.getValue()));
                LOGGER.debug("Replaced encrypted value at {}", element.toString());
            }
        }
        for (String nodeName : encryptedNodes) {
            XPathExpression<Element> xpathExpression = xPathFactory.compile(String.format("//%s", nodeName), Filters.element());
            List<Element> encryptedNode = xpathExpression.evaluate(document);
            for (Element element : encryptedNode) {
                element.setText(reEncryptUsingNewKey(oldCipher, newCipher, element.getValue()));
                LOGGER.debug("Replaced encrypted value at {}", element.toString());
            }
        }
        try (FileOutputStream fileOutputStream = new FileOutputStream(configFile)) {
            XmlUtils.writeXml(document, fileOutputStream);
        }
        LOGGER.info("Successfully re-encrypted config");
    } catch (Exception e) {
        LOGGER.error("Re-keying of cipher failed with error: [{}]", e.getMessage(), e);
        if (backupCipherFile.exists()) {
            try {
                FileUtils.copyFile(backupCipherFile, cipherFile);
            } catch (IOException e1) {
                LOGGER.error("Could not replace the cipher file [{}] with original one [{}], please do so manually. Error: [{}]", cipherFile.getAbsolutePath(), backupCipherFile.getAbsolutePath(), e.getMessage(), e);
                bomb(e1);
            }
        }
    }
}
Also used : SAXBuilder(org.jdom2.input.SAXBuilder) Attribute(org.jdom2.Attribute) CipherProvider(com.thoughtworks.go.security.CipherProvider) Element(org.jdom2.Element) IOException(java.io.IOException) Document(org.jdom2.Document) IOException(java.io.IOException) InvalidCipherTextException(org.bouncycastle.crypto.InvalidCipherTextException) XPathFactory(org.jdom2.xpath.XPathFactory) FileOutputStream(java.io.FileOutputStream) File(java.io.File) SimpleDateFormat(java.text.SimpleDateFormat)

Example 77 with Attribute

use of org.jdom2.Attribute in project robovm by robovm.

the class X509AttributeCertificateHolder method getAttributes.

/**
     * Return the attributes, if any associated with this request.
     *
     * @return an array of Attribute, zero length if none present.
     */
public Attribute[] getAttributes() {
    ASN1Sequence seq = attrCert.getAcinfo().getAttributes();
    Attribute[] attrs = new Attribute[seq.size()];
    for (int i = 0; i != seq.size(); i++) {
        attrs[i] = Attribute.getInstance(seq.getObjectAt(i));
    }
    return attrs;
}
Also used : ASN1Sequence(org.bouncycastle.asn1.ASN1Sequence) Attribute(org.bouncycastle.asn1.x509.Attribute)

Example 78 with Attribute

use of org.jdom2.Attribute 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 79 with Attribute

use of org.jdom2.Attribute in project nhin-d by DirectProject.

the class PKCS11Commands method createCSR.

@Command(name = "CreateCSR", usage = CREATE_CSR)
public void createCSR(String[] args) {
    final String alias = StringArrayUtil.getRequiredValue(args, 0);
    final String commonName = StringArrayUtil.getRequiredValue(args, 1);
    final String subjectAltName = StringArrayUtil.getRequiredValue(args, 2);
    final String keyUsage = StringArrayUtil.getRequiredValue(args, 3);
    // make sure we have a valid keyUsage
    if (!(keyUsage.compareToIgnoreCase("DigitalSignature") == 0 || keyUsage.compareToIgnoreCase("KeyEncipherment") == 0 || keyUsage.compareToIgnoreCase("DualUse") == 0)) {
        System.out.println("Invalid key usage.");
        return;
    }
    final Vector<String> additionalRDNFields = new Vector<String>();
    int cnt = 4;
    String rdnField;
    do {
        rdnField = StringArrayUtil.getOptionalValue(args, cnt++, "");
        if (!StringUtils.isEmpty(rdnField))
            additionalRDNFields.add(rdnField);
    } while (!StringUtils.isEmpty(rdnField));
    try {
        final KeyStore ks = mgr.getKS();
        if (!ks.containsAlias(alias)) {
            System.out.println("Entry with key name " + alias + " does not exist.");
            return;
        }
        final X509Certificate storedCert = (X509Certificate) ks.getCertificate(alias);
        if (storedCert == null) {
            System.out.println("Key name " + alias + " does not contain a certificate that can be exported.  This key may not be an RSA key pair.");
            return;
        }
        final PrivateKey privKey = (PrivateKey) ks.getKey(alias, "".toCharArray());
        if (privKey == null) {
            System.out.println("Failed to object private key.  This key may not be an RSA key pair.");
            return;
        }
        // create the CSR
        //  create the extensions that we want
        final X509ExtensionsGenerator extsGen = new X509ExtensionsGenerator();
        // Key Usage
        int usage;
        if (keyUsage.compareToIgnoreCase("KeyEncipherment") == 0)
            usage = KeyUsage.keyEncipherment;
        else if (keyUsage.compareToIgnoreCase("DigitalSignature") == 0)
            usage = KeyUsage.digitalSignature;
        else
            usage = KeyUsage.keyEncipherment | KeyUsage.digitalSignature;
        extsGen.addExtension(X509Extensions.KeyUsage, true, new KeyUsage(usage));
        // Subject Alt Name
        int nameType = subjectAltName.contains("@") ? GeneralName.rfc822Name : GeneralName.dNSName;
        final GeneralNames altName = new GeneralNames(new GeneralName(nameType, subjectAltName));
        extsGen.addExtension(X509Extensions.SubjectAlternativeName, false, altName);
        // Extended Key Usage
        final Vector<KeyPurposeId> purposes = new Vector<KeyPurposeId>();
        purposes.add(KeyPurposeId.id_kp_emailProtection);
        extsGen.addExtension(X509Extensions.ExtendedKeyUsage, false, new ExtendedKeyUsage(purposes));
        // Basic constraint
        final BasicConstraints bc = new BasicConstraints(false);
        extsGen.addExtension(X509Extensions.BasicConstraints, true, bc);
        // create the extension requests
        final X509Extensions exts = extsGen.generate();
        final ASN1EncodableVector attributes = new ASN1EncodableVector();
        final Attribute attribute = new Attribute(PKCSObjectIdentifiers.pkcs_9_at_extensionRequest, new DERSet(exts.toASN1Object()));
        attributes.add(attribute);
        final DERSet requestedAttributes = new DERSet(attributes);
        // create the DN
        final StringBuilder dnBuilder = new StringBuilder("CN=").append(commonName);
        for (String field : additionalRDNFields) dnBuilder.append(",").append(field);
        final X500Principal subjectPrin = new X500Principal(dnBuilder.toString());
        final X509Principal xName = new X509Principal(true, subjectPrin.getName());
        // create the CSR
        final PKCS10CertificationRequest request = new PKCS10CertificationRequest("SHA256WITHRSA", xName, storedCert.getPublicKey(), requestedAttributes, privKey, ks.getProvider().getName());
        final byte[] encodedCSR = request.getEncoded();
        final String csrString = "-----BEGIN CERTIFICATE REQUEST-----\r\n" + Base64.encodeBase64String(encodedCSR) + "-----END CERTIFICATE REQUEST-----";
        final File csrFile = new File(alias + "-CSR.pem");
        FileUtils.writeStringToFile(csrFile, csrString);
        System.out.println("CSR written to " + csrFile.getAbsolutePath());
    } catch (Exception e) {
        e.printStackTrace();
        System.err.println("Failed to create CSR : " + e.getMessage());
    }
}
Also used : PrivateKey(java.security.PrivateKey) Attribute(org.bouncycastle.asn1.x509.Attribute) KeyUsage(org.bouncycastle.asn1.x509.KeyUsage) ExtendedKeyUsage(org.bouncycastle.asn1.x509.ExtendedKeyUsage) X509Extensions(org.bouncycastle.asn1.x509.X509Extensions) DERSet(org.bouncycastle.asn1.DERSet) X509Principal(org.bouncycastle.jce.X509Principal) ASN1EncodableVector(org.bouncycastle.asn1.ASN1EncodableVector) X509ExtensionsGenerator(org.bouncycastle.asn1.x509.X509ExtensionsGenerator) Vector(java.util.Vector) ASN1EncodableVector(org.bouncycastle.asn1.ASN1EncodableVector) ExtendedKeyUsage(org.bouncycastle.asn1.x509.ExtendedKeyUsage) PKCS10CertificationRequest(org.bouncycastle.jce.PKCS10CertificationRequest) KeyPurposeId(org.bouncycastle.asn1.x509.KeyPurposeId) KeyStore(java.security.KeyStore) X509Certificate(java.security.cert.X509Certificate) GeneralNames(org.bouncycastle.asn1.x509.GeneralNames) X500Principal(javax.security.auth.x500.X500Principal) GeneralName(org.bouncycastle.asn1.x509.GeneralName) BasicConstraints(org.bouncycastle.asn1.x509.BasicConstraints) File(java.io.File) Command(org.nhindirect.common.tooling.Command)

Example 80 with Attribute

use of org.jdom2.Attribute 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)

Aggregations

Attribute (org.jdom2.Attribute)104 Element (org.jdom2.Element)96 DataConversionException (org.jdom2.DataConversionException)17 Editor (jmri.jmrit.display.Editor)15 ArrayList (java.util.ArrayList)13 NamedIcon (jmri.jmrit.catalog.NamedIcon)13 IOException (java.io.IOException)12 LayoutEditor (jmri.jmrit.display.layoutEditor.LayoutEditor)10 File (java.io.File)8 Color (java.awt.Color)7 List (java.util.List)7 HashMap (java.util.HashMap)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