Example usage for java.security KeyFactory getInstance

List of usage examples for java.security KeyFactory getInstance

Introduction

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

Prototype

public static KeyFactory getInstance(String algorithm) throws NoSuchAlgorithmException 

Source Link

Document

Returns a KeyFactory object that converts public/private keys of the specified algorithm.

Usage

From source file:org.opendatakit.services.utilities.EncryptionUtils.java

/**
 * Retrieve the encryption information for this row.
 * /*from  www .  j  a v  a  2  s. c  om*/
 * @param appName
 * @param tableId
 * @param xmlBase64RsaPublicKey
 * @param instanceId
 * @return
 */
public static EncryptedFormInformation getEncryptedFormInformation(String appName, String tableId,
        String xmlBase64RsaPublicKey, String instanceId) {

    // fetch the form information
    String base64RsaPublicKey = xmlBase64RsaPublicKey;
    PublicKey pk;
    Base64Wrapper wrapper;

    if (base64RsaPublicKey == null || base64RsaPublicKey.length() == 0) {
        return null; // this is legitimately not an encrypted form
    }

    // submission must have an OpenRosa metadata block with a non-null
    // instanceID value.
    if (instanceId == null) {
        WebLogger.getLogger(appName).e(t, "No OpenRosa metadata block or no instanceId defined in that block");
        return null;
    }

    int version = android.os.Build.VERSION.SDK_INT;
    if (version < 8) {
        WebLogger.getLogger(appName).e(t, "Phone does not support encryption.");
        return null; // save unencrypted
    }

    // this constructor will throw an exception if we are not
    // running on version 8 or above (if Base64 is not found).
    try {
        wrapper = new Base64Wrapper(appName);
    } catch (ClassNotFoundException e) {
        WebLogger.getLogger(appName).e(t, "Phone does not have Base64 class but API level is " + version);
        WebLogger.getLogger(appName).printStackTrace(e);
        return null; // save unencrypted
    }

    // OK -- Base64 decode (requires API Version 8 or higher)
    byte[] publicKey = wrapper.decode(base64RsaPublicKey);
    X509EncodedKeySpec publicKeySpec = new X509EncodedKeySpec(publicKey);
    KeyFactory kf;
    try {
        kf = KeyFactory.getInstance(RSA_ALGORITHM);
    } catch (NoSuchAlgorithmException e) {
        WebLogger.getLogger(appName).e(t, "Phone does not support RSA encryption.");
        WebLogger.getLogger(appName).printStackTrace(e);
        return null;
    }
    try {
        pk = kf.generatePublic(publicKeySpec);
    } catch (InvalidKeySpecException e) {
        WebLogger.getLogger(appName).printStackTrace(e);
        WebLogger.getLogger(appName).e(t, "Invalid RSA public key.");
        return null;
    }
    return new EncryptedFormInformation(appName, tableId, xmlBase64RsaPublicKey, instanceId, pk, wrapper);
}

From source file:org.oscarehr.sharingcenter.actions.SecurityInfrastructureServlet.java

