Example usage for java.security.cert X509Certificate getSigAlgName

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

Introduction

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

Prototype

public abstract String getSigAlgName();

Source Link

Document

Gets the signature algorithm name for the certificate signature algorithm.

Usage

From source file:org.cesecore.certificates.util.AlgorithmTools.java

/**
 * Simple methods that returns the signature algorithm value from the certificate. Not usable for setting signature algorithms names in EJBCA,
 * only for human presentation.//from   w w  w.j  av a2  s .  c  o  m
 * 
 * @return Signature algorithm name from the certificate as a human readable string, for example SHA1WithRSA.
 */
public static String getCertSignatureAlgorithmNameAsString(Certificate cert) {
    String certSignatureAlgorithm = null;
    if (cert instanceof X509Certificate) {
        X509Certificate x509cert = (X509Certificate) cert;
        certSignatureAlgorithm = x509cert.getSigAlgName();
        if (log.isDebugEnabled()) {
            log.debug("certSignatureAlgorithm is: " + certSignatureAlgorithm);
        }
    } else if (StringUtils.equals(cert.getType(), "CVC")) {
        CardVerifiableCertificate cvccert = (CardVerifiableCertificate) cert;
        CVCPublicKey cvcpk;
        try {
            cvcpk = cvccert.getCVCertificate().getCertificateBody().getPublicKey();
            OIDField oid = cvcpk.getObjectIdentifier();
            certSignatureAlgorithm = AlgorithmUtil.getAlgorithmName(oid);
        } catch (NoSuchFieldException e) {
            log.error("NoSuchFieldException: ", e);
        }
    }
    // Try to make it easier to display some signature algorithms that cert.getSigAlgName() does not have a good string for.
    if (certSignatureAlgorithm.equalsIgnoreCase("1.2.840.113549.1.1.10")) {
        // Figure out if it is SHA1 or SHA256
        // If we got this value we should have a x509 cert
        if (cert instanceof X509Certificate) {
            X509Certificate x509cert = (X509Certificate) cert;
            certSignatureAlgorithm = x509cert.getSigAlgName();
            byte[] params = x509cert.getSigAlgParams();
            if ((params != null) && (params.length == 2)) {
                certSignatureAlgorithm = AlgorithmConstants.SIGALG_SHA1_WITH_RSA_AND_MGF1;
            } else {
                certSignatureAlgorithm = AlgorithmConstants.SIGALG_SHA256_WITH_RSA_AND_MGF1;
            }
        }
    }
    // SHA256WithECDSA does not work to be translated in JDK5.
    if (certSignatureAlgorithm.equalsIgnoreCase("1.2.840.10045.4.3.2")) {
        certSignatureAlgorithm = AlgorithmConstants.SIGALG_SHA256_WITH_ECDSA;
    }
    // GOST3410
    if (isGost3410Enabled()
            && certSignatureAlgorithm.equalsIgnoreCase(CesecoreConfiguration.getOidGost3410())) {
        certSignatureAlgorithm = AlgorithmConstants.SIGALG_GOST3411_WITH_ECGOST3410;
    }
    // DSTU4145
    if (isDstu4145Enabled()
            && certSignatureAlgorithm.startsWith(CesecoreConfiguration.getOidDstu4145() + ".")) {
        certSignatureAlgorithm = AlgorithmConstants.SIGALG_GOST3411_WITH_DSTU4145;
    }
    return certSignatureAlgorithm;
}

From source file:net.sf.keystore_explorer.crypto.x509.X509CertUtil.java

/**
 * For a given X.509 certificate get the algorithm of its signature. Useful
 * as the JCE may return an unfriendly name. This method converts known
 * "unfriendly names" to friendly names.
 *
 * @param cert//ww w  .  j a  v a 2s.  c  o m
 *            The certificate
 * @return The algorithm
 */
public static String getCertificateSignatureAlgorithm(X509Certificate cert) {
    // Unfriendly JCE sig names may be actual JCE names or OIDs
    String algorithm = cert.getSigAlgName();

    SignatureType type = SignatureType.resolveJce(algorithm);

    if (type != null) {
        algorithm = type.friendly();
    } else {
        type = SignatureType.resolveOid(algorithm);

        if (type != null) {
            algorithm = type.friendly();
        }
    }

    return algorithm;
}

