Example usage for java.security.cert X509Certificate getSubjectX500Principal

List of usage examples for java.security.cert X509Certificate getSubjectX500Principal

Introduction

In this page you can find the example usage for java.security.cert X509Certificate getSubjectX500Principal.

Prototype

public X500Principal getSubjectX500Principal() 

Source Link

Document

Returns the subject (subject distinguished name) value from the certificate as an X500Principal .

Usage

From source file:org.guanxi.sp.engine.form.RegisterGuardFormController.java

/**
 * Handles the nitty gritty of signing a CSR
 *
 * @param rootCert The certificate of the root authority who will vouch for the entity
 * @param rootPrivKey The private key of the root authority who will vouch for the entity
 * @param csr The entitie's CSR/*from   w  w  w  .  java  2 s.  c o m*/
 * @param keyType The type of the key, e.g. "RSA", "DSA"
 * @return A certificate chain as an array of X509Certificate instances or null if an
 * error occurred
 */
private X509Certificate[] createSignedCert(X509Certificate rootCert, PrivateKey rootPrivKey,
        PKCS10CertificationRequest csr, String keyType) {
    X509V3CertificateGenerator certGen = new X509V3CertificateGenerator();

    try {
        Date validFrom = new Date();
        validFrom.setTime(validFrom.getTime() - (10 * 60 * 1000));
        Date validTo = new Date();
        validTo.setTime(validTo.getTime() + (20 * (24 * 60 * 60 * 1000)));

        certGen.setSerialNumber(BigInteger.valueOf(System.currentTimeMillis()));
        certGen.setIssuerDN(rootCert.getSubjectX500Principal());
        certGen.setNotBefore(validFrom);
        certGen.setNotAfter(validTo);
        certGen.setSubjectDN(csr.getCertificationRequestInfo().getSubject());
        certGen.setPublicKey(csr.getPublicKey("BC"));

        if (keyType.toLowerCase().equals("rsa"))
            certGen.setSignatureAlgorithm("SHA256WithRSAEncryption");
        if (keyType.toLowerCase().equals("dsa"))
            certGen.setSignatureAlgorithm("DSAWithSHA1");

        certGen.addExtension(X509Extensions.AuthorityKeyIdentifier, false,
                new AuthorityKeyIdentifierStructure(rootCert));
        certGen.addExtension(X509Extensions.SubjectKeyIdentifier, false,
                new SubjectKeyIdentifierStructure(csr.getPublicKey("BC")));
        certGen.addExtension(X509Extensions.BasicConstraints, true, new BasicConstraints(false));
        certGen.addExtension(X509Extensions.KeyUsage, true,
                new KeyUsage(KeyUsage.digitalSignature | KeyUsage.keyEncipherment));
        certGen.addExtension(X509Extensions.ExtendedKeyUsage, true,
                new ExtendedKeyUsage(KeyPurposeId.id_kp_clientAuth));

        X509Certificate issuedCert = certGen.generate(rootPrivKey, "BC");
        return new X509Certificate[] { issuedCert, rootCert };
    } catch (Exception e) {
        logger.error(e);
        return null;
    }
}

From source file:com.microsoft.azure.keyvault.test.CertificateOperationsTest.java

/**
 * Create a self-signed certificate in PKCS12 format (which includes the
 * private key) certificate./*from   w  w w .  java  2s. c o  m*/
 * 
 * @throws Exception
 */