private String importCertificates(Integer infrastructureId, InputStream inputStream) {

    String status = "fail";
    OscarProperties oscarProperties = OscarProperties.getInstance();
    String keyStoreFile = oscarProperties.getProperty("TOMCAT_KEYSTORE_FILE");
    String trustStoreFile = oscarProperties.getProperty("TOMCAT_TRUSTSTORE_FILE");
    String keyStorePass = oscarProperties.getProperty("TOMCAT_KEYSTORE_PASSWORD");
    String trustStorePass = oscarProperties.getProperty("TOMCAT_TRUSTSTORE_PASSWORD");

    InfrastructureDao dao = SpringUtils.getBean(InfrastructureDao.class);
    InfrastructureDataObject infrastructure = dao.getInfrastructure(infrastructureId);

    String alias = infrastructure.getAlias();
    PrivateKey privateKey = null;
    KeyStore ks = null;//from   w  ww .  j av  a2 s . c om
    KeyStore ts = null;

    try {
        //acquiring the private key
        Base64 base64 = new Base64();
        byte[] privKey = base64.decode(infrastructure.getBase64EncodedPrivateKey());
        privateKey = KeyFactory.getInstance("RSA").generatePrivate(new PKCS8EncodedKeySpec(privKey));

        ks = SslUtility.loadKeyStore(keyStoreFile, keyStorePass.toCharArray());
        ts = SslUtility.loadKeyStore(trustStoreFile, trustStorePass.toCharArray());

    } catch (SslException ex) {
        LOGGER.info(ex);
    } catch (InvalidKeySpecException ex) {
        LOGGER.info(ex);
    } catch (NoSuchAlgorithmException ex) {
        LOGGER.info(ex);
    }

    if (ks != null && ts != null && privateKey != null) {
        // import certificates to keystore and truststore
        try {
            // extract certificates
            ArrayList<X509Certificate> certificates = SslUtility.extractX509Certificates(inputStream);
            // get the private key and add certificate chain
            X509Certificate[] chain = new X509Certificate[2];
            ks.setKeyEntry(alias, privateKey, keyStorePass.toCharArray(), certificates.toArray(chain));

            // save the keystore
            ks.store(new FileOutputStream(keyStoreFile), keyStorePass.toCharArray());

            // add root CA certificate truststore
            ArrayList<X509Certificate> caCerts = SslUtility.retrieveCACertificates(certificates);
            for (X509Certificate x509Certificate : caCerts) {
                ts.setCertificateEntry(alias, x509Certificate);
            }

            // save the truststore
            ts.store(new FileOutputStream(trustStoreFile), trustStorePass.toCharArray());
            status = "import";
        } catch (NoSuchAlgorithmException ex) {
            LOGGER.info(ex);
        } catch (CertificateException ex) {
            LOGGER.info(ex);
        } catch (KeyStoreException ex) {
            LOGGER.info(ex);
        } catch (IOException ex) {
            LOGGER.info(ex);
        } catch (SslException ex) {
            LOGGER.info(ex);
        }
    } else {
        LOGGER.debug("Bad data. Keystore/Truststore/PrivateKey might be null");
    }

    return status;

}

From source file:com.mytalentfolio.h_daforum.CconnectToServer.java

/**
 * Creates a new instance of {@code PublicKey}. Convert the string formatted
 * public key into {@code PublicKey} type.
 * //  w ww .j  a v a 2s.  c o  m
 * @param key
 *            the string formated public key.
 * @return the new {@code PublicKey} instance.
 * @throws NoSuchAlgorithmException
 *             if no provider provides the requested algorithm.
 * @throws InvalidKeyException
 *             if the specified keySpec is invalid.
 * 
 */
// Converting the Server Public key format to Java compatible from
private PublicKey getServerPublicKey(String key) throws NoSuchAlgorithmException, InvalidKeySpecException {

    // Converting the Server Public key format to Java compatible from
    key = key.replace("-----BEGIN PUBLIC KEY-----\n", "");
    key = key.replace("\n-----END PUBLIC KEY-----", "");

    // Creating the public key from the string format received from server
    KeyFactory keyFactory = KeyFactory.getInstance("RSA");
    PublicKey serverPublicKeySig = keyFactory
            .generatePublic(new X509EncodedKeySpec(Base64.decode(key.toString(), Base64.DEFAULT)));
    return serverPublicKeySig;
}

From source file:net.sourceforge.msscodefactory.cfasterisk.v2_2.CFAstSMWar.CFAstSMWarAddDeviceHtml.java