From source file:KeystoreGeneratorTest.java

@Test
public void test() throws Exception {
    File dir = null;/*  w  w w  . j  ava  2s . co m*/
    FileInputStream fis = null;
    try {
        dir = Files.createTempDir();
        File keystoreFile = new File(dir, KEYSTORE_NAME);

        String config = GSON.toJson(ImmutableMap.builder().put("password", KEYSTORE_PASSWORD)
                .put("entries", ImmutableList.builder()
                        .add(ImmutableMap.builder().put("label", "rsatest1").put("algorithm", "SHA256WithRSA")
                                .put("keyAlgorithm", "RSA").put("rsaKeySize", "2048").build())
                        .add(ImmutableMap.builder().put("label", "ecdsatest1")
                                .put("algorithm", "SHA256WithECDSA").put("keyAlgorithm", "ECDSA")
                                .put("ecdsaNamedCurve", "secp192r1").build())
                        .add(ImmutableMap.builder().put("label", "ecdsatest2")
                                .put("algorithm", "SHA256WithECDSA").put("keyAlgorithm", "ECDSA")
                                .put("ecdsaNamedCurve", "secp256r1").build())
                        .build())
                .build());
        // generate
        KeyStore store = new KeystoreGenerator().generate(GSON.fromJson(config, KeystoreConfig.class));
        // write to disk
        try (FileOutputStream out = new FileOutputStream(keystoreFile)) {
            store.store(out, KEYSTORE_PASSWORD.toCharArray());
        }
        // load
        fis = new FileInputStream(keystoreFile);
        KeyStore ks = KeyStore.getInstance("PKCS12", "SunJSSE");
        ks.load(fis, KEYSTORE_PASSWORD.toCharArray());
        Enumeration<String> aliases = ks.aliases();
        while (aliases.hasMoreElements()) {
            String al = aliases.nextElement();
            System.out.println("Label: [" + al + "]");
            X509Certificate cert = (X509Certificate) ks.getCertificate(al);
            System.out.println("  Algorithm: [" + cert.getSigAlgName() + "]");
            PublicKey key = cert.getPublicKey();
            if (key instanceof ECKey) {
                ECKey eckey = (ECKey) key;
                ECParameterSpec spec = eckey.getParams();
                System.out.println("  EC spec: [" + spec + "]");
            }
        }
    } finally {
        closeQuietly(fis);
        FileUtils.deleteDirectory(dir);
    }
}

From source file:com.thoughtworks.go.security.AuthSSLX509TrustManagerFactory.java

private void logKeyStore(KeyStore store) throws KeyStoreException {
    Enumeration aliases = store.aliases();
    while (aliases.hasMoreElements()) {
        String alias = (String) aliases.nextElement();
        LOG.debug("Trusted certificate '" + alias + "':");
        Certificate trustedcert = store.getCertificate(alias);
        if (trustedcert != null && trustedcert instanceof X509Certificate) {
            X509Certificate cert = (X509Certificate) trustedcert;
            LOG.trace("  Subject DN: " + cert.getSubjectDN());
            LOG.trace("  Signature Algorithm: " + cert.getSigAlgName());
            LOG.trace("  Valid from: " + cert.getNotBefore());
            LOG.trace("  Valid until: " + cert.getNotAfter());
            LOG.trace("  Issuer: " + cert.getIssuerDN());
        }/*w w w .  j a  va  2  s.  c om*/
    }
}

From source file:com.xwiki.authentication.sts.STSTokenValidator.java

/**
  * validateToken(SignableSAMLObject samlToken)
  * Validates Token from SAMLlObject - returns boolen
  * Validates Token - exitracting sertificate from samlToken.
  * And validates it. Returning true or false according on validation results.
  * @param samlToken SignableSAMLObject/*from ww  w . j  a  va 2  s. c om*/
  * @return boolean valid => true, not valid => false
  */
