Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
 package com.github.joschi.jersey.security;
 
 
Utility classes to extract PublicKey, PrivateKey, and X509Certificate from openssl generated PEM files

Author(s):
Bill Burke
Version:
$Revision: 1 $
public class PemUtils {
    static {
        BouncyIntegration.init();
    }
    public static X509Certificate decodeCertificate(InputStream isthrows Exception {
        byte[] der = pemToDer(is);
        ByteArrayInputStream bis = new ByteArrayInputStream(der);
        return DerUtils.decodeCertificate(bis);
    }

    
Extract a public key from a PEM string

Parameters:
pem
Returns:
Throws:
java.lang.Exception
    public static PublicKey decodePublicKey(String pemthrows Exception {
        byte[] der = pemToDer(pem);
        return DerUtils.decodePublicKey(der);
    }

    
Extract a private key that is a PKCS8 pem string (base64 encoded PKCS8)

Parameters:
pem
Returns:
Throws:
java.lang.Exception
    public static PrivateKey decodePrivateKey(String pemthrows Exception {
        byte[] der = pemToDer(pem);
        return DerUtils.decodePrivateKey(der);
    }
    public static PrivateKey decodePrivateKey(InputStream isthrows Exception {
        String pem = pemFromStream(is);
        return decodePrivateKey(pem);
    }

    
Decode a PEM file to DER format

Parameters:
is
Returns:
Throws:
java.io.IOException
    public static byte[] pemToDer(InputStream isthrows IOException {
        String pem = pemFromStream(is);
        byte[] der = pemToDer(pem);
        return der;
    }

    
Decode a PEM string to DER format

Parameters:
pem
Returns:
Throws:
java.io.IOException
    public static byte[] pemToDer(String pemthrows java.io.IOException {
        pem = removeBeginEnd(pem);
        return Base64.decode(pem);
    }
    private static String removeBeginEnd(String pem) {
        pem = pem.replaceAll("-----BEGIN (.*)-----""");
        pem = pem.replaceAll("-----END (.*)----""");
        pem = pem.replaceAll("\r\n""\n");
        return pem.trim();
    }
    public static String pemFromStream(InputStream isthrows IOException {
        DataInputStream dis = new DataInputStream(is);
        byte[] keyBytes = new byte[dis.available()];
        dis.readFully(keyBytes);
        dis.close();
        return new String(keyBytes"utf-8");
    }
New to GrepCode? Check out our FAQ X