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.diorite.impl.auth.yggdrasil.YggdrasilSessionService.java

public YggdrasilSessionService(final Proxy proxy, final String clientToken) {
    this.proxy = proxy;
    this.clientToken = clientToken;
    try {/*  w  ww .  j  av  a2  s  .co  m*/
        //noinspection HardcodedFileSeparator
        final KeySpec spec = new X509EncodedKeySpec(IOUtils.toByteArray(
                YggdrasilSessionService.class.getResourceAsStream("/yggdrasil_session_pubkey.der")));
        final KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        this.publicKey = keyFactory.generatePublic(spec);
    } catch (final Exception e) {
        //noinspection HardcodedFileSeparator
        throw new Error("Missing/invalid yggdrasil public key!");
    }
}

From source file:compiler.downloader.MegaHandler.java

private int login_process(JSONObject json, long[] password_aes) throws IOException {

    String master_key_b64 = null;
    try {/*from   w  w w  . j a va  2 s .c  o m*/
        master_key_b64 = json.getString("k");
    } catch (JSONException e) {
        e.printStackTrace();
    }
    if (master_key_b64 == null || master_key_b64.isEmpty()) {
        return -1;
    }

    long[] encrypted_master_key = MegaCrypt.base64_to_a32(master_key_b64);
    master_key = MegaCrypt.decrypt_key(encrypted_master_key, password_aes);

    if (json.has("csid")) {
        String encrypted_rsa_private_key_b64 = null;
        try {
            encrypted_rsa_private_key_b64 = json.getString("privk");
        } catch (JSONException e) {
            e.printStackTrace();
        }

        long[] encrypted_rsa_private_key = MegaCrypt.base64_to_a32(encrypted_rsa_private_key_b64);
        long[] rsa_private_key = MegaCrypt.decrypt_key(encrypted_rsa_private_key, master_key);
        String private_key = MegaCrypt.a32_to_str(rsa_private_key);

        BigInteger[] rsa_private_key1 = new BigInteger[4];
        for (int i = 0; i < 4; i++) {
            int l = ((((int) private_key.charAt(0)) * 256 + ((int) private_key.charAt(1)) + 7) / 8) + 2;
            rsa_private_key1[i] = MegaCrypt.mpi_to_int(private_key.substring(0, l));
            private_key = private_key.substring(l);
        }

        BigInteger encrypted_sid = null;
        try {
            encrypted_sid = MegaCrypt.mpi_to_int(MegaCrypt.base64_url_decode(json.getString("csid")));
        } catch (JSONException e) {
            e.printStackTrace();
        }

        BigInteger modulus = rsa_private_key1[0].multiply(rsa_private_key1[1]);
        BigInteger privateExponent = rsa_private_key1[2];

        BigInteger sid = null;
        try {
            PrivateKey privateKey = KeyFactory.getInstance("RSA")
                    .generatePrivate(new RSAPrivateKeySpec(modulus, privateExponent));
            Cipher cipher = Cipher.getInstance("RSA/ECB/NoPadding");
            cipher.init(Cipher.DECRYPT_MODE, privateKey);
            // PyCrypt can handle >256 bit length... what the fuck... sometimes i get 257
            if (encrypted_sid.toByteArray().length > 256) {
                Random rg = new Random();
                sequence_number = rg.nextInt(Integer.MAX_VALUE);
                return -2; // lets get a new seession
            }
            sid = new BigInteger(cipher.doFinal(encrypted_sid.toByteArray()));
        } catch (Exception e) {
            e.printStackTrace();
            return -1;
        }

        String sidS = sid.toString(16);
        if (sidS.length() % 2 != 0) {
            sidS = "0" + sidS;
        }
        try {
            byte[] sidsnohex = MegaCrypt.decodeHexString(sidS);
            this.sid = MegaCrypt.base64_url_encode(new String(sidsnohex, "ISO-8859-1").substring(0, 43));
        } catch (Exception e) {
            e.printStackTrace();
            return -1;
        }
    }
    return 0;
}

From source file:com.hhi.bigdata.platform.push.client.RegisterUtil.java

