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.rhq.enterprise.server.plugins.rhnhosted.RHNSSLCertReader.java

static public void main(String[] args) {
    if (args.length < 1) {
        System.out.println("Please re-run and specify an argument for the location of a RHN SSL Cert.");
        System.exit(0);// w w w.  j  a va2  s .co m
    }
    String path = args[0];
    System.out.println("path is " + path);
    String rawCert = null;
    try {
        rawCert = FileUtils.readFileToString(new File(path));
    } catch (IOException e) {
        e.printStackTrace();
        System.exit(0);
    }
    List<String> certs = RHNSSLCertReader.getCertText(rawCert);
    for (String cert : certs) {
        System.out.println("Parsed SSL Certificate: \n" + cert);
    }

    List<X509Certificate> sslCerts = new ArrayList<X509Certificate>();
    try {
        sslCerts = getSSLCertificates(rawCert);
    } catch (CertificateException e) {
        e.printStackTrace();
        System.exit(0);
    }
    for (X509Certificate c : sslCerts) {
        System.out.println("Cert SigAlgName = " + c.getSigAlgName());
        System.out.println("Cert IssuerDN = " + c.getIssuerDN());
        System.out.println("Cert NotAfter = " + c.getNotAfter());
        System.out.println("Cert NotBefore = " + c.getNotBefore());
        System.out.println("Cert PublicKey = " + c.getPublicKey());
        System.out.println("Cert SubjectDN = " + c.getSubjectDN());
    }
}

From source file:CertificateSigner.java