@Test
public void createSelfSignedCertificatePkcs12() throws Exception {
    // Set content type to indicate the certificate is PKCS12 format.
    SecretProperties secretProperties = new SecretProperties().withContentType(MIME_PKCS12);

    String subjectName = "CN=SelfSignedJavaPkcs12";
    X509CertificateProperties x509Properties = new X509CertificateProperties().withSubject(subjectName)
            .withValidityInMonths(12);

    // Set issuer to "Self"
    IssuerParameters issuerParameters = new IssuerParameters().withName(ISSUER_SELF);

    CertificatePolicy certificatePolicy = new CertificatePolicy().withSecretProperties(secretProperties)
            .withIssuerParameters(issuerParameters).withX509CertificateProperties(x509Properties);

    Attributes attribute = new CertificateAttributes().withEnabled(true)
            .withExpires(new DateTime().withYear(2050).withMonthOfYear(1))
            .withNotBefore(new DateTime().withYear(2000).withMonthOfYear(1));

    String vaultUri = getVaultUri();
    String certificateName = "createSelfSignedJavaPkcs12";

    CreateCertificateRequest createCertificateRequest = new CreateCertificateRequest.Builder(vaultUri,
            certificateName).withPolicy(certificatePolicy).withAttributes(attribute).withTags(sTags).build();

    CertificateOperation certificateOperation = keyVaultClient.createCertificate(createCertificateRequest);

    Assert.assertNotNull(certificateOperation);
    Assert.assertTrue(certificateOperation.status().equalsIgnoreCase(STATUS_IN_PROGRESS));

    CertificateBundle certificateBundle = pollOnCertificateOperation(certificateOperation);
    validateCertificateBundle(certificateBundle, certificatePolicy);
    compareAttributes(attribute, createCertificateRequest.certificateAttributes());

    // Load the CER part into X509Certificate object
    X509Certificate x509Certificate = loadCerToX509Certificate(certificateBundle);

    Assert.assertTrue(x509Certificate.getSubjectX500Principal().getName().equals(subjectName));
    Assert.assertTrue(x509Certificate.getIssuerX500Principal().getName().equals(subjectName));

    // Retrieve the secret backing the certificate
    SecretIdentifier secretIdentifier = certificateBundle.secretIdentifier();
    SecretBundle secret = keyVaultClient.getSecret(secretIdentifier.baseIdentifier());
    Assert.assertTrue(secret.managed());

    // Retrieve the key backing the certificate
    KeyIdentifier keyIdentifier = certificateBundle.keyIdentifier();
    KeyBundle keyBundle = keyVaultClient.getKey(keyIdentifier.baseIdentifier());
    Assert.assertTrue(keyBundle.managed());

    // Load the secret into a KeyStore
    String secretPassword = "";
    KeyStore keyStore = loadSecretToKeyStore(secret, secretPassword);

    // Validate the certificate and key in the KeyStore
    validateCertificateKeyInKeyStore(keyStore, x509Certificate, secretPassword);

    CertificateBundle deletedCertificateBundle = keyVaultClient.deleteCertificate(getVaultUri(),
            certificateName);
    Assert.assertNotNull(deletedCertificateBundle);
    try {
        keyVaultClient.getCertificate(deletedCertificateBundle.certificateIdentifier().baseIdentifier());
    } catch (KeyVaultErrorException e) {
        Assert.assertNotNull(e.body().error());
        Assert.assertEquals("CertificateNotFound", e.body().error().code());
    }
}

From source file:com.microsoft.azure.keyvault.test.CertificateOperationsTest.java

/**
 * Create a test-issuer issued certificate in PKCS12 format (which includes
 * the private key) certificate./*from   w  w  w  . j  a  v  a  2  s.  c o m*/
 * 
 * @throws Exception
 */
@Test
public void createCertificatePkcs12() throws Exception {
    // Construct organization administrator details
    AdministratorDetails administratorDetails = new AdministratorDetails().withFirstName("John")
            .withLastName("Doe").withEmailAddress("john.doe@contoso.com").withPhone("1234567890");

    // Construct organization details
    List<AdministratorDetails> administratorsDetails = new ArrayList<AdministratorDetails>();
    administratorsDetails.add(administratorDetails);
    OrganizationDetails organizationDetails = new OrganizationDetails().withAdminDetails(administratorsDetails);

    // Construct certificate issuer credentials
    IssuerCredentials credentials = new IssuerCredentials().withAccountId("account1").withPassword("Pa$$w0rd");

    String certificateIssuerName = "createCertificateJavaPkcs12Issuer01";
    IssuerBundle createdCertificateIssuer = keyVaultClient.setCertificateIssuer(
            new SetCertificateIssuerRequest.Builder(getVaultUri(), certificateIssuerName, ISSUER_TEST)
                    .withCredentials(credentials).withOrganizationDetails(organizationDetails).build());

    validateCertificateIssuer(createdCertificateIssuer, certificateIssuerName);

    // Set content type to indicate the certificate is PKCS12 format.
    SecretProperties secretProperties = new SecretProperties().withContentType(MIME_PKCS12);

    String subjectName = "CN=TestJavaPkcs12";
    X509CertificateProperties x509Properties = new X509CertificateProperties().withSubject(subjectName)
            .withValidityInMonths(12);

    // Set issuer reference to the created issuer
    IssuerParameters issuerParameters = new IssuerParameters();
    issuerParameters.withName(createdCertificateIssuer.issuerIdentifier().name());

    CertificatePolicy certificatePolicy = new CertificatePolicy().withSecretProperties(secretProperties)
            .withIssuerParameters(issuerParameters).withX509CertificateProperties(x509Properties);

    String vaultUri = getVaultUri();
    String certificateName = "createTestJavaPkcs12";
    CertificateOperation certificateOperation = keyVaultClient
            .createCertificate(new CreateCertificateRequest.Builder(vaultUri, certificateName)
                    .withPolicy(certificatePolicy).build());

    Assert.assertNotNull(certificateOperation);
    Assert.assertTrue(certificateOperation.status().equalsIgnoreCase(STATUS_IN_PROGRESS));

    CertificateBundle certificateBundle = pollOnCertificateOperation(certificateOperation);
    validateCertificateBundle(certificateBundle, certificatePolicy);

    // Load the CER part into X509Certificate object
    X509Certificate x509Certificate = loadCerToX509Certificate(certificateBundle);

    Assert.assertTrue(x509Certificate.getSubjectX500Principal().getName().equals(subjectName));
    Assert.assertTrue(x509Certificate.getIssuerX500Principal().getName().equals(subjectName));

    // Retrieve the secret backing the certificate
    SecretIdentifier secretIdentifier = certificateBundle.secretIdentifier();
    SecretBundle secret = keyVaultClient.getSecret(secretIdentifier.baseIdentifier());
    Assert.assertTrue(secret.managed());

    // Load the secret into a KeyStore
    String secretPassword = "";
    KeyStore keyStore = loadSecretToKeyStore(secret, secretPassword);

    // Validate the certificate and key in the KeyStore
    validateCertificateKeyInKeyStore(keyStore, x509Certificate, secretPassword);

    CertificateBundle deletedCertificateBundle = keyVaultClient.deleteCertificate(getVaultUri(),
            certificateName);
    Assert.assertNotNull(deletedCertificateBundle);

    try {
        keyVaultClient.getCertificate(deletedCertificateBundle.certificateIdentifier().baseIdentifier());
    } catch (KeyVaultErrorException e) {
        Assert.assertNotNull(e.body().error());
        Assert.assertEquals("CertificateNotFound", e.body().error().code());
    }
}