/**
 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
 *//*from  w  ww. j a va2 s. c o  m*/
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    final String S_ProcName = "doPost";

    ICFAstSchemaObj schemaObj;
    HttpSession sess = request.getSession(false);
    if (sess == null) {
        sess = request.getSession(true);
        schemaObj = new CFAstSchemaObj();
        sess.setAttribute("SchemaObj", schemaObj);
    } else {
        schemaObj = (ICFAstSchemaObj) sess.getAttribute("SchemaObj");
        if (schemaObj == null) {
            response.sendRedirect("CFAstSMWarLoginHtml");
            return;
        }
    }

    CFAstAuthorization auth = schemaObj.getAuthorization();
    if (auth == null) {
        response.sendRedirect("CFAstSMWarLoginHtml");
        return;
    }

    ICFAstSecUserObj secUser = null;
    ICFAstClusterObj secCluster = null;
    String clusterDescription = "";

    ICFAstSchema dbSchema = null;
    try {
        dbSchema = CFAstSchemaPool.getSchemaPool().getInstance();
        schemaObj.setBackingStore(dbSchema);
        schemaObj.beginTransaction();

        secUser = schemaObj.getSecUserTableObj().readSecUserByIdIdx(auth.getSecUserId());

        secCluster = schemaObj.getClusterTableObj().readClusterByIdIdx(auth.getSecClusterId());
        if (secCluster == null) {
            throw CFLib.getDefaultExceptionFactory().newNullArgumentException(getClass(), S_ProcName, 0,
                    "secCluster");
        }
        clusterDescription = secCluster.getRequiredDescription();

        String deviceName = request.getParameter("DeviceName");
        if ((deviceName == null) || (deviceName.length() <= 0)) {
            response.setContentType("text/html");
            PrintWriter out = response.getWriter();
            out.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01//EN\">");
            out.println("<HTML>");
            out.println("<BODY>");
            out.println("<form method=\"post\" formaction=\"CFAstSMWarAddDeviceHtml\">");
            out.println("<H1 style=\"text-align:center\">" + clusterDescription + " Security Manager</H1>");
            out.println("<H2 style=\"text-align:center\">ERROR</H2>");
            out.println("<p style=\"text-align:center\">Device Name must be specified.");
            out.println("<H2 style=\"text-align:center\">Add new device for "
                    + secUser.getRequiredEMailAddress() + "</H2>");
            out.println("<p>");
            out.println("<table style=\"width:90%\">");
            out.println(
                    "<tr><th style=\"text-align:left\">Device Name:</th><td><input type=\"text\" name=\"DeviceName\"/></td></tr>");
            out.println(
                    "<tr><th style=\"text-align:left\">Public Key:</th><td><textarea name=\"PublicKey\" cols=\"60\" rows=\"10\"></textarea></td></tr>");
            out.println("</table>");
            out.println(
                    "<p style=\"text-align:center\"><button type=\"submit\" name=\"Ok\"\">Add Device</button>&nbsp;&nbsp;&nbsp;&nbsp;<button type=\"button\" name=\"Cancel\"\" onclick=\"window.location.href='CFAstSMWarSecurityMainHtml'\">Cancel</button>");
            out.println("</form>");
            out.println("</BODY>");
            out.println("</HTML>");
            return;
        }

        ICFAstSecDeviceObj secDev = schemaObj.getSecDeviceTableObj()
                .readSecDeviceByIdIdx(secUser.getRequiredSecUserId(), deviceName);
        if (secDev != null) {
            response.setContentType("text/html");
            PrintWriter out = response.getWriter();
            out.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01//EN\">");
            out.println("<HTML>");
            out.println("<BODY>");
            out.println("<form method=\"post\" formaction=\"CFAstSMWarAddDeviceHtml\">");
            out.println("<H1 style=\"text-align:center\">" + clusterDescription + " Security Manager</H1>");
            out.println("<H2 style=\"text-align:center\">ERROR</H2>");
            out.println("<p style=\"text-align:center\">Device Name \"" + deviceName + "\" already in use.");
            out.println("<H2 style=\"text-align:center\">Add new device for "
                    + secUser.getRequiredEMailAddress() + "</H2>");
            out.println("<p>");
            out.println("<table style=\"width:90%\">");
            out.println(
                    "<tr><th style=\"text-align:left\">Device Name:</th><td><input type=\"text\" name=\"DeviceName\"/></td></tr>");
            out.println(
                    "<tr><th style=\"text-align:left\">Public Key:</th><td><textarea name=\"PublicKey\" cols=\"60\" rows=\"10\"></textarea></td></tr>");
            out.println("</table>");
            out.println(
                    "<p style=\"text-align:center\"><button type=\"submit\" name=\"Ok\"\">Add Device</button>&nbsp;&nbsp;&nbsp;&nbsp;<button type=\"button\" name=\"Cancel\"\" onclick=\"window.location.href='CFAstSMWarSecurityMainHtml'\">Cancel</button>");
            out.println("</form>");
            out.println("</BODY>");
            out.println("</HTML>");
            return;
        }

        String publicKey = request.getParameter("PublicKey");
        if ((publicKey == null) || (publicKey.length() <= 0)) {
            response.setContentType("text/html");
            PrintWriter out = response.getWriter();
            out.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01//EN\">");
            out.println("<HTML>");
            out.println("<BODY>");
            out.println("<form method=\"post\" formaction=\"CFAstSMWarAddDeviceHtml\">");
            out.println("<H1 style=\"text-align:center\">" + clusterDescription + " Security Manager</H1>");
            out.println("<p style=\"text-align:center\">Public Key must be specified.");
            out.println("<H2 style=\"text-align:center\">Add new device for "
                    + secUser.getRequiredEMailAddress() + "</H2>");
            out.println("<p>");
            out.println("<table style=\"width:90%\">");
            out.println(
                    "<tr><th style=\"text-align:left\">Device Name:</th><td><input type=\"text\" name=\"DeviceName\"/></td></tr>");
            out.println(
                    "<tr><th style=\"text-align:left\">Public Key:</th><td><textarea name=\"PublicKey\" cols=\"60\" rows=\"10\"></textarea></td></tr>");
            out.println("</table>");
            out.println(
                    "<p style=\"text-align:center\"><button type=\"submit\" name=\"Ok\"\">Add Device</button>&nbsp;&nbsp;&nbsp;&nbsp;<button type=\"button\" name=\"Cancel\"\" onclick=\"window.location.href='CFAstSMWarSecurityMainHtml'\">Cancel</button>");
            out.println("</form>");
            out.println("</BODY>");
            out.println("</HTML>");
            return;
        }

        byte wrapped[] = Base64.decodeBase64(publicKey);

        X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(wrapped);
        KeyFactory kf = KeyFactory.getInstance("RSA");
        if (kf == null) {
            throw CFLib.getDefaultExceptionFactory().newNullArgumentException(getClass(), S_ProcName, 0, "kf");
        }

        PublicKey decodedPublicKey = kf.generatePublic(x509KeySpec);
        if (decodedPublicKey == null) {
            response.setContentType("text/html");
            PrintWriter out = response.getWriter();
            out.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01//EN\">");
            out.println("<HTML>");
            out.println("<BODY>");
            out.println("<form method=\"post\" formaction=\"CFAstSMWarAddDeviceHtml\">");
            out.println("<H1 style=\"text-align:center\">" + clusterDescription + " Security Manager</H1>");
            out.println("<p style=\"text-align:center\">Public Key must be a valid RSA 2048 Key.");
            out.println("<H2 style=\"text-align:center\">Add new device for "
                    + secUser.getRequiredEMailAddress() + "</H2>");
            out.println("<p>");
            out.println("<table style=\"width:90%\">");
            out.println(
                    "<tr><th style=\"text-align:left\">Device Name:</th><td><input type=\"text\" name=\"DeviceName\"/></td></tr>");
            out.println(
                    "<tr><th style=\"text-align:left\">Public Key:</th><td><textarea name=\"PublicKey\" cols=\"60\" rows=\"10\"></textarea></td></tr>");
            out.println("</table>");
            out.println(
                    "<p style=\"text-align:center\"><button type=\"submit\" name=\"Ok\"\">Add Device</button>&nbsp;&nbsp;&nbsp;&nbsp;<button type=\"button\" name=\"Cancel\"\" onclick=\"window.location.href='CFAstSMWarSecurityMainHtml'\">Cancel</button>");
            out.println("</form>");
            out.println("</BODY>");
            out.println("</HTML>");
            return;
        }

        ICFAstClusterObj systemCluster = schemaObj.getClusterTableObj().readClusterByUDomainNameIdx("system");
        ICFAstTenantObj systemTenant = schemaObj.getTenantTableObj()
                .readTenantByUNameIdx(systemCluster.getRequiredId(), "system");
        ICFAstSecUserObj systemUser = schemaObj.getSecUserTableObj().readSecUserByULoginIdx("system");
        ICFAstSecSessionObj systemSession = schemaObj.getSecSessionTableObj().newInstance();
        ICFAstSecSessionEditObj editSystemSession = (ICFAstSecSessionEditObj) systemSession.beginEdit();
        editSystemSession.setRequiredContainerSecUser(systemUser);
        editSystemSession.setRequiredStart(Calendar.getInstance());
        systemSession = editSystemSession.create();
        editSystemSession.endEdit();

        CFAstAuthorization secAuth = new CFAstAuthorization();
        secAuth.setSecCluster(systemCluster);
        secAuth.setSecTenant(systemTenant);
        secAuth.setSecSession(systemSession);
        schemaObj.setAuthorization(secAuth);

        secDev = schemaObj.getSecDeviceTableObj().newInstance();
        ICFAstSecDeviceEditObj editDev = secDev.beginEdit();
        editDev.setRequiredContainerSecUser(secUser);
        editDev.setRequiredDevName(deviceName);
        editDev.setOptionalPubKey(publicKey);
        secDev = editDev.create();
        editDev.endEdit();

        if (null == secUser.getOptionalLookupDefDev()) {
            ICFAstSecUserEditObj editSecUser = secUser.beginEdit();
            editSecUser.setOptionalLookupDefDev(secDev);
            editSecUser.update();
            editSecUser.endEdit();
        }

        editSystemSession = (ICFAstSecSessionEditObj) systemSession.beginEdit();
        editSystemSession.setOptionalFinish(Calendar.getInstance());
        editSystemSession.update();
        editSystemSession.endEdit();

        schemaObj.commit();

        schemaObj.setAuthorization(auth);

        response.sendRedirect("CFAstSMWarSecurityMainHtml");

    } catch (InvalidKeySpecException e) {
        response.setContentType("text/html");
        PrintWriter out = response.getWriter();
        out.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01//EN\">");
        out.println("<HTML>");
        out.println("<BODY>");
        out.println("<form method=\"post\" formaction=\"CFAstSMWarAddDeviceHtml\">");
        out.println("<H1 style=\"text-align:center\">" + clusterDescription + " Security Manager</H1>");
        out.println("<p style=\"text-align:center\">Public Key must be a valid RSA 2048 Key.");
        out.println("<H2 style=\"text-align:center\">Add new device for " + secUser.getRequiredEMailAddress()
                + "</H2>");
        out.println("<p>");
        out.println("<table style=\"width:90%\">");
        out.println(
                "<tr><th style=\"text-align:left\">Device Name:</th><td><input type=\"text\" name=\"DeviceName\"/></td></tr>");
        out.println(
                "<tr><th style=\"text-align:left\">Public Key:</th><td><textarea name=\"PublicKey\" cols=\"60\" rows=\"10\"></textarea></td></tr>");
        out.println("</table>");
        out.println(
                "<p style=\"text-align:center\"><button type=\"submit\" name=\"Ok\"\">Add Device</button>&nbsp;&nbsp;&nbsp;&nbsp;<button type=\"button\" name=\"Cancel\"\" onclick=\"window.location.href='CFAstSMWarSecurityMainHtml'\">Cancel</button>");
        out.println("</form>");
        out.println("</BODY>");
        out.println("</HTML>");
    } catch (NoSuchAlgorithmException e) {
        throw CFLib.getDefaultExceptionFactory().newRuntimeException(getClass(), S_ProcName,
                "Caught NoSuchAlgorithmException -- " + e.getMessage(), e);
    } catch (RuntimeException e) {
        throw CFLib.getDefaultExceptionFactory().newRuntimeException(getClass(), S_ProcName,
                "Caught RuntimeException -- " + e.getMessage(), e);
    } finally {
        schemaObj.setAuthorization(auth);
        if (dbSchema != null) {
            try {
                if (schemaObj.isTransactionOpen()) {
                    schemaObj.rollback();
                }
            } catch (RuntimeException e) {
            }
            schemaObj.setBackingStore(null);
            CFAstSchemaPool.getSchemaPool().releaseInstance(dbSchema);
        }
    }
}

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  va2s  .com

        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.squid.kraken.v4.api.core.customer.AuthServiceImpl.java