/**
 * <pre>/* ww w . java 2s  .co m*/
 * create a SSLSocketFactory instance with given parameters
 * </pre>
 * @param keystore
 * @param password
 * @return
 * @throws IOException
 */
private static PrivateKey getPrivateKey(URI keyFile) throws Exception {
    InputStream privKeyIs = new FileInputStream(new File(keyFile));
    PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(IOUtils.toByteArray(privKeyIs));
    KeyFactory keyFactory = KeyFactory.getInstance("RSA");

    return keyFactory.generatePrivate(keySpec);
}

From source file:com.buzzcoders.security.cryptoutils.asymmetric.AbstractAsymmetricEncryptionModule.java

public PrivateKey loadPrivateKey(String path) {
    FileInputStream fis = null;//from   w w  w.jav a  2  s . c o m
    try {
        File filePrivateKey = new File(path);
        fis = new FileInputStream(path);
        byte[] encodedPrivateKey = new byte[(int) filePrivateKey.length()];
        fis.read(encodedPrivateKey);
        KeyFactory keyFactory = KeyFactory.getInstance(getAlgorithm());
        PKCS8EncodedKeySpec privateKeySpec = new PKCS8EncodedKeySpec(encodedPrivateKey);
        PrivateKey privateKey = keyFactory.generatePrivate(privateKeySpec);
        return privateKey;
    } catch (Exception e) {
        LOG.error("An error occurred while loading the private key from disk.", e);
    } finally {
        IOUtils.closeQuietly(fis);
    }
    return null;
}

From source file:com.forsrc.utils.MyRsa2Utils.java

/**
 * Gets public key.//from  w w  w .  j  ava 2s . c  om
 *
 * @param key the key
 * @return the public key
 * @throws RsaException the rsa exception
 */
public static PublicKey getPublicKey(String key) throws RsaException {
    byte[] keyBytes;
    try {
        keyBytes = (new Base64()).decode(key);
    } catch (Exception e) {
        throw new RsaException(e);
    }
    X509EncodedKeySpec keySpec = new X509EncodedKeySpec(keyBytes);
    KeyFactory keyFactory = null;
    try {
        keyFactory = KeyFactory.getInstance(RsaKey.ALGORITHM);
    } catch (NoSuchAlgorithmException e) {
        throw new RsaException(e);
    }
    PublicKey publicKey = null;
    try {
        publicKey = keyFactory.generatePublic(keySpec);
    } catch (InvalidKeySpecException e) {
        throw new RsaException(e);
    }
    return publicKey;
}

From source file:net.unicon.cas.support.wsfederation.WsFederationUtils.java

/**
 * getSigningCredential loads up an X509Credential from a file.
 *
 * @param resource the signing certificate file
 * @return an X509 credential/* ww w .  j a va  2  s  .  c om*/
 */
public static X509Credential getSigningCredential(final Resource resource) {
    try (final InputStream inputStream = resource.getInputStream()) {
        //grab the certificate file
        final CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
        final X509Certificate certificate = (X509Certificate) certificateFactory
                .generateCertificate(inputStream);

        //get the public key from the certificate
        final X509EncodedKeySpec publicKeySpec = new X509EncodedKeySpec(
                certificate.getPublicKey().getEncoded());

        //generate public key to validate signatures
        final KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        final PublicKey publicKey = keyFactory.generatePublic(publicKeySpec);

        //add the public key
        final BasicX509Credential publicCredential = new BasicX509Credential();
        publicCredential.setPublicKey(publicKey);
        LOGGER.debug("getSigningCredential: key retrieved.");
        return publicCredential;
    } catch (final Exception ex) {
        LOGGER.error("I/O error retrieving the signing cert: {}", ex);
        return null;
    }
}

From source file:MegaHandler.java