private static boolean validateToken(SignableSAMLObject samlToken)
        throws SecurityException, ValidationException, ConfigurationException, UnmarshallingException,
        CertificateException, KeyException {

    // Validate XML structure
    samlToken.validate(true);

    Signature signature = samlToken.getSignature();
    X509Certificate certificate = certFromToken(samlToken);

    // Certificate data
    log.debug("certificate issuerDN: " + certificate.getIssuerDN());
    log.debug("certificate issuerUniqueID: " + certificate.getIssuerUniqueID());
    log.debug("certificate issuerX500Principal: " + certificate.getIssuerX500Principal());
    log.debug("certificate notBefore: " + certificate.getNotBefore());
    log.debug("certificate notAfter: " + certificate.getNotAfter());
    log.debug("certificate serialNumber: " + certificate.getSerialNumber());
    log.debug("certificate sigAlgName: " + certificate.getSigAlgName());
    log.debug("certificate sigAlgOID: " + certificate.getSigAlgOID());
    log.debug("certificate signature: " + new String(certificate.getSignature()));
    log.debug("certificate issuerX500Principal: " + certificate.getIssuerX500Principal().toString());
    log.debug("certificate publicKey: " + certificate.getPublicKey());
    log.debug("certificate subjectDN: " + certificate.getSubjectDN());
    log.debug("certificate sigAlgOID: " + certificate.getSigAlgOID());
    log.debug("certificate version: " + certificate.getVersion());

    BasicX509Credential cred = new BasicX509Credential();
    cred.setEntityCertificate(certificate);

    // Credential data
    cred.setEntityId(entityId);
    log.debug("cred entityId: " + cred.getEntityId());
    log.debug("cred usageType: " + cred.getUsageType());
    log.debug("cred credentalContextSet: " + cred.getCredentalContextSet());
    log.debug("cred hashCode: " + cred.hashCode());
    log.debug("cred privateKey: " + cred.getPrivateKey());
    log.debug("cred publicKey: " + cred.getPublicKey());
    log.debug("cred secretKey: " + cred.getSecretKey());
    log.debug("cred entityCertificateChain: " + cred.getEntityCertificateChain());

    ArrayList<Credential> trustedCredentials = new ArrayList<Credential>();
    trustedCredentials.add(cred);

    CollectionCredentialResolver credResolver = new CollectionCredentialResolver(trustedCredentials);
    KeyInfoCredentialResolver kiResolver = SecurityTestHelper.buildBasicInlineKeyInfoResolver();
    ExplicitKeySignatureTrustEngine engine = new ExplicitKeySignatureTrustEngine(credResolver, kiResolver);

    CriteriaSet criteriaSet = new CriteriaSet();
    criteriaSet.add(new EntityIDCriteria(entityId));

    Base64 decoder = new Base64();
    // In trace mode write certificate in the file
    if (log.isTraceEnabled()) {
        String certEncoded = new String(decoder.encode(certificate.getEncoded()));
        try {
            FileUtils.writeStringToFile(new File("/tmp/Certificate.cer"),
                    "-----BEGIN CERTIFICATE-----\n" + certEncoded + "\n-----END CERTIFICATE-----");
            log.trace("Certificate file was saved in: /tmp/Certificate.cer");
        } catch (IOException e1) {
            log.error(e1);
        }
    }
    return engine.validate(signature, criteriaSet);
}

From source file:com.ab.http.AuthSSLX509TrustManager.java

/***
 * @see javax.net.ssl.X509TrustManager#checkClientTrusted(X509Certificate[],String
 *      authType)//from  w w  w.j  av a  2  s.  c om
 */
public void checkClientTrusted(X509Certificate[] certificates, String authType) throws CertificateException {
    if (certificates != null) {
        for (int c = 0; c < certificates.length; c++) {
            X509Certificate cert = certificates[c];
            Log.i(TAG, "  Client certificate " + (c + 1) + ":");
            Log.i(TAG, "  Subject DN: " + cert.getSubjectDN());
            Log.i(TAG, "  Signature Algorithm: " + cert.getSigAlgName());
            Log.i(TAG, "  Valid from: " + cert.getNotBefore());
            Log.i(TAG, "  Valid until: " + cert.getNotAfter());
            Log.i(TAG, "  Issuer: " + cert.getIssuerDN());
        }
    }
    defaultTrustManager.checkClientTrusted(certificates, authType);
}

From source file:com.ab.http.AuthSSLX509TrustManager.java