public AccessToken getTokenFromJWT(AppContext ctx, String jwt) {
    try {/* w  w w  . ja  va 2s.co  m*/
        // first pass to read the issuer (client Id)
        JwtConsumer firstPassJwtConsumer = new JwtConsumerBuilder().setSkipAllValidators()
                .setDisableRequireSignature().setSkipSignatureVerification().build();
        JwtContext jwtContext = firstPassJwtConsumer.process(jwt);
        JwtClaims claims = jwtContext.getJwtClaims();
        String issuer = claims.getIssuer();
        String customerId = claims.getStringClaimValue("customerId");
        ClientPK clientId = new ClientPK(claims.getStringClaimValue("customerId"), issuer);

        // load the client using superuser to get the key
        AppContext rootUserContext = ServiceUtils.getInstance().getRootUserContext(customerId);
        Client client = DAOFactory.getDAOFactory().getDAO(Client.class).readNotNull(rootUserContext, clientId);
        String publicKeyPEM = client.getJWTKeyPublic();
        publicKeyPEM = publicKeyPEM.substring(publicKeyPEM.indexOf('\n'), publicKeyPEM.lastIndexOf('\n'));
        publicKeyPEM = publicKeyPEM.replace("\n", "");
        byte[] publicKey = Base64.decodeBase64(publicKeyPEM);

        KeySpec keySpec = new X509EncodedKeySpec(publicKey);
        KeyFactory kf = KeyFactory.getInstance("RSA");
        PublicKey key = kf.generatePublic(keySpec);

        JwtConsumer jwtConsumer = new JwtConsumerBuilder().setRequireExpirationTime() // the JWT must have an expiration time
                .setAllowedClockSkewInSeconds(30) // allow some leeway in validating time based claims to account for clock skew
                .setRequireSubject() // the JWT must have a subject claim
                .setVerificationKey(key) // verify the signature with the public key
                .build(); // create the JwtConsumer instance

        // validate the JWT
        jwtConsumer.processContext(jwtContext);

        // create the token
        String userId = jwtContext.getJwtClaims().getSubject();
        AccessToken token = ServiceUtils.getInstance().createToken(customerId, clientId, userId,
                System.currentTimeMillis(), ServiceUtils.getInstance().getTokenExpirationPeriodMillis(), null,
                null);
        return token;
    } catch (MalformedClaimException e) {
        logger.debug(e.getMessage());
        throw new InvalidCredentialsAPIException("Invalid JWT Claim", ctx.isNoError());
    } catch (InvalidJwtException e) {
        logger.debug(e.getMessage());
        throw new InvalidCredentialsAPIException("Invalid JWT", ctx.isNoError());
    } catch (NoSuchAlgorithmException e) {
        logger.debug(e.getMessage());
        throw new RuntimeException(e);
    } catch (InvalidKeySpecException e) {
        logger.debug(e.getMessage());
        throw new RuntimeException(e);
    }
}