From source file:com.microsoft.azure.keyvault.test.CertificateOperationsTest.java

private void validateCertificateKeyInKeyStore(KeyStore keyStore, X509Certificate x509Certificate,
        String secretPassword) throws KeyStoreException, UnrecoverableKeyException, NoSuchAlgorithmException,
        InvalidKeyException, NoSuchPaddingException, IllegalBlockSizeException, BadPaddingException {
    String defaultAlias = Collections.list(keyStore.aliases()).get(0);
    X509Certificate secretCertificate = (X509Certificate) keyStore.getCertificate(defaultAlias);
    Assert.assertNotNull(secretCertificate);
    Assert.assertTrue(secretCertificate.getSubjectX500Principal().getName()
            .equals(x509Certificate.getSubjectX500Principal().getName()));
    Assert.assertTrue(secretCertificate.getIssuerX500Principal().getName()
            .equals(x509Certificate.getIssuerX500Principal().getName()));
    Assert.assertTrue(secretCertificate.getSerialNumber().equals(x509Certificate.getSerialNumber()));

    // Validate the key in the KeyStore
    Key secretKey = keyStore.getKey(defaultAlias, secretPassword.toCharArray());
    Assert.assertNotNull(secretKey);//from   w  w  w.ja v  a2  s.  co  m
    Assert.assertTrue(secretKey instanceof PrivateKey);
    PrivateKey secretPrivateKey = (PrivateKey) secretKey;

    // Create a KeyPair with the private key from the KeyStore and public
    // key from the certificate to verify they match
    KeyPair keyPair = new KeyPair(secretCertificate.getPublicKey(), secretPrivateKey);
    Assert.assertNotNull(keyPair);
    verifyRSAKeyPair(keyPair);
}

From source file:org.apache.jmeter.protocol.http.proxy.JMeterProxyControl.java

public String[] getCertificateDetails() {
    if (isDynamicMode()) {
        try {/*from  ww w  .ja  va 2  s.c  o  m*/
            X509Certificate caCert = (X509Certificate) sslKeyStore
                    .getCertificate(KeyToolUtils.getRootCAalias());
            if (caCert == null) {
                return new String[] { "Could not find certificate" };
            }
            return new String[] { caCert.getSubjectX500Principal().toString(),
                    "Fingerprint(SHA1): "
                            + JOrphanUtils.baToHexString(DigestUtils.sha1(caCert.getEncoded()), ' '),
                    "Created: " + caCert.getNotBefore().toString() };
        } catch (GeneralSecurityException e) {
            LOG.error("Problem reading root CA from keystore", e);
            return new String[] { "Problem with root certificate", e.getMessage() };
        }
    }
    return null; // should not happen
}

From source file:org.zuinnote.hadoop.office.format.common.parser.msexcel.MSExcelLowFootprintParser.java

/**
 * Processes a OPCPackage (new Excel format, .xlsx) in Streaming Mode
 * /*from   w w  w .  ja v a  2s  . c  o m*/
 * @param pkg
 * @throws OpenXML4JException 
 * @throws IOException 
 */
