Example usage for java.security.cert CertificateFactory generateCertificate

List of usage examples for java.security.cert CertificateFactory generateCertificate

Introduction

In this page you can find the example usage for java.security.cert CertificateFactory generateCertificate.

Prototype

public final Certificate generateCertificate(InputStream inStream) throws CertificateException 

Source Link

Document

Generates a certificate object and initializes it with the data read from the input stream inStream .

Usage

From source file:dk.nversion.jwt.CryptoUtils.java

public static PublicKey loadCertificate(String filename) throws FileNotFoundException, IOException,
        InvalidKeySpecException, NoSuchAlgorithmException, CertificateException {
    PublicKey key = null;/*from  w  ww  .j  a v  a 2 s .  co m*/
    InputStream is = null;
    try {
        is = new FileInputStream(filename);
        BufferedReader br = new BufferedReader(new InputStreamReader(is));
        StringBuilder builder = new StringBuilder();
        boolean inKey = false;

        String line;
        while ((line = br.readLine()) != null) {
            if (!inKey) {
                if (line.startsWith("-----BEGIN CERTIFICATE-----")) {
                    inKey = true;
                }
            } else {
                if (line.startsWith("-----END CERTIFICATE-----")) {
                    break;
                }
                builder.append(line);
            }
        }

        if (builder.length() == 0) {
            throw new CertificateException("Did not find a certificate in the file");
        }

        byte[] encoded = Base64.decodeBase64(builder.toString());
        CertificateFactory cf = CertificateFactory.getInstance("X.509");
        X509Certificate certificate = (X509Certificate) cf
                .generateCertificate(new ByteArrayInputStream(encoded));
        key = certificate.getPublicKey();

    } finally {
        if (is != null) {
            try {
                is.close();
            } catch (IOException ex) {
                // Ignore
            }
        }
    }
    return key;
}

From source file:org.apache.ambari.server.security.encryption.CertificateUtils.java

/**
 * Get RSA public key from X.509 certificate string (full crt file content, including header and footer)
 * @param certificateString certificate string
 * @return RSA public key//from www .j  a  va2 s .c  om
 * @throws CertificateException
 * @throws UnsupportedEncodingException
 */
public static RSAPublicKey getPublicKeyFromString(String certificateString)
        throws CertificateException, UnsupportedEncodingException {

    CertificateFactory fact = CertificateFactory.getInstance("X.509");
    ByteArrayInputStream is = new ByteArrayInputStream(certificateString.getBytes("UTF8"));

    X509Certificate cer = (X509Certificate) fact.generateCertificate(is);
    return (RSAPublicKey) cer.getPublicKey();
}

From source file:nl.surfnet.spring.security.opensaml.util.KeyStoreUtil.java

/**
 * Append a certificate and private key to a keystore.
 *
 * @param keyStore        where to append the certificate and private key to
 * @param keyAlias        the alias of the key
 * @param certificateInputStream the inputStream containing the certificate in the PEM format
 * @param privatekeyInputStream  the input stream containing the private key in the DER format
 * @param password        the password on the key
 *                        <p/>//from w  w  w .j  a  v  a2  s .c o m
 *                        Generate your private key: openssl genrsa -out something.key 1024
 *                        <p/>
 *                        Show the PEM private key: openssl asn1parse -inform pem -dump -i
 *                        -in something.key
 *                        <p/>
 *                        Translate the key to pkcs8 DER format: openssl pkcs8 -topk8
 *                        -inform PEM -outform DER -in something.key -nocrypt >
 *                        something.pkcs8.der
 *                        <p/>
 *                        Show the DER private key: openssl asn1parse -inform der -dump -i
 *                        -in something.pkcs8.der
 *                        <p/>
 *                        Generate a certificate request: openssl req -new -key
 *                        something.key -out something.csr
 *                        <p/>
 *                        Generate a certificate: openssl x509 -req -days 365 -in
 *                        something.csr -signkey something.key -out something.crt
 */