From source file:com.intuit.s3encrypt.S3Encrypt.java

public static KeyPair loadKeyPair(String filename, String algorithm)
        throws IOException, NoSuchAlgorithmException, InvalidKeySpecException {
    // Read public key from file.
    FileInputStream keyfis = new FileInputStream(filename + ".pub");
    byte[] encodedPublicKey = new byte[keyfis.available()];
    keyfis.read(encodedPublicKey);/*from w  w w  . j ava 2  s. co  m*/
    keyfis.close();

    // Read private key from file.
    keyfis = new FileInputStream(filename);
    byte[] encodedPrivateKey = new byte[keyfis.available()];
    keyfis.read(encodedPrivateKey);
    keyfis.close();

    // Generate KeyPair from public and private keys.
    KeyFactory keyFactory = KeyFactory.getInstance(algorithm);
    X509EncodedKeySpec publicKeySpec = new X509EncodedKeySpec(encodedPublicKey);
    PublicKey publicKey = keyFactory.generatePublic(publicKeySpec);

    PKCS8EncodedKeySpec privateKeySpec = new PKCS8EncodedKeySpec(encodedPrivateKey);
    PrivateKey privateKey = keyFactory.generatePrivate(privateKeySpec);

    return new KeyPair(publicKey, privateKey);

}