private void processOPCPackage(OPCPackage pkg) throws FormatNotUnderstoodException {
    LOG.debug("Processing OPCPackage in low footprint mode");
    // check if signature should be verified
    if (this.hocr.getVerifySignature()) {
        LOG.info("Verifying signature of document");
        SignatureConfig sic = new SignatureConfig();
        sic.setOpcPackage(pkg);
        SignatureInfo si = new SignatureInfo();
        si.setSignatureConfig(sic);
        if (!si.verifySignature()) {
            throw new FormatNotUnderstoodException(
                    "Cannot verify signature of OOXML (.xlsx) file: " + this.hocr.getFileName());
        } else {
            LOG.info("Successfully verifed first part signature of OXXML (.xlsx) file: "
                    + this.hocr.getFileName());
        }
        Iterator<SignaturePart> spIter = si.getSignatureParts().iterator();
        while (spIter.hasNext()) {
            SignaturePart currentSP = spIter.next();
            if (!(currentSP.validate())) {
                throw new FormatNotUnderstoodException(
                        "Could not validate all signature parts for file: " + this.hocr.getFileName());
            } else {
                X509Certificate currentCertificate = currentSP.getSigner();
                try {
                    if ((this.hocr.getX509CertificateChain().size() > 0) && (!CertificateChainVerificationUtil
                            .verifyCertificateChain(currentCertificate, this.hocr.getX509CertificateChain()))) {
                        throw new FormatNotUnderstoodException(
                                "Could not validate signature part for principal \""
                                        + currentCertificate.getSubjectX500Principal().getName() + "\" : "
                                        + this.hocr.getFileName());
                    }
                } catch (CertificateException | NoSuchAlgorithmException | NoSuchProviderException
                        | InvalidAlgorithmParameterException e) {
                    LOG.error("Could not validate signature part for principal \""
                            + currentCertificate.getSubjectX500Principal().getName() + "\" : "
                            + this.hocr.getFileName(), e);
                    throw new FormatNotUnderstoodException("Could not validate signature part for principal \""
                            + currentCertificate.getSubjectX500Principal().getName() + "\" : "
                            + this.hocr.getFileName());

                }
            }
        }
        LOG.info("Successfully verifed all signatures of OXXML (.xlsx) file: " + this.hocr.getFileName());
    }
    // continue in lowfootprint mode
    XSSFReader r;
    try {
        r = new XSSFReader(pkg);
    } catch (IOException | OpenXML4JException e) {
        LOG.error(e);
        throw new FormatNotUnderstoodException("Error cannot parse new Excel file (.xlsx)");
    }
    try {
        // read date format
        InputStream workbookDataXML = r.getWorkbookData();
        WorkbookDocument wd = WorkbookDocument.Factory.parse(workbookDataXML);
        this.isDate1904 = wd.getWorkbook().getWorkbookPr().getDate1904();

        // read shared string tables
        if (HadoopOfficeReadConfiguration.OPTION_LOWFOOTPRINT_PARSER_SAX
                .equalsIgnoreCase(this.hocr.getLowFootprintParser())) {
            this.pushSST = new ReadOnlySharedStringsTable(pkg);
        } else if (HadoopOfficeReadConfiguration.OPTION_LOWFOOTPRINT_PARSER_STAX
                .equalsIgnoreCase(this.hocr.getLowFootprintParser())) {
            List<PackagePart> pkgParts = pkg
                    .getPartsByContentType(XSSFRelation.SHARED_STRINGS.getContentType());
            if (pkgParts.size() > 0) {
                this.pullSST = new EncryptedCachedDiskStringsTable(pkgParts.get(0), this.hocr.getSstCacheSize(),
                        this.hocr.getCompressSST(), this.ca, this.cm);
            }
        }
        this.styles = r.getStylesTable();
        XSSFReader.SheetIterator iter = (XSSFReader.SheetIterator) r.getSheetsData();
        int sheetNumber = 0;
        while (iter.hasNext()) {

            // check if we need to parse this sheet?
            boolean parse = false;
            if (this.sheets != null) {
                for (int i = 0; i < this.sheets.length; i++) {
                    if (iter.getSheetName().equals(this.sheets[i])) {
                        parse = true;
                        break;
                    }
                }
            } else {
                parse = true;
            }
            // sheet is supposed to be parsed
            if (parse) {

                InputStream rawSheetInputStream = iter.next();
                this.sheetNameList.add(iter.getSheetName());
                InputSource rawSheetInputSource = new InputSource(rawSheetInputStream);
                if (HadoopOfficeReadConfiguration.OPTION_LOWFOOTPRINT_PARSER_SAX
                        .equalsIgnoreCase(this.hocr.getLowFootprintParser())) {
                    this.event = true;
                    LOG.info("Using SAX parser for low footprint Excel parsing");
                    XMLReader sheetParser = SAXHelper.newXMLReader();
                    XSSFEventParser xssfp = new XSSFEventParser(sheetNumber, iter.getSheetName(),
                            this.spreadSheetCellDAOCache);

                    ContentHandler handler = new XSSFSheetXMLHandler(this.styles, iter.getSheetComments(),
                            this.pushSST, xssfp, this.useDataFormatter, false);
                    sheetParser.setContentHandler(handler);
                    sheetParser.parse(rawSheetInputSource);
                    sheetNumber++;
                } else if (HadoopOfficeReadConfiguration.OPTION_LOWFOOTPRINT_PARSER_STAX
                        .equalsIgnoreCase(this.hocr.getLowFootprintParser())) {
                    LOG.info("Using STAX parser for low footprint Excel parsing");
                    this.event = false;
                    this.pullSheetInputList.add(rawSheetInputStream);
                    this.pullSheetNameList.add(iter.getSheetName());
                    // make shared string table available

                    // everything else is in the getNext method
                } else {
                    LOG.error("Unknown XML parser configured for low footprint mode: \""
                            + this.hocr.getLowFootprintParser() + "\"");
                    throw new FormatNotUnderstoodException(
                            "Unknown XML parser configured for low footprint mode: \""
                                    + this.hocr.getLowFootprintParser() + "\"");
                }

            }
        }
    } catch (InvalidFormatException | IOException e) {
        LOG.error(e);
        throw new FormatNotUnderstoodException("Error cannot parse new Excel file (.xlsx)");
    } catch (SAXException e) {
        LOG.error(e);
        throw new FormatNotUnderstoodException(
                "Parsing Excel sheet in .xlsx format failed. Cannot read XML content");
    } catch (ParserConfigurationException e) {
        LOG.error(e);
        throw new FormatNotUnderstoodException(
                "Parsing Excel sheet in .xlsx format failed. Cannot read XML content");
    } catch (XmlException e) {
        LOG.error(e);
        throw new FormatNotUnderstoodException(
                "Parsing Excel sheet in .xlsx format failed. Cannot read XML content");
    }
    // check skipping of additional lines
    for (int i = 0; i < this.hocr.getSkipLines(); i++) {
        this.getNext();
    }
    // check header
    if (this.hocr.getReadHeader()) {

        LOG.debug("Reading header...");
        Object[] firstRow = this.getNext();
        if (firstRow != null) {
            this.header = new String[firstRow.length];
            for (int i = 0; i < firstRow.length; i++) {
                if ((firstRow[i] != null)
                        && (!"".equals(((SpreadSheetCellDAO) firstRow[i]).getFormattedValue()))) {
                    this.header[i] = ((SpreadSheetCellDAO) firstRow[i]).getFormattedValue();
                }
            }
            this.header = MSExcelParser.sanitizeHeaders(this.header, this.hocr.getColumnNameRegex(),
                    this.hocr.getColumnNameReplace());
        } else {
            this.header = new String[0];
        }
    }
    this.headerParsed = true;

}