/***
 * @see javax.net.ssl.X509TrustManager#checkServerTrusted(X509Certificate[],String
 *      authType)//from  w w  w.  j a  va2  s.co m
 */
public void checkServerTrusted(X509Certificate[] certificates, String authType) throws CertificateException {
    if (certificates != null) {
        for (int c = 0; c < certificates.length; c++) {
            X509Certificate cert = certificates[c];
            Log.i(TAG, "  Server certificate " + (c + 1) + ":");
            Log.i(TAG, "  Subject DN: " + cert.getSubjectDN());
            Log.i(TAG, "  Signature Algorithm: " + cert.getSigAlgName());
            Log.i(TAG, "  Valid from: " + cert.getNotBefore());
            Log.i(TAG, "  Valid until: " + cert.getNotAfter());
            Log.i(TAG, "  Issuer: " + cert.getIssuerDN());
        }
    }
    defaultTrustManager.checkServerTrusted(certificates, authType);
}

From source file:org.openhealthtools.openatna.net.LoggedX509TrustManager.java

/**
 * @see javax.net.ssl.X509TrustManager#checkServerTrusted(X509Certificate[], String)
 *///from   ww w  .  j a  v a 2s  . c om
public void checkServerTrusted(X509Certificate[] certificates, String authType) throws CertificateException {
    if (log.isInfoEnabled() && certificates != null) {
        String certificateChain = "Server Certificate Chain: \n";
        for (int c = 0; c < certificates.length; c++) {
            X509Certificate cert = certificates[c];
            certificateChain += "\n Server certificate " + (c + 1) + ":" + "\n  Subject DN: "
                    + cert.getSubjectDN() + "\n  Signature Algorithm: " + cert.getSigAlgName()
                    + "\n  Valid from: " + cert.getNotBefore() + "\n  Valid until: " + cert.getNotAfter()
                    + "\n  Issuer: " + cert.getIssuerDN();
        }
        log.info(certificateChain);
    }
    // This will throw a CertificateException if it is not trusted.
    try {
        this.defaultTrustManager.checkServerTrusted(certificates, authType);
    } catch (CertificateException e) {
        log.error("Something wrong with the server certificate: (auth type: " + authType + ")", e);
        throw e;
    }
}

From source file:au.edu.monash.merc.capture.util.httpclient.ssl.AuthSSLX509TrustManager.java

/**
 * @see javax.net.ssl.X509TrustManager#checkClientTrusted(X509Certificate[],String authType)
 */// w w w. j  a v a2s.c o m
public void checkClientTrusted(X509Certificate[] certificates, String authType) throws CertificateException {
    if (LOG.isInfoEnabled() && certificates != null) {
        for (int c = 0; c < certificates.length; c++) {
            X509Certificate cert = certificates[c];
            LOG.info(" Client certificate " + (c + 1) + ":");
            LOG.info("  Subject DN: " + cert.getSubjectDN());
            LOG.info("  Signature Algorithm: " + cert.getSigAlgName());
            LOG.info("  Valid from: " + cert.getNotBefore());
            LOG.info("  Valid until: " + cert.getNotAfter());
            LOG.info("  Issuer: " + cert.getIssuerDN());
        }
    }
    defaultTrustManager.checkClientTrusted(certificates, authType);
}

From source file:au.edu.monash.merc.capture.util.httpclient.ssl.AuthSSLX509TrustManager.java

/**
 * @see javax.net.ssl.X509TrustManager#checkServerTrusted(X509Certificate[],String authType)
 *//*from ww w  .ja v  a 2s.  c o m*/
public void checkServerTrusted(X509Certificate[] certificates, String authType) throws CertificateException {
    if (LOG.isInfoEnabled() && certificates != null) {
        for (int c = 0; c < certificates.length; c++) {
            X509Certificate cert = certificates[c];
            LOG.info(" Server certificate " + (c + 1) + ":");
            LOG.info("  Subject DN: " + cert.getSubjectDN());
            LOG.info("  Signature Algorithm: " + cert.getSigAlgName());
            LOG.info("  Valid from: " + cert.getNotBefore());
            LOG.info("  Valid until: " + cert.getNotAfter());
            LOG.info("  Issuer: " + cert.getIssuerDN());
        }
    }
    defaultTrustManager.checkServerTrusted(certificates, authType);
}