From source file:strat.mining.stratum.proxy.Launcher.java

/**
 * Check that a valid SSl certificate already exists. If not, create a new
 * one./*from  ww  w .jav a  2s.  c o  m*/
 * 
 * @throws Exception
 */
private static void checkCertificate() throws Exception {
    File storeFile = new File(ConfigurationManager.getInstance().getDatabaseDirectory(), KEYSTORE_FILE_NAME);
    KeyStore keyStore = KeyStore.getInstance("JKS");
    if (!storeFile.exists()) {
        LOGGER.info("KeyStore does not exist. Create {}", storeFile.getAbsolutePath());
        storeFile.getParentFile().mkdirs();
        storeFile.createNewFile();
        keyStore.load(null, null);

        LOGGER.info("Generating new SSL certificate.");
        AlgorithmIdentifier sigAlgId = new DefaultSignatureAlgorithmIdentifierFinder().find("SHA256withRSA");
        AlgorithmIdentifier digAlgId = new DefaultDigestAlgorithmIdentifierFinder().find(sigAlgId);

        RSAKeyPairGenerator keyGenerator = new RSAKeyPairGenerator();
        keyGenerator
                .init(new RSAKeyGenerationParameters(BigInteger.valueOf(101), new SecureRandom(), 2048, 14));
        AsymmetricCipherKeyPair keysPair = keyGenerator.generateKeyPair();

        RSAKeyParameters rsaPrivateKey = (RSAKeyParameters) keysPair.getPrivate();
        RSAPrivateKeySpec rsaPrivSpec = new RSAPrivateKeySpec(rsaPrivateKey.getModulus(),
                rsaPrivateKey.getExponent());
        RSAKeyParameters rsaPublicKey = (RSAKeyParameters) keysPair.getPublic();
        RSAPublicKeySpec rsaPublicSpec = new RSAPublicKeySpec(rsaPublicKey.getModulus(),
                rsaPublicKey.getExponent());
        KeyFactory kf = KeyFactory.getInstance("RSA");
        PrivateKey rsaPriv = kf.generatePrivate(rsaPrivSpec);
        PublicKey rsaPub = kf.generatePublic(rsaPublicSpec);

        X500Name issuerDN = new X500Name("CN=localhost, OU=None, O=None, L=None, C=None");
        Integer randomNumber = new SecureRandom().nextInt();
        BigInteger serialNumber = BigInteger.valueOf(randomNumber >= 0 ? randomNumber : randomNumber * -1);
        Date notBefore = new Date(System.currentTimeMillis() - 1000L * 60 * 60 * 24 * 30);
        Date notAfter = new Date(System.currentTimeMillis() + (1000L * 60 * 60 * 24 * 365 * 10));
        X500Name subjectDN = new X500Name("CN=localhost, OU=None, O=None, L=None, C=None");
        byte[] publickeyb = rsaPub.getEncoded();
        ASN1Sequence sequence = (ASN1Sequence) ASN1Primitive.fromByteArray(publickeyb);
        SubjectPublicKeyInfo subPubKeyInfo = new SubjectPublicKeyInfo(sequence);
        X509v3CertificateBuilder v3CertGen = new X509v3CertificateBuilder(issuerDN, serialNumber, notBefore,
                notAfter, subjectDN, subPubKeyInfo);

        ContentSigner contentSigner = new BcRSAContentSignerBuilder(sigAlgId, digAlgId)
                .build(keysPair.getPrivate());
        X509CertificateHolder certificateHolder = v3CertGen.build(contentSigner);

        Certificate certificate = new CertificateFactory()
                .engineGenerateCertificate(new ByteBufferBackedInputStream(
                        ByteBuffer.wrap(certificateHolder.toASN1Structure().getEncoded())));

        LOGGER.info("Certificate generated.");

        keyStore.setKeyEntry(KEYSTORE_KEY_ENTRY_ALIAS, rsaPriv, KEYSTORE_PASSWORD.toCharArray(),
                new java.security.cert.Certificate[] { certificate });

        keyStore.store(new FileOutputStream(storeFile), KEYSTORE_PASSWORD.toCharArray());
    }
}