From source file:org.apache.ranger.biz.AssetMgr.java

public String getLatestRepoPolicy(VXAsset xAsset, List<VXResource> xResourceList, Long updatedTime,
        X509Certificate[] certchain, boolean httpEnabled, String epoch, String ipAddress, boolean isSecure,
        String count, String agentId) {
    if (xAsset == null) {
        logger.error("Requested repository not found");
        throw restErrorUtil.createRESTException("No Data Found.", MessageEnums.DATA_NOT_FOUND);
    }//  ww  w.jav  a  2  s .  c o m
    if (xResourceList == null) {
        logger.error("ResourceList is found");
        throw restErrorUtil.createRESTException("No Data Found.", MessageEnums.DATA_NOT_FOUND);
    }
    if (xAsset.getActiveStatus() == RangerCommonEnums.ACT_STATUS_DISABLED) {
        logger.error("Requested repository is disabled");
        throw restErrorUtil.createRESTException("Unauthorized access.", MessageEnums.OPER_NO_EXPORT);
    }

    HashMap<String, Object> updatedRepo = new HashMap<String, Object>();
    updatedRepo.put("repository_name", xAsset.getName());

    XXPolicyExportAudit policyExportAudit = new XXPolicyExportAudit();
    policyExportAudit.setRepositoryName(xAsset.getName());

    if (agentId != null && !agentId.isEmpty()) {
        policyExportAudit.setAgentId(agentId);
    }

    policyExportAudit.setClientIP(ipAddress);

    if (epoch != null && !epoch.trim().isEmpty() && !epoch.equalsIgnoreCase("null")) {
        policyExportAudit.setRequestedEpoch(Long.parseLong(epoch));
    } else {
        policyExportAudit.setRequestedEpoch(0L);
    }

    if (!httpEnabled) {
        if (!isSecure) {
            policyExportAudit.setHttpRetCode(HttpServletResponse.SC_BAD_REQUEST);
            createPolicyAudit(policyExportAudit);

            throw restErrorUtil.createRESTException("Unauthorized access -" + " only https allowed",
                    MessageEnums.OPER_NOT_ALLOWED_FOR_ENTITY);
        }

        if (certchain == null || certchain.length == 0) {

            policyExportAudit.setHttpRetCode(HttpServletResponse.SC_BAD_REQUEST);
            createPolicyAudit(policyExportAudit);

            throw restErrorUtil.createRESTException(
                    "Unauthorized access -" + " unable to get client certificate",
                    MessageEnums.OPER_NOT_ALLOWED_FOR_ENTITY);
        }
    }

    Long policyCount = restErrorUtil.parseLong(count, "Invalid value for " + "policyCount",
            MessageEnums.INVALID_INPUT_DATA, null, "policyCount");

    String commonName = null;

    if (certchain != null) {
        X509Certificate clientCert = certchain[0];
        String dn = clientCert.getSubjectX500Principal().getName();

        try {
            LdapName ln = new LdapName(dn);
            for (Rdn rdn : ln.getRdns()) {
                if (rdn.getType().equalsIgnoreCase("CN")) {
                    commonName = rdn.getValue() + "";
                    break;
                }
            }
            if (commonName == null) {
                policyExportAudit.setHttpRetCode(HttpServletResponse.SC_BAD_REQUEST);
                createPolicyAudit(policyExportAudit);

                throw restErrorUtil.createRESTException(
                        "Unauthorized access - Unable to find Common Name from [" + dn + "]",
                        MessageEnums.OPER_NOT_ALLOWED_FOR_ENTITY);
            }
        } catch (InvalidNameException e) {
            policyExportAudit.setHttpRetCode(HttpServletResponse.SC_BAD_REQUEST);
            createPolicyAudit(policyExportAudit);

            logger.error("Invalid Common Name.", e);
            throw restErrorUtil.createRESTException("Unauthorized access - Invalid Common Name",
                    MessageEnums.OPER_NOT_ALLOWED_FOR_ENTITY);
        }
    }

    if (policyCount == null) {
        policyCount = 0L;
    }

    if (commonName != null) {
        String config = xAsset.getConfig();
        Map<String, String> configMap = jsonUtil.jsonToMap(config);
        String cnFromConfig = configMap.get("commonNameForCertificate");

        if (cnFromConfig == null || !commonName.equalsIgnoreCase(cnFromConfig)) {
            policyExportAudit.setHttpRetCode(HttpServletResponse.SC_BAD_REQUEST);
            createPolicyAudit(policyExportAudit);

            throw restErrorUtil.createRESTException(
                    "Unauthorized access. expected [" + cnFromConfig + "], found [" + commonName + "]",
                    MessageEnums.OPER_NOT_ALLOWED_FOR_ENTITY);
        }
    }

    long epochTime = epoch != null ? Long.parseLong(epoch) : 0;

    if (epochTime == updatedTime) {
        int resourceListSz = xResourceList.size();

        if (policyCount == resourceListSz) {
            policyExportAudit.setHttpRetCode(HttpServletResponse.SC_NOT_MODIFIED);
            createPolicyAudit(policyExportAudit);

            throw restErrorUtil.createRESTException(HttpServletResponse.SC_NOT_MODIFIED,
                    "No change since last update", false);
        }
    }

    List<HashMap<String, Object>> resourceList = new ArrayList<HashMap<String, Object>>();

    // HDFS Repository
    if (xAsset.getAssetType() == AppConstants.ASSET_HDFS) {
        for (VXResource xResource : xResourceList) {
            HashMap<String, Object> resourceMap = new HashMap<String, Object>();
            resourceMap.put("id", xResource.getId());
            resourceMap.put("resource", xResource.getName());
            resourceMap.put("isRecursive", getBooleanValue(xResource.getIsRecursive()));
            resourceMap.put("policyStatus",
                    RangerCommonEnums.getLabelFor_ActiveStatus(xResource.getResourceStatus()));
            // resourceMap.put("isEncrypt",
            // AKAConstants.getLabelFor_BooleanValue(xResource.getIsEncrypt()));
            populatePermMap(xResource, resourceMap, AppConstants.ASSET_HDFS);
            List<VXAuditMap> xAuditMaps = xResource.getAuditList();
            if (xAuditMaps.size() != 0) {
                resourceMap.put("audit", 1);
            } else {
                resourceMap.put("audit", 0);
            }

            resourceList.add(resourceMap);
        }
    } else if (xAsset.getAssetType() == AppConstants.ASSET_HIVE) {
        for (VXResource xResource : xResourceList) {
            HashMap<String, Object> resourceMap = new HashMap<String, Object>();
            resourceMap.put("id", xResource.getId());
            resourceMap.put("database_name", xResource.getDatabases());
            resourceMap.put("policyStatus",
                    RangerCommonEnums.getLabelFor_ActiveStatus(xResource.getResourceStatus()));
            resourceMap.put("tablePolicyType", AppConstants.getLabelFor_PolicyType(xResource.getTableType()));
            resourceMap.put("columnPolicyType", AppConstants.getLabelFor_PolicyType(xResource.getColumnType()));
            int resourceType = xResource.getResourceType();
            if (resourceType == AppConstants.RESOURCE_UDF) {
                resourceMap.put("udf_name", xResource.getUdfs());
            } else if (resourceType == AppConstants.RESOURCE_COLUMN) {
                resourceMap.put("table_name", xResource.getTables());
                resourceMap.put("column_name", xResource.getColumns());
            } else if (resourceType == AppConstants.RESOURCE_TABLE) {
                resourceMap.put("table_name", xResource.getTables());
            }

            populatePermMap(xResource, resourceMap, AppConstants.ASSET_HIVE);

            List<VXAuditMap> xAuditMaps = xResource.getAuditList();
            if (xAuditMaps.size() != 0) {
                resourceMap.put("audit", 1);
            } else {
                resourceMap.put("audit", 0);
            }
            resourceList.add(resourceMap);
        }
    }

    else if (xAsset.getAssetType() == AppConstants.ASSET_HBASE) {
        for (VXResource xResource : xResourceList) {
            HashMap<String, Object> resourceMap = new HashMap<String, Object>();

            resourceMap.put("id", xResource.getId());
            resourceMap.put("table_name", xResource.getTables());
            resourceMap.put("column_name", xResource.getColumns());
            resourceMap.put("column_families", xResource.getColumnFamilies());
            resourceMap.put("policyStatus",
                    RangerCommonEnums.getLabelFor_ActiveStatus(xResource.getResourceStatus()));
            if (xResource.getIsEncrypt() == 1) {
                resourceMap.put("encrypt", 1);
            } else {
                resourceMap.put("encrypt", 0);
            }
            // resourceMap.put("isEncrypt",
            // AKAConstants.getLabelFor_BooleanValue(xResource.getIsEncrypt()));
            populatePermMap(xResource, resourceMap, AppConstants.ASSET_HBASE);
            List<VXAuditMap> xAuditMaps = xResource.getAuditList();
            if (xAuditMaps.size() != 0) {
                resourceMap.put("audit", 1);
            } else {
                resourceMap.put("audit", 0);
            }
            resourceList.add(resourceMap);
        }
    } else if (xAsset.getAssetType() == AppConstants.ASSET_KNOX) {
        for (VXResource xResource : xResourceList) {
            HashMap<String, Object> resourceMap = new HashMap<String, Object>();

            resourceMap.put("id", xResource.getId());
            resourceMap.put("topology_name", xResource.getTopologies());
            resourceMap.put("service_name", xResource.getServices());
            resourceMap.put("policyStatus",
                    RangerCommonEnums.getLabelFor_ActiveStatus(xResource.getResourceStatus()));
            if (xResource.getIsEncrypt() == 1) {
                resourceMap.put("encrypt", 1);
            } else {
                resourceMap.put("encrypt", 0);
            }
            // resourceMap.put("isEncrypt",
            // AKAConstants.getLabelFor_BooleanValue(xResource.getIsEncrypt()));
            populatePermMap(xResource, resourceMap, AppConstants.ASSET_KNOX);
            List<VXAuditMap> xAuditMaps = xResource.getAuditList();
            if (xAuditMaps.size() != 0) {
                resourceMap.put("audit", 1);
            } else {
                resourceMap.put("audit", 0);
            }
            resourceList.add(resourceMap);
        }

    } else if (xAsset.getAssetType() == AppConstants.ASSET_STORM) {
        for (VXResource xResource : xResourceList) {
            HashMap<String, Object> resourceMap = new HashMap<String, Object>();

            resourceMap.put("id", xResource.getId());
            resourceMap.put("topology_name", xResource.getTopologies());
            resourceMap.put("policyStatus",
                    RangerCommonEnums.getLabelFor_ActiveStatus(xResource.getResourceStatus()));
            if (xResource.getIsEncrypt() == 1) {
                resourceMap.put("encrypt", 1);
            } else {
                resourceMap.put("encrypt", 0);
            }
            populatePermMap(xResource, resourceMap, AppConstants.ASSET_STORM);
            List<VXAuditMap> xAuditMaps = xResource.getAuditList();
            if (xAuditMaps.size() != 0) {
                resourceMap.put("audit", 1);
            } else {
                resourceMap.put("audit", 0);
            }
            resourceList.add(resourceMap);
        }
    } else {
        policyExportAudit.setHttpRetCode(HttpServletResponse.SC_BAD_REQUEST);
        createPolicyAudit(policyExportAudit);
        throw restErrorUtil.createRESTException("The operation isn't yet supported for the repository",
                MessageEnums.OPER_NOT_ALLOWED_FOR_ENTITY);
    }

    policyCount = Long.valueOf(resourceList.size());
    updatedRepo.put("last_updated", updatedTime);
    updatedRepo.put("policyCount", policyCount);
    updatedRepo.put("acl", resourceList);

    String updatedPolicyStr = jsonUtil.readMapToString(updatedRepo);

    //      File file = null;
    //      try {
    //         file = jsonUtil.writeMapToFile(updatedRepo, repository);
    //      } catch (JsonGenerationException e) {
    //         logger.error("Error exporting policies for repository : "
    //               + repository, e);
    //      } catch (JsonMappingException e) {
    //         logger.error("Error exporting policies for repository : "
    //               + repository, e);
    //      } catch (IOException e) {
    //         logger.error("Error exporting policies for repository : "
    //               + repository, e);
    //      }

    policyExportAudit.setHttpRetCode(HttpServletResponse.SC_OK);
    createPolicyAudit(policyExportAudit);

    return updatedPolicyStr;
}