public static void appendKeyToKeyStore(KeyStore keyStore, String keyAlias, InputStream certificateInputStream,
        InputStream privatekeyInputStream, char[] password) throws IOException {

    CertificateFactory certFact;
    Certificate cert;
    try {
        certFact = CertificateFactory.getInstance("X.509");
        cert = certFact.generateCertificate(certificateInputStream);
    } catch (CertificateException e) {
        throw new RuntimeException("Could not instantiate cert", e);
    }
    ArrayList<Certificate> certs = new ArrayList<Certificate>();
    certs.add(cert);

    byte[] privKeyBytes = IOUtils.toByteArray(privatekeyInputStream);

    try {
        KeySpec ks = new PKCS8EncodedKeySpec(privKeyBytes);
        RSAPrivateKey privKey = (RSAPrivateKey) KeyFactory.getInstance("RSA").generatePrivate(ks);
        keyStore.setKeyEntry(keyAlias, privKey, password, certs.toArray(new Certificate[certs.size()]));
    } catch (InvalidKeySpecException e) {
        throw new RuntimeException(e);
    } catch (KeyStoreException e) {
        throw new RuntimeException(e);
    } catch (NoSuchAlgorithmException e) {
        throw new RuntimeException(e);
    }
}

From source file:Main.java

public static boolean isDebuggable(Context ctx) {
    boolean debuggable = false;
    try {//from w ww  . ja va 2s.c  o m
        PackageInfo pinfo = ctx.getPackageManager().getPackageInfo(ctx.getPackageName(),
                PackageManager.GET_SIGNATURES);
        Signature signatures[] = pinfo.signatures;
        for (int i = 0; i < signatures.length; i++) {
            CertificateFactory cf = CertificateFactory.getInstance("X.509");
            ByteArrayInputStream stream = new ByteArrayInputStream(signatures[i].toByteArray());
            X509Certificate cert = (X509Certificate) cf.generateCertificate(stream);
            debuggable = cert.getSubjectX500Principal().equals(DEBUG_DN);
            if (debuggable)
                break;
        }

    } catch (NameNotFoundException e) {
    } catch (CertificateException e) {
    }
    return debuggable;
}

From source file:ch.bfh.unicert.certimport.Main.java

/**
 * Create a certificate fot the given CSV record
 *
 * @param record the record to parse//  w w  w  .j  a  va 2s . c o m
 * @throws InvalidNameException
 */
private static void createCertificate(CSVRecord record) throws InvalidNameException {

    int recordid = Integer.parseInt(record.get(0));
    String pemCert = record.get(1);
    String institution = record.get(2);
    int revoked = Integer.parseInt(record.get(3));
    if (revoked == 1) {
        System.out.println("Certficate " + recordid + " is revoked. Looking for next certificate...");
        return;
    }

    String studyBranch = record.get(5);
    String uniqueId = record.get(6);
    String mail = record.get(8);

    CertificateFactory cf;
    X509Certificate cert;
    try {
        cf = CertificateFactory.getInstance("X.509");
        cert = (X509Certificate) cf.generateCertificate(new ByteArrayInputStream(pemCert.getBytes()));
    } catch (CertificateException ex) {
        logger.log(Level.SEVERE, "Not able to read certificate for record {0}, exception: {1}",
                new Object[] { recordid, ex });
        return;
    }

    DSAPublicKey pubKey = (DSAPublicKey) cert.getPublicKey();

    String commonName = cert.getSubjectDN().getName();

    LdapName ln = new LdapName(cert.getSubjectX500Principal().toString());

    for (Rdn rdn : ln.getRdns()) {
        if (rdn.getType().equalsIgnoreCase("CN")) {
            commonName = (String) rdn.getValue();
            break;
        } else if (rdn.getType().equalsIgnoreCase("UID")) {
            uniqueId = (String) rdn.getValue();
            break;
        } else if (rdn.getType().equalsIgnoreCase("OU")) {
            studyBranch = (String) rdn.getValue();
            break;
        }
    }

    IdentityData idData = new IdentityData(commonName, uniqueId, institution, studyBranch, null, null, null,
            null, null, "SwitchAAI", null);

    try {
        Certificate certificate = issuer.createClientCertificate(idData, keystorePath, pubKey, 10, "UniVote",
                new String[] { "Voter" }, uniBoardWSDLurl, uniBoardUrl, section);
        counter++;
        System.out.println("Certificate published for " + recordid + ". Count " + counter + " of 6424");
    } catch (CertificateCreationException ex) {
        logger.log(Level.SEVERE, "Not able to create certificate for record {0}, exception: {1}",
                new Object[] { recordid, ex });
    }
}