From source file:com.owncloud.android.utils.EncryptionUtils.java

/**
 * Decrypt string with RSA algorithm, ECB mode, OAEPWithSHA-256AndMGF1 padding
 * Asymmetric encryption, with private and public key
 *
 * @param string           string to decrypt
 * @param privateKeyString private key//  w w w.  ja  va2s .  c om
 * @return decrypted string
 */
@RequiresApi(api = Build.VERSION_CODES.KITKAT)
public static String decryptStringAsymmetric(String string, String privateKeyString)
        throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, BadPaddingException,
        IllegalBlockSizeException, InvalidKeySpecException {

    Cipher cipher = Cipher.getInstance(RSA_CIPHER);

    byte[] privateKeyBytes = decodeStringToBase64Bytes(privateKeyString);
    PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(privateKeyBytes);
    KeyFactory kf = KeyFactory.getInstance(RSA);
    PrivateKey privateKey = kf.generatePrivate(keySpec);

    cipher.init(Cipher.DECRYPT_MODE, privateKey);

    byte[] bytes = decodeStringToBase64Bytes(string);
    byte[] encodedBytes = cipher.doFinal(bytes);

    return decodeBase64BytesToString(encodedBytes);
}

From source file:com.mastercard.mcbp.utils.crypto.CryptoServiceImpl.java