From source file:com.otterca.common.crypto.acceptance.X509CertificateBuilderAcceptanceTest.java

/**
 * Test search criteria. There's no easy way to check the subject key id and
 * authority key id - we can get the extension's bytes but still need to
 * parse them./*w ww . j  a v a2s  .  c  o  m*/
 */
@Test
public void testTestSearchCriteria() throws GeneralSecurityException {

    // create issuer certificate
    populate(builder);
    builder.setSubject(ISSUER_NAME);
    builder.setIssuer(ISSUER_NAME);
    builder.setBasicConstraints(true);
    X509Certificate issuer = builder.build(issuerKeyPair.getPrivate());

    builder.reset();

    // create subject certificate
    populate(builder);
    builder.setIssuer(issuer);
    X509Certificate cert = builder.build(keyPair.getPrivate());

    assertEquals(certUtil.getFingerprint(cert), toHex(DigestUtils.sha(cert.getEncoded())));
    assertEquals(certUtil.getCertificateHash(cert), rfc4387(cert.getEncoded()));
    assertEquals(certUtil.getIHash(cert), rfc4387(cert.getIssuerX500Principal().getEncoded()));
    assertEquals(certUtil.getSHash(cert), rfc4387(cert.getSubjectX500Principal().getEncoded()));
}