private int login_process(JSONObject json, long[] password_aes) throws IOException {

    String master_key_b64 = null;
    try {//from  w  w  w .j  av  a 2s .  com
        master_key_b64 = json.getString("k");
    } catch (JSONException e) {
        e.printStackTrace();
    }
    if (master_key_b64 == null || master_key_b64.isEmpty())
        return -1;

    long[] encrypted_master_key = MegaCrypt.base64_to_a32(master_key_b64);
    master_key = MegaCrypt.decrypt_key(encrypted_master_key, password_aes);

    if (json.has("csid")) {
        String encrypted_rsa_private_key_b64 = null;
        try {
            encrypted_rsa_private_key_b64 = json.getString("privk");
        } catch (JSONException e) {
            e.printStackTrace();
        }

        long[] encrypted_rsa_private_key = MegaCrypt.base64_to_a32(encrypted_rsa_private_key_b64);
        long[] rsa_private_key = MegaCrypt.decrypt_key(encrypted_rsa_private_key, master_key);
        String private_key = MegaCrypt.a32_to_str(rsa_private_key);

        this.rsa_private_key = new BigInteger[4];
        for (int i = 0; i < 4; i++) {
            int l = ((((int) private_key.charAt(0)) * 256 + ((int) private_key.charAt(1)) + 7) / 8) + 2;
            this.rsa_private_key[i] = MegaCrypt.mpi_to_int(private_key.substring(0, l));
            private_key = private_key.substring(l);
        }

        BigInteger encrypted_sid = null;
        try {
            encrypted_sid = MegaCrypt.mpi_to_int(MegaCrypt.base64_url_decode(json.getString("csid")));
        } catch (JSONException e) {
            e.printStackTrace();
        }

        BigInteger modulus = this.rsa_private_key[0].multiply(this.rsa_private_key[1]);
        BigInteger privateExponent = this.rsa_private_key[2];

        BigInteger sid = null;
        try {
            PrivateKey privateKey = KeyFactory.getInstance("RSA")
                    .generatePrivate(new RSAPrivateKeySpec(modulus, privateExponent));
            Cipher cipher = Cipher.getInstance("RSA/ECB/NoPadding");
            cipher.init(Cipher.DECRYPT_MODE, privateKey);
            // PyCrypt can handle >256 bit length... what the fuck... sometimes i get 257
            if (encrypted_sid.toByteArray().length > 256) {
                Random rg = new Random();
                sequence_number = rg.nextInt(Integer.MAX_VALUE);
                return -2; // lets get a new seession
            }
            sid = new BigInteger(cipher.doFinal(encrypted_sid.toByteArray()));
        } catch (Exception e) {
            e.printStackTrace();
            return -1;
        }

        String sidS = sid.toString(16);
        if (sidS.length() % 2 != 0)
            sidS = "0" + sidS;
        try {
            byte[] sidsnohex = MegaCrypt.decodeHexString(sidS);
            this.sid = MegaCrypt.base64_url_encode(new String(sidsnohex, "ISO-8859-1").substring(0, 43));
        } catch (Exception e) {
            e.printStackTrace();
            return -1;
        }
    }
    return 0;
}

From source file:com.streamsets.datacollector.publicrestapi.CredentialsDeploymentResource.java

private boolean validateSignature(CredentialsBeanJson credentialsBeanJson)
        throws NoSuchAlgorithmException, InvalidKeySpecException, InvalidKeyException, SignatureException {
    // getProperty so we can test it
    String publicKey = Preconditions.checkNotNull(System.getProperty(DPM_AGENT_PUBLIC_KEY));

    X509EncodedKeySpec kspec = new X509EncodedKeySpec(Base64.getDecoder().decode(publicKey));
    KeyFactory kf = KeyFactory.getInstance("RSA");
    PublicKey key = kf.generatePublic(kspec);
    Signature sig = Signature.getInstance("SHA256withRSA");
    sig.initVerify(key);//from   w  w  w .j a va2  s  .co m
    sig.update(credentialsBeanJson.getToken().getBytes(Charsets.UTF_8));
    LOG.info("Token : {}, Signature {}", credentialsBeanJson.getToken(),
            credentialsBeanJson.getTokenSignature());
    return sig.verify(Base64.getDecoder().decode(credentialsBeanJson.getTokenSignature()));
}

From source file:org.eclipse.che.ide.ext.datasource.server.ssl.KeyStoreObject.java