/**
 * {@inheritDoc}/*from   w  w w  .  j  a v  a 2s.c  o m*/
 */
@Override
public final int initRsaPrivateKey(final ByteArray primeP, final ByteArray primeQ,
        final ByteArray primeExponentP, final ByteArray primeExponentQ, final ByteArray crtCoefficient)
        throws McbpCryptoException {
    try {
        final BigInteger p = new BigInteger(primeP.toHexString(), 16);
        final BigInteger q = new BigInteger(primeQ.toHexString(), 16);
        final BigInteger dp = new BigInteger(primeExponentP.toHexString(), 16);
        final BigInteger dq = new BigInteger(primeExponentQ.toHexString(), 16);
        final BigInteger a = new BigInteger(crtCoefficient.toHexString(), 16);

        final BigInteger n = p.multiply(q);
        final BigInteger e = dp.modInverse(p.subtract(BigInteger.ONE));

        final BigInteger d = e.modInverse(p.subtract(BigInteger.ONE).multiply(q.subtract(BigInteger.ONE))
                .divide((p.subtract(BigInteger.ONE)).gcd(q.subtract(BigInteger.ONE))));

        final RSAPrivateKey rsaKey = (RSAPrivateKey) KeyFactory.getInstance("RSA")
                .generatePrivate(new RSAPrivateCrtKeySpec(n, e, d, p, q, dp, dq, a));

        initRsaPrivate(rsaKey);

        return n.bitLength() / 8;

    } catch (final NoSuchAlgorithmException | InvalidKeySpecException e) {
        throw new McbpCryptoException(e.toString());
    }
}