From source file:org.cesecore.certificates.ocsp.CanLogCache.java

private BasicOCSPRespGenerator createOcspResponseGenerator(OCSPReq req, X509Certificate respondercert,
        int respIdType) throws OCSPException, NotSupportedException {
    if (null == req) {
        throw new IllegalArgumentException();
    }//from w ww.  j  a v  a 2 s.  c o m
    BasicOCSPRespGenerator res = null;
    if (respIdType == OcspConfiguration.RESPONDERIDTYPE_NAME) {
        res = new BasicOCSPRespGenerator(new RespID(respondercert.getSubjectX500Principal()));
    } else {
        res = new BasicOCSPRespGenerator(respondercert.getPublicKey());
    }
    X509Extensions reqexts = req.getRequestExtensions();
    if (reqexts != null) {
        X509Extension ext = reqexts.getExtension(OCSPObjectIdentifiers.id_pkix_ocsp_response);
        if (null != ext) {
            // log.debug("Found extension AcceptableResponses");
            ASN1OctetString oct = ext.getValue();
            try {
                ASN1Sequence seq = ASN1Sequence.getInstance(
                        new ASN1InputStream(new ByteArrayInputStream(oct.getOctets())).readObject());
                @SuppressWarnings("unchecked")
                Enumeration<DERObjectIdentifier> en = seq.getObjects();
                boolean supportsResponseType = false;
                while (en.hasMoreElements()) {
                    DERObjectIdentifier oid = en.nextElement();
                    // log.debug("Found oid: "+oid.getId());
                    if (oid.equals(OCSPObjectIdentifiers.id_pkix_ocsp_basic)) {
                        // This is the response type we support, so we are happy! Break the loop.
                        supportsResponseType = true;
                        log.debug("Response type supported: " + oid.getId());
                        continue;
                    }
                }
                if (!supportsResponseType) {
                    throw new NotSupportedException(
                            "Required response type not supported, this responder only supports id-pkix-ocsp-basic.");
                }
            } catch (IOException e) {
            }
        }
    }
    return res;
}

From source file:be.fedict.eid.tsl.TrustServiceList.java

public void sign(PrivateKey privateKey, X509Certificate certificate) throws IOException {
    LOG.debug("sign with: " + certificate.getSubjectX500Principal());
    if (null == this.tslDocument) {
        /*/*  w w  w  .ja v a  2 s.  c  o m*/
         * Marshall to DOM.
         */
        try {
            marshall();
        } catch (Exception e) {
            throw new IOException("marshaller error: " + e.getMessage(), e);
        }
    }

    /*
     * Remove existing XML signature from DOM.
     */
    Node signatureNode = getSignatureNode();
    if (null != signatureNode) {
        signatureNode.getParentNode().removeChild(signatureNode);
    }

    String tslId = this.trustStatusList.getId();

    /*
     * Create new XML signature.
     */
    try {
        xmlSign(privateKey, certificate, tslId);
    } catch (Exception e) {
        throw new IOException("XML sign error: " + e.getMessage(), e);
    }
    setChanged();
}