public void addNewKey(String alias, Iterator<FileItem> uploadedFilesIterator) throws Exception {
    PrivateKey privateKey = null;
    Certificate[] certs = null;//w  ww .  jav a 2 s .  c o  m
    while (uploadedFilesIterator.hasNext()) {
        FileItem fileItem = uploadedFilesIterator.next();
        if (!fileItem.isFormField()) {
            if ("keyFile".equals(fileItem.getFieldName())) {
                KeyFactory kf = KeyFactory.getInstance("RSA");
                privateKey = kf.generatePrivate(new PKCS8EncodedKeySpec(fileItem.get()));
            }
            if ("certFile".equals(fileItem.getFieldName())) {
                CertificateFactory cf = CertificateFactory.getInstance("X.509");
                certs = cf.generateCertificates(fileItem.getInputStream()).toArray(new Certificate[] {});
            }
        }
    }

    if (privateKey == null || certs == null) {
        throw new WebApplicationException(
                Response.ok("<pre>Can't find input file.</pre>", MediaType.TEXT_HTML).build());
    }

    keystore.setKeyEntry(alias, privateKey, keyStorePassword.toCharArray(), certs);
    save();
}

From source file:io.kodokojo.config.module.SecurityModule.java

@Provides
@Singleton/*  w  ww .  ja v a 2s  .c om*/
SSLKeyPair provideSSLKeyPair(SecurityConfig securityConfig) {
    if (securityConfig == null) {
        throw new IllegalArgumentException("securityConfig must be defined.");
    }
    if (StringUtils.isNotBlank(securityConfig.wildcardPemPath())) {

        File pemFile = new File(securityConfig.wildcardPemPath());
        try {
            String content = IOUtils.toString(new FileReader(pemFile));
            String contentPrivate = RSAUtils.extractPrivateKey(content);
            String contentPublic = RSAUtils.extractPublic(content);

            RSAPrivateKey rsaPrivateKey = RSAUtils.readRsaPrivateKey(new StringReader(contentPrivate));
            X509Certificate certificate = RSAUtils.readRsaPublicKey(new StringReader(contentPublic));
            RSAPublicKey rsaPublicKey = (RSAPublicKey) certificate.getPublicKey();

            X509Certificate[] certificates = new X509Certificate[1];
            certificates[0] = certificate;
            LOGGER.info(
                    "Using Wildcard SSL certificat {} from path {}to provide Certificat to all instances of Kodo Kojo. ",
                    certificate.getSubjectDN().toString(), securityConfig.wildcardPemPath());
            return new SSLKeyPair(rsaPrivateKey, rsaPublicKey, certificates);
        } catch (IOException e) {
            throw new IllegalArgumentException("Unable to read pem file " + pemFile.getAbsolutePath() + ".", e);
        }
    } else {
        try {
            KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
            ks.load(new FileInputStream(System.getProperty("javax.net.ssl.keyStore")),
                    System.getProperty("javax.net.ssl.keyStorePassword", "").toCharArray());

            RSAPrivateCrtKey key = (RSAPrivateCrtKey) ks.getKey(securityConfig.sslRootCaKsAlias(),
                    securityConfig.sslRootCaKsPassword().toCharArray());
            if (key == null) {
                return null;
            }

            RSAPublicKeySpec publicKeySpec = new RSAPublicKeySpec(key.getModulus(), key.getPublicExponent());

            KeyFactory keyFactory = KeyFactory.getInstance("RSA");
            RSAPublicKey publicKey = (RSAPublicKey) keyFactory.generatePublic(publicKeySpec);
            Certificate[] certificateChain = ks.getCertificateChain(securityConfig.sslRootCaKsAlias());
            List<X509Certificate> x509Certificates = Arrays.asList(certificateChain).stream()
                    .map(c -> (X509Certificate) c).collect(Collectors.toList());
            LOGGER.info(
                    "Using a CA SSL certificat {} from keystore  to provide Certificat to all instances of Kodo Kojo. ",
                    securityConfig.sslRootCaKsAlias(), System.getProperty("javax.net.ssl.keyStore"));
            return new SSLKeyPair(key, publicKey,
                    x509Certificates.toArray(new X509Certificate[x509Certificates.size()]));
        } catch (UnrecoverableKeyException | NoSuchAlgorithmException | KeyStoreException
                | InvalidKeySpecException | CertificateException | IOException e) {

            throw new RuntimeException("Unable to open default Keystore", e);
        }
    }
}