public static void main(String[] args) {
    String ksname = null; // the keystore name
    String alias = null; // the private key alias
    String inname = null; // the input file name
    String outname = null; // the output file name
    for (int i = 0; i < args.length; i += 2) {
        if (args[i].equals("-keystore"))
            ksname = args[i + 1];//from   w  ww.  j  a v  a2  s .  co  m
        else if (args[i].equals("-alias"))
            alias = args[i + 1];
        else if (args[i].equals("-infile"))
            inname = args[i + 1];
        else if (args[i].equals("-outfile"))
            outname = args[i + 1];
        else
            usage();
    }

    if (ksname == null || alias == null || inname == null || outname == null)
        usage();

    try {
        Console console = System.console();
        if (console == null)
            error("No console");
        char[] password = console.readPassword("Keystore password: ");
        KeyStore store = KeyStore.getInstance("JKS", "SUN");
        InputStream in = new FileInputStream(ksname);
        store.load(in, password);
        Arrays.fill(password, ' ');
        in.close();

        char[] keyPassword = console.readPassword("Key password for %s: ", alias);
        PrivateKey issuerPrivateKey = (PrivateKey) store.getKey(alias, keyPassword);
        Arrays.fill(keyPassword, ' ');

        if (issuerPrivateKey == null)
            error("No such private key");

        in = new FileInputStream(inname);

        CertificateFactory factory = CertificateFactory.getInstance("X.509");

        X509Certificate inCert = (X509Certificate) factory.generateCertificate(in);
        in.close();
        byte[] inCertBytes = inCert.getTBSCertificate();

        X509Certificate issuerCert = (X509Certificate) store.getCertificate(alias);
        Principal issuer = issuerCert.getSubjectDN();
        String issuerSigAlg = issuerCert.getSigAlgName();

        FileOutputStream out = new FileOutputStream(outname);

        X509CertInfo info = new X509CertInfo(inCertBytes);
        info.set(X509CertInfo.ISSUER, new CertificateIssuerName((X500Name) issuer));

        X509CertImpl outCert = new X509CertImpl(info);
        outCert.sign(issuerPrivateKey, issuerSigAlg);
        outCert.derEncode(out);

        out.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:MainClass.java

public static void main(String args[]) throws Exception {
    CertificateFactory cf = CertificateFactory.getInstance("X.509");
    FileInputStream in = new FileInputStream(args[0]);
    java.security.cert.Certificate c = cf.generateCertificate(in);
    in.close();//  w  ww . j  av  a  2  s.c  o m

    X509Certificate t = (X509Certificate) c;
    System.out.println(t.getVersion());
    System.out.println(t.getSerialNumber().toString(16));
    System.out.println(t.getSubjectDN());
    System.out.println(t.getIssuerDN());
    System.out.println(t.getNotBefore());
    System.out.println(t.getNotAfter());
    System.out.println(t.getSigAlgName());
    byte[] sig = t.getSignature();
    System.out.println(new BigInteger(sig).toString(16));
    PublicKey pk = t.getPublicKey();
    byte[] pkenc = pk.getEncoded();
    for (int i = 0; i < pkenc.length; i++) {
        System.out.print(pkenc[i] + ",");
    }
}

From source file:MainClass.java

public static void main(String args[]) throws Exception {
    FileInputStream fr = new FileInputStream("sdo.cer");
    CertificateFactory cf = CertificateFactory.getInstance("X509");
    X509Certificate c = (X509Certificate) cf.generateCertificate(fr);
    System.out.println("\tCertificate for: " + c.getSubjectDN());
    System.out.println("\tCertificate issued by: " + c.getIssuerDN());
    System.out.println("\tThe certificate is valid from " + c.getNotBefore() + " to " + c.getNotAfter());
    System.out.println("\tCertificate SN# " + c.getSerialNumber());
    System.out.println("\tGenerated with " + c.getSigAlgName());
}

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

/**
 * For debuging only.  Prints out keystore certificate chain.
 *
 * @param keystore Keystore to print out.
 * @throws KeyStoreException If the keystore is broken.
 *//*w w  w .j  a  v a  2  s  .  co m*/
public static void printTrustCerts(KeyStore keystore) throws KeyStoreException {
    Enumeration<String> aliases = keystore.aliases();
    while (aliases.hasMoreElements()) {
        String alias = aliases.nextElement();
        String message = "Trusted certificate '" + alias + "':";
        Certificate trustedcert = keystore.getCertificate(alias);
        if (trustedcert != null && trustedcert instanceof X509Certificate) {
            X509Certificate cert = (X509Certificate) trustedcert;
            message += "\n  Subject DN: " + cert.getSubjectDN();
            message += "\n  Signature Algorithm: " + cert.getSigAlgName();
            message += "\n  Valid from: " + cert.getNotBefore();
            message += "\n  Valid until: " + cert.getNotAfter();
            message += "\n  Issuer: " + cert.getIssuerDN();
        }
        log.info(message);
    }
}

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

/**
 * For debuging only.  Prints out keystore certificate chain.
 *
 * @param keystore Keystore to print out.
 * @throws KeyStoreException If the keystore is broken.
 *//*from  w  ww .j  a  v a  2  s  .com*/
public static void printKeyCertificates(KeyStore keystore) throws KeyStoreException {
    Enumeration<String> aliases = keystore.aliases();
    while (aliases.hasMoreElements()) {
        String alias = aliases.nextElement();
        Certificate[] certs = keystore.getCertificateChain(alias);
        if (certs != null) {
            String message = "Certificate chain '" + alias + "':";
            int i = 1;
            for (Certificate cert : certs) {
                if (cert instanceof X509Certificate) {
                    X509Certificate Xcert = (X509Certificate) cert;
                    message += "\n Certificate " + i++ + ":";
                    message += "\n  Subject DN: " + Xcert.getSubjectDN();
                    message += "\n  Signature Algorithm: " + Xcert.getSigAlgName();
                    message += "\n  Valid from: " + Xcert.getNotBefore();
                    message += "\n  Valid until: " + Xcert.getNotAfter();
                    message += "\n  Issuer: " + Xcert.getIssuerDN();
                }
            }
            log.info(message);
        }
    }
}

From source file:com.bcmcgroup.flare.xmldsig.Xmldsig.java

/**
* Method used to create an enveloped digital signature for an element of a TAXII document.
*
* @param element the element to be signed
* @param keyEntry the PrivateKeyEntry// www .j  a v  a 2 s  .  com
* @param cbIndex the index of the Content_Block if we're signing a Content_Block, otherwise set to -1 if we're signing the root element
* @return the status of the operation
*
* Usage Example:
*   String pks = config.getProperty("pathToPublisherKeyStore");
*    String pksPw = FLAREclientUtil.decrypt(config.getProperty("publisherKeyStorePassword"));
*    String keyName = config.getProperty("publisherKeyName");
*    String keyPW = FLAREclientUtil.decrypt(config.getProperty("publisherKeyPassword"));
*   PrivateKeyEntry keyEntry =  FLAREclientUtil.getKeyEntry(pks, pksPw, keyName, keyPW);
*   List<Integer> statusList = Xmldsig.sign(rootElement, keyEntry, -1);
*/
private static boolean sign(Element element, PrivateKeyEntry keyEntry, int cbIndex) {
    element.normalize();
    boolean status = false;

    //Create XML Signature Factory
    XMLSignatureFactory xmlSigFactory = XMLSignatureFactory.getInstance("DOM");
    PublicKey publicKey = ClientUtil.getPublicKey(keyEntry);
    PrivateKey privateKey = keyEntry.getPrivateKey();
    DOMSignContext dsc = new DOMSignContext(privateKey, element);
    dsc.setDefaultNamespacePrefix("ds");
    dsc.setURIDereferencer(new MyURIDereferencer(element));
    SignedInfo si = null;
    DigestMethod dm = null;
    SignatureMethod sm = null;
    KeyInfo ki = null;
    X509Data xd;
    List<Serializable> x509Content = new ArrayList<>();
    try {
        String algorithm = publicKey.getAlgorithm();
        X509Certificate cert = (X509Certificate) keyEntry.getCertificate();
        x509Content.add(cert.getSubjectX500Principal().getName());
        x509Content.add(cert);
        String algorithmName = cert.getSigAlgName();
        if (algorithm.toUpperCase().contains("RSA")) {
            if (algorithmName.toUpperCase().contains("SHA1")) {
                dm = xmlSigFactory.newDigestMethod(DigestMethod.SHA1, null);
                sm = xmlSigFactory.newSignatureMethod(SignatureMethod.RSA_SHA1, null);
            } else if (algorithmName.toUpperCase().contains("SHA2")) {
                dm = xmlSigFactory.newDigestMethod(DigestMethod.SHA256, null);
                sm = xmlSigFactory.newSignatureMethod(RSA_SHA256_URI, null);
            } else {
                logger.error("Error in digital signature application. " + algorithmName + " is not supported.");
            }
            CanonicalizationMethod cm;
            if (cbIndex != -1) {
                cm = xmlSigFactory.newCanonicalizationMethod(CanonicalizationMethod.INCLUSIVE_WITH_COMMENTS,
                        (C14NMethodParameterSpec) null);
                String refUri = "#xpointer(//*[local-name()='Content_Block'][" + cbIndex
                        + "]/*[local-name()='Content'][1]/*)";
                List<Reference> references = Collections.singletonList(xmlSigFactory.newReference(refUri, dm));
                si = xmlSigFactory.newSignedInfo(cm, sm, references);
            } else {
                List<Transform> transforms = new ArrayList<>(2);
                transforms.add(xmlSigFactory.newTransform(Transform.ENVELOPED, (TransformParameterSpec) null));
                transforms.add(xmlSigFactory.newTransform(CanonicalizationMethod.EXCLUSIVE,
                        (TransformParameterSpec) null));
                cm = xmlSigFactory.newCanonicalizationMethod(CanonicalizationMethod.EXCLUSIVE,
                        (C14NMethodParameterSpec) null);
                String refUri = "#xpointer(/*)";
                List<Reference> references = Collections
                        .singletonList(xmlSigFactory.newReference(refUri, dm, transforms, null, null));
                si = xmlSigFactory.newSignedInfo(cm, sm, references);
            }
            KeyInfoFactory kif = xmlSigFactory.getKeyInfoFactory();
            xd = kif.newX509Data(x509Content);
            ki = kif.newKeyInfo(Collections.singletonList(xd));
        } else {
            logger.error("Error in digital signature application. " + algorithmName + " is not supported.");
        }
    } catch (NoSuchAlgorithmException ex) {
        logger.error("NoSuchAlgorithm Exception when attempting to digitally sign a document.");
    } catch (InvalidAlgorithmParameterException ex) {
        logger.error("InvalidAlgorithmParameter Exception when attempting to digitally sign a document.");
    }

    // Create a new XML Signature
    XMLSignature signature = xmlSigFactory.newXMLSignature(si, ki);
    try {
        // Sign the document
        signature.sign(dsc);
        status = true;
    } catch (MarshalException ex) {
        logger.error("MarshalException when attempting to digitally sign a document.");
    } catch (XMLSignatureException ex) {
        logger.error("XMLSignature Exception when attempting to digitally sign a document.");
    } catch (Exception e) {
        logger.error("General exception when attempting to digitally sign a document.");
    }
    return status;
}

From source file:nl.nn.adapterframework.http.AuthSSLProtocolSocketFactoryBase.java

protected static KeyStore createKeyStore(final URL url, final String password, String keyStoreType,
        String prefix) throws KeyStoreException, NoSuchAlgorithmException, CertificateException, IOException {
    if (url == null) {
        throw new IllegalArgumentException("Keystore url for " + prefix + " may not be null");
    }/* w w  w .  j a  va 2 s.  co  m*/
    log.info("Initializing keystore for " + prefix + " from " + url.toString());
    KeyStore keystore = KeyStore.getInstance(keyStoreType);
    keystore.load(url.openStream(), password != null ? password.toCharArray() : null);
    if (log.isInfoEnabled()) {
        Enumeration aliases = keystore.aliases();
        while (aliases.hasMoreElements()) {
            String alias = (String) aliases.nextElement();
            log.info(prefix + " '" + alias + "':");
            Certificate trustedcert = keystore.getCertificate(alias);
            if (trustedcert != null && trustedcert instanceof X509Certificate) {
                X509Certificate cert = (X509Certificate) trustedcert;
                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());
            }
        }
    }
    return keystore;
}

From source file:com.dbay.apns4j.tools.ApnsTools.java

public final static SocketFactory createSocketFactory(InputStream keyStore, String password,
        String keystoreType, String algorithm, String protocol)
        throws KeyStoreException, NoSuchAlgorithmException, CertificateException, IOException,
        UnrecoverableKeyException, KeyManagementException, CertificateExpiredException {

    char[] pwdChars = password.toCharArray();
    KeyStore ks = KeyStore.getInstance(keystoreType);
    ks.load(keyStore, pwdChars);/* w  ww. j  a  v a  2s .c  o m*/

    // ??
    Enumeration<String> enums = ks.aliases();
    String alias = "";
    if (enums.hasMoreElements()) {
        alias = enums.nextElement();
    }
    if (StringUtils.isNotEmpty(alias)) {
        X509Certificate certificate = (X509Certificate) ks.getCertificate(alias);
        if (null != certificate) {
            String type = certificate.getType();
            int ver = certificate.getVersion();
            String name = certificate.getSubjectDN().getName();
            String serialNumber = certificate.getSerialNumber().toString(16);
            String issuerDN = certificate.getIssuerDN().getName();
            String sigAlgName = certificate.getSigAlgName();
            String publicAlgorithm = certificate.getPublicKey().getAlgorithm();
            Date before = certificate.getNotBefore();
            Date after = certificate.getNotAfter();

            String beforeStr = DateFormatUtils.format(before, "yyyy-MM-dd HH:mm:ss");
            String afterStr = DateFormatUtils.format(after, "yyyy-MM-dd HH:mm:ss");

            // ??
            long expire = DateUtil.getNumberOfDaysBetween(new Date(), after);
            if (expire <= 0) {
                if (LOG.isErrorEnabled()) {
                    LOG.error(
                            "?[{}], [{}], ?[{}], ??[{}], ?[{}], ??[{}], [{}], [{}][{}], ?[{}]",
                            name, type, ver, serialNumber, issuerDN, sigAlgName, publicAlgorithm, beforeStr,
                            afterStr, Math.abs(expire));
                }

                throw new CertificateExpiredException("??[" + Math.abs(expire) + "]");
            }

            if (LOG.isInfoEnabled()) {
                LOG.info(
                        "?[{}], [{}], ?[{}], ??[{}], ?[{}], ??[{}], [{}], [{}][{}], ?[{}]?",
                        name, type, ver, serialNumber, issuerDN, sigAlgName, publicAlgorithm, beforeStr,
                        afterStr, expire);
            }
        }
    }

    KeyManagerFactory kf = KeyManagerFactory.getInstance(algorithm);
    kf.init(ks, pwdChars);

    TrustManagerFactory tmf = TrustManagerFactory.getInstance(algorithm);
    tmf.init((KeyStore) null);
    SSLContext context = SSLContext.getInstance(protocol);
    context.init(kf.getKeyManagers(), tmf.getTrustManagers(), null);

    return context.getSocketFactory();
}

From source file:be.fedict.eid.applet.service.JSONServlet.java

private static JSONObject createCertJSONObject(X509Certificate certificate, SimpleDateFormat simpleDateFormat)
        throws CertificateEncodingException, IOException {
    JSONObject certJSONObject = new JSONObject();
    certJSONObject.put("subject", certificate.getSubjectX500Principal().toString());
    certJSONObject.put("issuer", certificate.getIssuerX500Principal().toString());
    certJSONObject.put("serialNumber", certificate.getSerialNumber().toString());
    certJSONObject.put("notBefore", certificate.getNotBefore().toString());
    certJSONObject.put("notAfter", certificate.getNotAfter().toString());
    certJSONObject.put("signatureAlgo", certificate.getSigAlgName());
    certJSONObject.put("thumbprint", DigestUtils.shaHex(certificate.getEncoded()));
    certJSONObject.put("details", certificate.toString());
    certJSONObject.put("pem", toPem(certificate));

    return certJSONObject;
}