Example usage for java.security KeyFactory generatePrivate

List of usage examples for java.security KeyFactory generatePrivate

Introduction

In this page you can find the example usage for java.security KeyFactory generatePrivate.

Prototype

public final PrivateKey generatePrivate(KeySpec keySpec) throws InvalidKeySpecException 

Source Link

Document

Generates a private key object from the provided key specification (key material).

Usage

From source file:com.thoughtworks.go.server.util.HttpTestUtil.java

private KeyPair generateKeyPair() {
    try {/*from w w  w  .j  ava2s .  c om*/
        KeyPair seed = KeyPairGenerator.getInstance("RSA", "BC").generateKeyPair();
        RSAPrivateKey privateSeed = (RSAPrivateKey) seed.getPrivate();
        RSAPublicKey publicSeed = (RSAPublicKey) seed.getPublic();
        KeyFactory fact = KeyFactory.getInstance("RSA", "BC");
        RSAPrivateKeySpec privateKeySpec = new RSAPrivateKeySpec(privateSeed.getModulus(),
                privateSeed.getPrivateExponent());
        RSAPublicKeySpec publicKeySpec = new RSAPublicKeySpec(publicSeed.getModulus(),
                publicSeed.getPublicExponent());
        return new KeyPair(fact.generatePublic(publicKeySpec), fact.generatePrivate(privateKeySpec));
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

From source file:io.fabric8.kubernetes.api.KubernetesFactory.java

private void configureClientCert(WebClient webClient) {
    try (InputStream certInputStream = getInputStreamFromDataOrFile(clientCertData, clientCertFile)) {
        CertificateFactory certFactory = CertificateFactory.getInstance("X509");
        X509Certificate cert = (X509Certificate) certFactory.generateCertificate(certInputStream);

        InputStream keyInputStream = getInputStreamFromDataOrFile(clientKeyData, clientKeyFile);
        PEMReader reader = new PEMReader(keyInputStream);
        RSAPrivateCrtKeySpec keySpec = new PKCS1EncodedKeySpec(reader.getDerBytes()).getKeySpec();
        KeyFactory kf = KeyFactory.getInstance(clientKeyAlgo);
        RSAPrivateKey privKey = (RSAPrivateKey) kf.generatePrivate(keySpec);

        KeyStore keyStore = KeyStore.getInstance("JKS");
        keyStore.load(null);/*from w ww. j  a  v a 2s .co m*/

        String alias = cert.getSubjectX500Principal().getName();
        keyStore.setKeyEntry(alias, privKey, clientKeyPassword, new Certificate[] { cert });

        KeyManagerFactory keyManagerFactory = KeyManagerFactory
                .getInstance(KeyManagerFactory.getDefaultAlgorithm());
        keyManagerFactory.init(keyStore, clientKeyPassword);

        HTTPConduit conduit = WebClient.getConfig(webClient).getHttpConduit();

        TLSClientParameters params = conduit.getTlsClientParameters();

        if (params == null) {
            params = new TLSClientParameters();
            conduit.setTlsClientParameters(params);
        }

        KeyManager[] existingKeyManagers = params.getKeyManagers();
        KeyManager[] keyManagers;

        if (existingKeyManagers == null || ArrayUtils.isEmpty(existingKeyManagers)) {
            keyManagers = keyManagerFactory.getKeyManagers();
        } else {
            keyManagers = (KeyManager[]) ArrayUtils.addAll(existingKeyManagers,
                    keyManagerFactory.getKeyManagers());
        }

        params.setKeyManagers(keyManagers);

    } catch (Exception e) {
        log.error("Could not create key manager for " + clientCertFile + " (" + clientKeyFile + ")", e);
    }
}

From source file:com.kuzumeji.platform.standard.SecurityService.java

/**
 * RSA??//from  w w w  .  j av  a  2 s . c  om
 * <dl>
 * <dt>?
 * <dd>RSA??
 * </dl>
 * @param name RSA???
 * @return RSA?
 */
public KeyPair loadKeyPair(final String name) {
    try {
        final Properties property = new PropertyService(PROPERTY_NAME).getProperty();
        final KeyFactory keyFactory = KeyFactory.getInstance(RSA_ALGO_NAME);
        final RSAPublicKey publicKey = (RSAPublicKey) keyFactory.generatePublic(new X509EncodedKeySpec(
                Hex.decodeHex(property.getProperty(String.format(KEY_PUBLIC_ENCODED, name)).toCharArray())));
        final RSAPrivateKey privateKey = (RSAPrivateKey) keyFactory.generatePrivate(new PKCS8EncodedKeySpec(
                Hex.decodeHex(property.getProperty(String.format(KEY_PRIVATE_ENCODED, name)).toCharArray())));
        return new KeyPair(publicKey, privateKey);
    } catch (final IOException | DecoderException | InvalidKeySpecException | NoSuchAlgorithmException e) {
        throw new RuntimeException(e);
    }
}

From source file:authorize.java

public void service(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    Logger logger = LogManager.getLogger(authorize.class);
    logger.trace("START");
    PrintWriter out = response.getWriter();
    Connection conn = null;//from w  w w .  j  a va 2 s . c  o m
    Statement stmt = null;
    ResultSet rs = null;
    HttpSession session = request.getSession(false);
    String response_type = request.getParameter("response_type");
    String username = request.getParameter("username");
    String password = request.getParameter("password");
    String prompt = request.getParameter("prompt");
    String login_hint = request.getParameter("login_hint");
    String max_age = request.getParameter("max_age");
    String client_id = request.getParameter("client_id");
    String redirect_uri = request.getParameter("redirect_uri");
    String scope = request.getParameter("scope");
    String state = request.getParameter("state");
    String nonce = request.getParameter("nonce");
    String consent = request.getParameter("consent");
    String client_scope = null;
    String access_token = null;
    String id_token = null;
    String passwd = null;
    String db_redirect_uri = null;
    String path = null;
    String sql = null;
    String uri = null;
    String issuer = null;
    String keyname = null;
    String kit = "public.key";
    boolean redirect_uri_check = true;
    int access_token_time = 60;
    if (scope == null) {
        scope = "openid";
    } else if (scope.equals("consent")) {
        scope = null;
        if (null != request.getParameter("openid")) {
            scope = "openid";
            if (null != request.getParameter("profile"))
                scope += " profile";
            if (null != request.getParameter("email"))
                scope += " email";
            if (null != request.getParameter("phone"))
                scope += " phone";
            if (null != request.getParameter("address"))
                scope += " address";
        }
    }
    logger.trace(scope);
    if (prompt != null && prompt.contains("login") && consent == null && session != null)
        session.invalidate();
    try {
        ServletContext context = this.getServletContext();
        path = context.getRealPath("/WEB-INF/oauth2");
        Class.forName("org.apache.derby.jdbc.EmbeddedDriver").newInstance();
        conn = DriverManager.getConnection("jdbc:derby:" + path);
        stmt = conn.createStatement();
        logger.trace("connect()");
        sql = "SELECT scope,redirect_uri FROM client WHERE client_id='" + client_id + "'";
        rs = stmt.executeQuery(sql);
        while (rs.next()) {
            client_scope = rs.getString("scope");
            db_redirect_uri = rs.getString("redirect_uri");
        }
        logger.trace(sql);
        if (redirect_uri == null)
            redirect_uri = db_redirect_uri;
        sql = "SELECT passwd FROM profile WHERE uid='" + username + "'";
        rs = stmt.executeQuery(sql);
        while (rs.next()) {
            passwd = rs.getString("passwd");
        }
        logger.trace(sql);
        path = context.getRealPath("/WEB-INF/config.json");
        InputStream input = new FileInputStream(path);
        JsonParser parser = Json.createParser(input);
        while (parser.hasNext()) {
            JsonParser.Event event = parser.next();
            switch (event) {
            case KEY_NAME:
                keyname = parser.getString();
                break;
            case VALUE_NUMBER:
                access_token_time = parser.getInt();
                break;
            case VALUE_TRUE:
                redirect_uri_check = true;
                break;
            case VALUE_FALSE:
                redirect_uri_check = false;
                break;
            case VALUE_STRING:
                if (keyname.equals("issuer"))
                    issuer = parser.getString();
                if (keyname.equals("kit"))
                    kit = parser.getString();
                break;
            default:
                break;
            }
        }
        java.util.Date dt = new java.util.Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String currentTime = sdf.format(dt);
        if (client_scope != null && passwd != null) {
            byte[] cipher_byte;
            MessageDigest md = MessageDigest.getInstance("SHA-256");
            md.update(password.getBytes());
            cipher_byte = md.digest();
            String sha256_password = Base64.getEncoder().withoutPadding().encodeToString(cipher_byte);
            StringTokenizer strToken = new StringTokenizer(scope, " ");
            while (strToken.hasMoreTokens()) {
                String token = strToken.nextToken().toString();
                logger.trace(token);
                if (!client_scope.contains(token))
                    throw new Exception("out of scope");
            }
            if (passwd.contains(sha256_password)
                    && (!redirect_uri_check || db_redirect_uri.equals(redirect_uri))) {
                if (prompt != null && prompt.contains("consent") && !consent.equals("false")) {
                    username = "null";
                    password = "null";
                    consent = "true";
                    throw new Exception("consent is true");
                }
                access_token = RandomStringUtils.randomAlphanumeric(32);
                logger.trace(access_token);
                sql = "insert into session(uid,access_token,issued_in,scope,client_id) values ('" + username
                        + "','" + access_token + "','" + currentTime + "','" + scope + "','" + client_id + "')";
                stmt.executeUpdate(sql);
                md.update(access_token.getBytes());
                cipher_byte = md.digest();
                byte[] half_cipher_byte = Arrays.copyOf(cipher_byte, (cipher_byte.length / 2));
                String at_hash = Base64.getEncoder().withoutPadding().encodeToString(half_cipher_byte);
                path = context.getRealPath("/WEB-INF/private.der");
                File filePrivateKey = new File(path);
                FileInputStream fis = new FileInputStream(path);
                byte[] encodedPrivateKey = new byte[(int) filePrivateKey.length()];
                fis.read(encodedPrivateKey);
                fis.close();
                KeyFactory keyFactory = KeyFactory.getInstance("RSA");
                PKCS8EncodedKeySpec privateKeySpec = new PKCS8EncodedKeySpec(encodedPrivateKey);
                PrivateKey privateKey = keyFactory.generatePrivate(privateKeySpec);
                Calendar exp = Calendar.getInstance();
                exp.add(Calendar.SECOND, access_token_time);
                if (nonce == null || nonce.equals("null")) {
                    if (response_type.contains("id_token")) {
                        uri = redirect_uri;
                        uri += "#error=invalid_request&error_description=nonce%20is%20not%20valid.";
                        response.sendRedirect(uri);
                        logger.info(uri);
                        return;
                    }
                } else {
                    id_token = Jwts.builder().setHeaderParam("alg", "RS256").setHeaderParam("typ", "JWT")
                            .setHeaderParam("kid", kit).setIssuer(issuer).claim("at_hash", at_hash)
                            .setSubject(username).setAudience(client_id).claim("nonce", nonce)
                            .setSubject(username).setExpiration(exp.getTime())
                            .setIssuedAt(Calendar.getInstance().getTime())
                            .claim("auth_time",
                                    String.valueOf(Calendar.getInstance().getTime().getTime()).substring(0, 10))
                            .signWith(SignatureAlgorithm.RS256, privateKey).compact();
                    logger.trace(id_token);
                }
                uri = redirect_uri;
                if (response_type.equals("token"))
                    uri += "#access_token=" + access_token + "&token_type=bearer&expires_in="
                            + access_token_time;
                if (response_type.equals("id_token"))
                    uri += "#id_token=" + id_token;
                if (response_type.equals("token id_token") || response_type.equals("id_token token"))
                    uri += "#access_token=" + access_token + "&token_type=bearer&expires_in="
                            + access_token_time + "&id_token=" + id_token;
                if (state != null && !state.equals("null"))
                    uri += "&state=" + state;
                response.sendRedirect(uri);
                logger.info(uri);
                return;
            }
        }
    } catch (Exception e) {
        logger.trace(e.getMessage());
    } finally {
        try {
            if (rs != null)
                rs.close();
            if (stmt != null)
                stmt.close();
            if (conn != null)
                conn.close();
            logger.trace("close()");
        } catch (SQLException e) {
            logger.trace(e.getMessage());
        }
    }
    if (redirect_uri != null || redirect_uri.equals("null"))
        uri = redirect_uri;
    else
        uri = "/myop/error";
    if (username != null && !username.equals("null") && password != null && !password.equals("null")) {
        uri += "#error=access_denied&error_description=User%20authentication%20failed.";
        session = request.getSession(false);
        if (session != null)
            session.invalidate();
    } else if (scope == null) {
        uri += "#error=invalid_scope&error_description=The%20scope%20value%20is%20not%20supported.";
    } else if (client_scope == null || client_scope.equals("null")) {
        uri += "#error=unauthorized_clienti&error_description=Client%20authentication%20failed.";
    } else if (response_type == null || response_type.equals("null")
            || !(response_type.equals("token") || response_type.equals("id_token")
                    || response_type.equals("token id_token") || response_type.equals("id_token token"))) {
        uri += "#error=unsupported_response_type&error_description==The%20response_type%20value%20%22"
                + response_type + "%22%20is%20not%20supported.";
    } else if (redirect_uri_check && !db_redirect_uri.equals(redirect_uri)) {
        uri += "#error=invalid_request&error_description=redirect_uri%20is%20not%20valid.";
    } else {
        uri = "/myop/login?response_type=" + URLEncoder.encode(response_type, "UTF-8") + "&client_id="
                + client_id + "&redirect_uri=" + URLEncoder.encode(redirect_uri, "UTF-8") + "&scope="
                + URLEncoder.encode(scope, "UTF-8");
        if (nonce != null && !nonce.equals("null"))
            uri += "&nonce=" + nonce;
        if (prompt != null && !prompt.equals("null"))
            uri += "&prompt=" + prompt;
        if (login_hint != null && !login_hint.equals("null"))
            uri += "&login_hint=" + login_hint;
        if (max_age != null && !max_age.equals("null"))
            uri += "&max_age=" + max_age;
        if (consent != null && consent.equals("true"))
            uri += "&consent=" + consent;
    }
    if (state != null && !state.equals("null"))
        uri += "&state=" + state;
    response.sendRedirect(uri);
    logger.info(uri);
    logger.trace("END");
}

From source file:org.bedework.util.security.pki.PKITools.java

private PrivateKey makePrivateKey(final byte[] privKeyBytes) throws PKIException {
    try {//  w ww . j  a  v a  2 s .co m
        PKCS8EncodedKeySpec privateKeySpec = new PKCS8EncodedKeySpec(privKeyBytes);
        KeyFactory kf;

        if (curSchema.pName == null) {
            kf = KeyFactory.getInstance(curSchema.algorithm);
        } else {
            kf = KeyFactory.getInstance(curSchema.algorithm, curSchema.pName);
        }

        return kf.generatePrivate(privateKeySpec);
    } catch (Throwable t) {
        throw new PKIException(t);
    }
}

From source file:org.apache.xml.security.test.encryption.BaltimoreEncTest.java

/**
 * Method setUp/*from  w  w  w  .jav a 2 s  . c o m*/
 */
protected void setUp() throws Exception {
    // Create the comparison strings

    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    dbf.setNamespaceAware(true);
    dbf.setAttribute("http://xml.org/sax/features/namespaces", Boolean.TRUE);

    String filename = "data/ie/baltimore/merlin-examples/merlin-xmlenc-five/plaintext.xml";
    String basedir = System.getProperty("basedir");
    if (basedir != null && !"".equals(basedir)) {
        filename = basedir + "/" + filename;
    }
    File f = new File(filename);

    DocumentBuilder db = dbf.newDocumentBuilder();
    Document doc = db.parse(new java.io.FileInputStream(f));

    cardNumber = retrieveCCNumber(doc);

    // Test decrypt
    testDecryptString = new String("top secret message\n");

    // Count the nodes in the document as a secondary test
    nodeCount = countNodes(doc);

    // Create the keys
    jebBytes = "abcdefghijklmnopqrstuvwx".getBytes("ASCII");
    jobBytes = "abcdefghijklmnop".getBytes("ASCII");
    jedBytes = "abcdefghijklmnopqrstuvwxyz012345".getBytes("ASCII");

    // Certificate information
    rsaCertSerialNumber = new String("1014918766910");

    // rsaKey
    filename = "data/ie/baltimore/merlin-examples/merlin-xmlenc-five/rsa.p8";
    if (basedir != null && !"".equals(basedir)) {
        filename = basedir + "/" + filename;
    }

    byte[] pkcs8Bytes = JavaUtils.getBytesFromFile(filename);

    PKCS8EncodedKeySpec pkcs8Spec = new PKCS8EncodedKeySpec(pkcs8Bytes);

    // Create a key factory 
    KeyFactory keyFactory = KeyFactory.getInstance("RSA");
    rsaKey = keyFactory.generatePrivate(pkcs8Spec);

    // Initialise the library

    org.apache.xml.security.Init.init();

    // Register our key resolver
    KeyResolver.register("org.apache.xml.security.test.encryption.BobKeyResolver");

    // Check what algorithms are available

    haveISOPadding = false;
    String algorithmId = JCEMapper
            .translateURItoJCEID(org.apache.xml.security.utils.EncryptionConstants.ALGO_ID_BLOCKCIPHER_AES128);

    if (algorithmId != null) {
        try {
            if (Cipher.getInstance(algorithmId) != null)
                haveISOPadding = true;
        } catch (NoSuchAlgorithmException nsae) {
        } catch (NoSuchPaddingException nspe) {
        }
    }

    haveKeyWraps = (JCEMapper.translateURItoJCEID(
            org.apache.xml.security.utils.EncryptionConstants.ALGO_ID_KEYWRAP_AES128) != null);
}

From source file:uk.bowdlerize.API.java

@Deprecated
private String SignHeaders(String dataToSign, boolean isUser) throws NoSuchAlgorithmException,
        InvalidKeySpecException, NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException,
        BadPaddingException, UnsupportedEncodingException, NoSuchProviderException, SignatureException {
    PKCS8EncodedKeySpec spec;/*from w  ww  . j  av  a 2 s  .co  m*/
    if (isUser) {
        spec = new PKCS8EncodedKeySpec(
                Base64.decode(settings.getString(SETTINGS_USER_PRIVATE_KEY, "").getBytes(), 0));
    } else {
        spec = new PKCS8EncodedKeySpec(
                Base64.decode(settings.getString(SETTINGS_PROBE_PRIVATE_KEY, "").getBytes(), 0));
    }

    KeyFactory kf = KeyFactory.getInstance("RSA", "BC");
    PrivateKey pk = kf.generatePrivate(spec);
    byte[] signed = null;

    //Log.e("algorithm", pk.getAlgorithm());

    Signature instance = Signature.getInstance("SHA1withRSA");
    instance.initSign(pk);
    instance.update(dataToSign.getBytes());
    signed = instance.sign();

    Log.e("privateKey", settings.getString(SETTINGS_USER_PRIVATE_KEY, ""));
    Log.e("privateKey", settings.getString(SETTINGS_PROBE_PRIVATE_KEY, ""));
    //Log.e("Signature",Base64.encodeToString(signed, Base64.NO_WRAP));

    return Base64.encodeToString(signed, Base64.NO_WRAP);
}

From source file:servlets.SecretKeyProvider.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods.//from  w ww .j ava2s. c  o m
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    String opcion = request.getParameter("opcion");

    switch (opcion) {
    case "public":
        InputStream is = getServletContext().getResourceAsStream("/WEB-INF/server1024.publica");
        IOUtils.copy(is, response.getOutputStream());
        break;

    case "secret": {
        try {
            SecretKey secretKey = KeyGenerator.getInstance("AES").generateKey();
            request.getSession().setAttribute("clave", secretKey);

            Security.addProvider(new BouncyCastleProvider()); // Cargar el provider BC
            Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());
            Cipher cifrador = Cipher.getInstance("RSA/ECB/PKCS1Padding", "BC");

            KeyFactory keyFactoryRSA = KeyFactory.getInstance("RSA", "BC"); // Hace uso del provider BC

            byte[] bufferPriv = new byte[5000];
            InputStream in = getServletContext().getResourceAsStream("/WEB-INF/server1024.privada");
            int chars = in.read(bufferPriv, 0, 5000);
            in.close();

            byte[] bufferPriv2 = new byte[chars];
            System.arraycopy(bufferPriv, 0, bufferPriv2, 0, chars);

            // 2.2 Recuperar clave privada desde datos codificados en formato PKCS8
            PKCS8EncodedKeySpec clavePrivadaSpec = new PKCS8EncodedKeySpec(bufferPriv2);
            PrivateKey clavePrivada2 = keyFactoryRSA.generatePrivate(clavePrivadaSpec);

            // PASO 3a: Poner cifrador en modo CIFRADO
            cifrador.init(Cipher.ENCRYPT_MODE, clavePrivada2); // Cifra con la clave publica

            byte[] bufferCifrado = cifrador.doFinal(secretKey.getEncoded());

            String mandar = new String(Base64.encodeBase64(bufferCifrado));
            response.getWriter().print(mandar);

        } catch (NoSuchAlgorithmException ex) {
            Logger.getLogger(SecretKeyProvider.class.getName()).log(Level.SEVERE, null, ex);
        } catch (NoSuchProviderException ex) {
            Logger.getLogger(SecretKeyProvider.class.getName()).log(Level.SEVERE, null, ex);
        } catch (NoSuchPaddingException ex) {
            Logger.getLogger(SecretKeyProvider.class.getName()).log(Level.SEVERE, null, ex);
        } catch (InvalidKeySpecException ex) {
            Logger.getLogger(SecretKeyProvider.class.getName()).log(Level.SEVERE, null, ex);
        } catch (InvalidKeyException ex) {
            Logger.getLogger(SecretKeyProvider.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IllegalBlockSizeException ex) {
            Logger.getLogger(SecretKeyProvider.class.getName()).log(Level.SEVERE, null, ex);
        } catch (BadPaddingException ex) {
            Logger.getLogger(SecretKeyProvider.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
    }
}

From source file:org.tolven.config.model.CredentialManager.java

private PrivateKey getDERPrivateKey(CertificateKeyDetail keyDetail, char[] password)
        throws IOException, GeneralSecurityException {
    File privateKeyFile = new File(keyDetail.getSource());
    if (!privateKeyFile.exists()) {
        throw new RuntimeException("Cannot find PrivateKey file: " + privateKeyFile.getPath());
    }//from  w w  w .j av a2 s .c  o m
    byte[] privateKey = FileUtils.readFileToByteArray(privateKeyFile);
    EncryptedPrivateKeyInfo encryptedKeyInfo = new EncryptedPrivateKeyInfo(privateKey);
    AlgorithmParameters params = encryptedKeyInfo.getAlgParameters();
    SecretKeyFactory secretKeyFactory = SecretKeyFactory.getInstance(encryptedKeyInfo.getAlgName());
    PBEKeySpec passwordSpec = new PBEKeySpec(password);
    SecretKey secretKey = secretKeyFactory.generateSecret(passwordSpec);
    Cipher cipher = Cipher.getInstance(encryptedKeyInfo.getAlgName());
    cipher.init(Cipher.DECRYPT_MODE, secretKey, params);
    PKCS8EncodedKeySpec keySpec = encryptedKeyInfo.getKeySpec(cipher);
    KeyFactory keyFactory = KeyFactory.getInstance("RSA");
    return keyFactory.generatePrivate(keySpec);
}

From source file:be.e_contract.mycarenet.common.SessionKey.java

/**
 * Loader constructor. Loads an existing MyCareNet session key.
 * /*from   w w  w. j a  v  a 2 s .c o  m*/
 * @param encodedPrivateKey
 * @param encodedPublicKey
 * @param encodedCertificate
 * @param notBefore
 * @param notAfter
 */
public SessionKey(byte[] encodedPrivateKey, byte[] encodedPublicKey, byte[] encodedCertificate, Date notBefore,
        Date notAfter) {
    this.notBefore = notBefore;
    this.notAfter = notAfter;

    X509EncodedKeySpec x509EncodedKeySpec = new X509EncodedKeySpec(encodedPublicKey);
    KeyFactory keyFactory;
    try {
        keyFactory = KeyFactory.getInstance("RSA");
    } catch (NoSuchAlgorithmException e) {
        throw new RuntimeException("RSA", e);
    }
    PublicKey publicKey;
    try {
        publicKey = keyFactory.generatePublic(x509EncodedKeySpec);
    } catch (InvalidKeySpecException e) {
        throw new RuntimeException("invalid public key: " + e.getMessage(), e);
    }

    PKCS8EncodedKeySpec pkcs8EncodedKeySpec = new PKCS8EncodedKeySpec(encodedPrivateKey);
    PrivateKey privateKey;
    try {
        privateKey = keyFactory.generatePrivate(pkcs8EncodedKeySpec);
    } catch (InvalidKeySpecException e) {
        throw new RuntimeException("invalid private key: " + e.getMessage(), e);
    }

    this.keyPair = new KeyPair(publicKey, privateKey);

    CertificateFactory certificateFactory;
    try {
        certificateFactory = CertificateFactory.getInstance("X.509");
    } catch (CertificateException e) {
        throw new RuntimeException(e);
    }
    try {
        this.certificate = (X509Certificate) certificateFactory
                .generateCertificate(new ByteArrayInputStream(encodedCertificate));
    } catch (CertificateException e) {
        throw new RuntimeException("certificate decoding error: " + e.getMessage(), e);
    }
}