From source file:be.fedict.eid.idp.model.CryptoUtil.java

public static X509Certificate getCertificate(byte[] certificateBytes) throws CertificateException {

    CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
    return (X509Certificate) certificateFactory.generateCertificate(new ByteArrayInputStream(certificateBytes));
}

From source file:Main.java

/**
 * whether current app is debuggable//from   w ww . j av a2 s . co m
 */
public static boolean isDebuggable(Context ctx) {
    boolean debuggable = false;
    try {
        PackageInfo packageInfo = ctx.getPackageManager().getPackageInfo(ctx.getPackageName(),
                PackageManager.GET_SIGNATURES);
        Signature signatures[] = packageInfo.signatures;
        for (int i = 0; i < signatures.length; i++) {
            CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
            ByteArrayInputStream stream = new ByteArrayInputStream(signatures[i].toByteArray());
            X509Certificate cert = (X509Certificate) certificateFactory.generateCertificate(stream);
            debuggable = cert.getSubjectX500Principal().equals(DEBUG_DN);
            if (debuggable) {
                break;
            }
        }
    } catch (PackageManager.NameNotFoundException e) {
        e.printStackTrace();
    } catch (CertificateException e) {
        e.printStackTrace();
    }
    return debuggable;
}

From source file:Main.java

public static boolean isDebuggable(Context ctx) {
    boolean debuggable = false;
    try {/*from   ww w . jav  a  2  s .  c  om*/
        PackageInfo pinfo = ctx.getPackageManager().getPackageInfo(ctx.getPackageName(),
                PackageManager.GET_SIGNATURES);
        Signature signatures[] = pinfo.signatures;
        for (int i = 0; i < signatures.length; i++) {
            CertificateFactory cf = CertificateFactory.getInstance("X.509");//No i18n
            ByteArrayInputStream stream = new ByteArrayInputStream(signatures[i].toByteArray());
            X509Certificate cert = (X509Certificate) cf.generateCertificate(stream);
            debuggable = cert.getSubjectX500Principal().equals(DEBUG_DN);
            if (debuggable) {
                break;
            }
        }

    } catch (NameNotFoundException e) {
    } catch (CertificateException e) {
    }
    return debuggable;
}

From source file:Main.java

/**
 * parse a certificate file into ArrayList of certificates
 *///from  w  w  w  .  j  ava2s .  c o m
public static ArrayList<Certificate> readCertificate(File f) throws CertificateException {
    ArrayList<Certificate> certs = new ArrayList<Certificate>();
    CertificateFactory cf = CertificateFactory.getInstance("X.509");
    BufferedInputStream in;
    try {
        in = new BufferedInputStream(new FileInputStream(f));
        while (in.available() > 0) {
            Certificate cert = cf.generateCertificate(in);
            certs.add(cert);
        }
        in.close();
        return certs;
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return null;
}

From source file:com.easarrive.aws.plugins.common.util.SNSUtil.java

public static boolean isMessageSignatureValid(SNSMessage msg) {
    try {// ww  w  .  j  ava  2s  .  c  o m
        URL url = new URL(msg.getSigningCertURL());
        InputStream inStream = url.openStream();
        CertificateFactory cf = CertificateFactory.getInstance("X.509");
        X509Certificate cert = (X509Certificate) cf.generateCertificate(inStream);
        inStream.close();

        Signature sig = Signature.getInstance("SHA1withRSA");
        sig.initVerify(cert.getPublicKey());
        sig.update(getMessageBytesToSign(msg));
        return sig.verify(Base64.decodeBase64(msg.getSignature()));
    } catch (Exception e) {
        throw new SecurityException("Verify method failed.", e);
    }
}