Example usage for java.security.spec PKCS8EncodedKeySpec PKCS8EncodedKeySpec

List of usage examples for java.security.spec PKCS8EncodedKeySpec PKCS8EncodedKeySpec

Introduction

In this page you can find the example usage for java.security.spec PKCS8EncodedKeySpec PKCS8EncodedKeySpec.

Prototype

public PKCS8EncodedKeySpec(byte[] encodedKey) 

Source Link

Document

Creates a new PKCS8EncodedKeySpec with the given encoded key.

Usage

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

public static Key readKeyFromFile(boolean readPublicKey) {
    String keyPath = MainApp.getStoragePath() + File.separator + MainApp.getDataFolder() + File.separator
            + KEYPAIR_FOLDER;//from   w  ww.j  a v a  2s.  c  om

    String privateKeyPath = keyPath + File.separator + KEYPAIR_FILE_NAME + KEYPAIR_PRIV_EXTENSION;
    String publicKeyPath = keyPath + File.separator + KEYPAIR_FILE_NAME + KEYPAIR_PUB_EXTENSION;

    String path;

    if (readPublicKey) {
        path = publicKeyPath;
    } else {
        path = privateKeyPath;
    }

    FileInputStream fileInputStream = null;
    try {
        fileInputStream = new FileInputStream(path);
        byte[] bytes = new byte[fileInputStream.available()];
        fileInputStream.read(bytes);
        fileInputStream.close();

        KeyFactory keyFactory = KeyFactory.getInstance("RSA");

        if (readPublicKey) {
            X509EncodedKeySpec keySpec = new X509EncodedKeySpec(bytes);
            return keyFactory.generatePublic(keySpec);
        } else {
            PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(bytes);
            return keyFactory.generatePrivate(keySpec);
        }

    } catch (FileNotFoundException e) {
        Log_OC.d(TAG, "Failed to find path while reading the Key");
    } catch (IOException e) {
        Log_OC.d(TAG, "IOException while reading the key");
    } catch (InvalidKeySpecException e) {
        Log_OC.d(TAG, "InvalidKeySpecException while reading the key");
    } catch (NoSuchAlgorithmException e) {
        Log_OC.d(TAG, "RSA algorithm not supported");
    }

    return null;
}

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

private void generateCertificateSigningRequest(Integer infrastructureId, HttpServletResponse response)
        throws IOException {

    PrintWriter out = response.getWriter();

    try {/*ww  w. java 2  s  .com*/

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

        String CN = infrastructure.getCommonName();
        String OU = infrastructure.getOrganizationalUnit();
        String O = infrastructure.getOrganization();
        String L = infrastructure.getLocality();
        String S = infrastructure.getState();
        String C = infrastructure.getCountry();

        Base64 base64 = new Base64();
        byte[] pubKey = base64.decode(infrastructure.getBase64EncodedPublicKey());
        byte[] privKey = base64.decode(infrastructure.getBase64EncodedPrivateKey());

        PublicKey publicKey = KeyFactory.getInstance("RSA").generatePublic(new X509EncodedKeySpec(pubKey));
        PrivateKey privateKey = KeyFactory.getInstance("RSA").generatePrivate(new PKCS8EncodedKeySpec(privKey));

        CertificateIdentifier principal = new CertificateIdentifier(CN, OU, O, L, S, C);
        PKCS10CertificationRequest request = SslUtility.generatePKCS10(publicKey, privateKey, principal);
        String csr = SslUtility.generateCSR(request);
        out.println(csr);
    } catch (NumberFormatException e) {
        out.println(e);
    } catch (InvalidKeySpecException e) {
        out.println(e);
    } catch (NoSuchAlgorithmException e) {
        out.println(e);
    } catch (SslException e) {
        out.println(e);
    }
}

From source file:com.gamesalutes.utils.EncryptUtils.java

/**
 * Reads a PKCS8 formatted private key from file.
 * // ww  w.j  a v  a 2 s  .co  m
 * @param in the <code>InputStream</code> containing the key
 * @param alg the key algorithm
 * @return the read key
 * @throws Exception if error occurs reading the key
 */
public static PrivateKey readPKCS8(InputStream in, String alg) throws Exception {
    try {
        if (alg == null)
            throw new NullPointerException("alg");
        //alg = alg.toUpperCase();
        //if(!alg.equals("DSA") || !alg.equals("RSA"))
        //   throw new IllegalArgumentException("Illegal key alg=" + alg);
        byte[] encodedKey = ByteUtils.readBytes(in);
        KeyFactory kf = KeyFactory.getInstance(alg);
        try {
            return kf.generatePrivate(new PKCS8EncodedKeySpec(encodedKey));
        } catch (Exception e) {
            // maybe key was in PEM so convert to binary
            encodedKey = EncryptUtils.fromPemtoBinary(encodedKey);
            return kf.generatePrivate(new PKCS8EncodedKeySpec(encodedKey));
        }
    } finally {
        MiscUtils.closeStream(in);
    }
}

From source file:org.umit.icm.mobile.utils.RSACrypto.java

/**
* Converts a {@link String} to {@link PrivateKey}.
*    /*www  . j a v a2 s  . c om*/
                             
@param  privateKeyString  An object of the type {@link String}
*                                  
        
@return  {@link PrivateKey}
* 
        
@see         PKCS8EncodedKeySpec
*
        
@see         KeyFactory
*/
public static PrivateKey stringToPrivateKey(String privateKeyString)
        throws NoSuchAlgorithmException, InvalidKeySpecException {
    PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(Base64.decodeBase64(privateKeyString.getBytes()));
    KeyFactory keyFactory = KeyFactory.getInstance("RSA");
    return keyFactory.generatePrivate(spec);
}

From source file:com.hpe.elderberry.TaxiiConnection.java

/**
 * a convenient way to externally cache the key store is to create it from PEMs using
 * {@link #setPrivateKeyPem(String)} and {@link #setClientCertificatePemChain(List)} then obtaining it with this method and
 * storing it for future use.<p>/*  w ww  .  jav  a  2s  .  com*/
 * This method attempts to retrieve the key store in the following algorithm:
 * <ul>
 * <li>When it was already loaded or constructed it's returned</li>
 * <li>When it was directly set by {@link #setKeyStore(KeyStore, String)} then this key store is returned</li>
 * <li>When a key store file and password was set by {@link #setKeyStoreFile(File)} and
 * {@link #setKeyStorePassword(String)}, then the key store is loaded from the file and returned</li>
 * <li>When a private key was set by {@link #setPrivateKeyPem(String)} and its certificate chain was set by
 * {@link #setClientCertificatePemChain(List)} then a new key store is created, the private key material and the
 * client certificates are loaded into it, then this new key store is returned</li>
 * </ul>
 *
 * @return the key store
 */
public KeyStore getKeyStore() {
    if (keyStore != null) {
        return keyStore;
    }

    if (keyStoreFile != null) {
        try {
            keyStore = getInstance("JKS");
            keyStore.load(newInputStream(keyStoreFile.toPath()),
                    keyStorePassword == null ? "".toCharArray() : keyStorePassword.toCharArray());
        } catch (Exception e) {
            throw new RuntimeException("a key store file was set, but it could not be read, " + e.getMessage(),
                    e);
        }
    } else if (!isEmpty(privateKeyPem)) {
        try {
            // initialize an empty key store
            keyStore = getInstance("JKS");
            keyStore.load(null);

            // generate a random password for the private key
            keyPassword = randomUUID().toString().toCharArray();

            // load the private key
            byte[] key = parseBase64Binary(privateKeyPem.replaceAll("-+.*-+", ""));
            PrivateKey privateKey = KeyFactory.getInstance("RSA").generatePrivate(new PKCS8EncodedKeySpec(key));
            if (clientCertificatePemChain != null) {
                List<Certificate> chain = addPemsToStore(keyStore, clientCertificatePemChain);
                keyStore.setKeyEntry(randomUUID().toString(), privateKey, keyPassword,
                        chain.toArray(new Certificate[chain.size()]));
            } else {
                keyStore.setKeyEntry(randomUUID().toString(), privateKey, keyPassword, new Certificate[] {});
            }
        } catch (Exception e) {
            throw new RuntimeException("unable to create key store, " + e.getMessage(), e);
        }
    }

    return keyStore;
}

From source file:jef.tools.security.EncrypterUtil.java

/**
 * PKCS8/*from w  w  w.  j  a  v a 2  s.  c  om*/
 * 
 * @param f
 * @param algom
 *            
 * @param isPublic
 *            true?false??
 * @return
 */
public static Key loadPKCS8Key(File f, String algom, boolean isPublic) {
    try {
        byte[] keyData = IOUtils.toByteArray(f);
        PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(keyData);
        KeyFactory keyFactory = KeyFactory.getInstance(algom);
        Key result = (isPublic) ? keyFactory.generatePublic(keySpec) : keyFactory.generatePrivate(keySpec);
        return result;
    } catch (IOException e) {
        throw new RuntimeException(e);
    } catch (GeneralSecurityException e) {
        throw new RuntimeException(e);
    }
}

From source file:com.linkedin.drelephant.clients.azkaban.AzkabanWorkflowClient.java

/**
 * Decodes the encoded password using the _privateKey
 * @param encodedPassword/* w w  w  .jav  a 2s  .  c  o  m*/
 * @param _privateKey
 * @return The decoded password
 * @throws IOException
 * @throws NoSuchAlgorithmException
 * @throws InvalidKeySpecException
 * @throws NoSuchPaddingException
 * @throws InvalidKeyException
 * @throws IllegalBlockSizeException
 * @throws BadPaddingException
 */
private String decodeHeadlessChallenge(String encodedPassword, File _privateKey)
        throws IOException, NoSuchAlgorithmException, InvalidKeySpecException, NoSuchPaddingException,
        InvalidKeyException, IllegalBlockSizeException, BadPaddingException {

    final String RSA = "RSA";
    final String ASCII = "US-ASCII";

    // Read private key from file
    FileInputStream fstream = new FileInputStream(_privateKey);
    byte[] sshPrivateKey = IOUtils.toByteArray(fstream);
    PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(sshPrivateKey);
    KeyFactory kf = KeyFactory.getInstance(RSA);
    PrivateKey privateKey = kf.generatePrivate(keySpec);

    // Init RSA decrypter with private key
    Cipher decryptCipher = Cipher.getInstance(RSA);
    decryptCipher.init(2, privateKey);

    // Convert base 64 password string to raw bytes
    byte[] rawBytes = org.apache.commons.codec.binary.Base64.decodeBase64(encodedPassword.getBytes(ASCII));

    // Decrypt the encoded raw bytes using decrypter
    byte[] decodedBytes = decryptCipher.doFinal(rawBytes);

    // Return decoded bytes as string
    return new String(decodedBytes, ASCII);
}

From source file:com.jrummyapps.busybox.signing.ZipSigner.java

/** Read a PKCS 8 format private key. */
private static PrivateKey readPrivateKey(InputStream file) throws IOException, GeneralSecurityException {
    final DataInputStream input = new DataInputStream(file);
    try {/*from   w w w .jav  a 2  s .c  o m*/
        byte[] bytes = new byte[10000];
        int nBytesTotal = 0, nBytes;
        while ((nBytes = input.read(bytes, nBytesTotal, 10000 - nBytesTotal)) != -1) {
            nBytesTotal += nBytes;
        }

        final byte[] bytes2 = new byte[nBytesTotal];
        System.arraycopy(bytes, 0, bytes2, 0, nBytesTotal);
        bytes = bytes2;

        KeySpec spec = decryptPrivateKey(bytes);
        if (spec == null) {
            spec = new PKCS8EncodedKeySpec(bytes);
        }

        try {
            return KeyFactory.getInstance("RSA").generatePrivate(spec);
        } catch (final InvalidKeySpecException ex) {
            return KeyFactory.getInstance("DSA").generatePrivate(spec);
        }
    } finally {
        input.close();
    }
}

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;/*w  w  w.j  a v  a2s  . c  o  m*/
    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:org.hyperledger.fabric.sdk.security.CryptoPrimitivesTest.java

@Before
public void setUp() throws Exception {
    // TODO should do this in @BeforeClass. Need to find out how to get to
    // files from static junit method
    BufferedInputStream bis = new BufferedInputStream(this.getClass().getResourceAsStream("/ca.crt"));
    testCACert = cf.generateCertificate(bis);
    bis.close();//from   ww  w .j a  v a2 s.c  o  m
    crypto.addCACertificateToTrustStore(testCACert, "ca");

    bis = new BufferedInputStream(this.getClass().getResourceAsStream("/keypair-signed.crt"));
    Certificate cert = cf.generateCertificate(bis);
    bis.close();

    // TODO: get PEM file without dropping down to BouncyCastle ?
    PEMParser pem = new PEMParser(new FileReader(this.getClass().getResource("/keypair-signed.key").getFile()));
    PEMKeyPair bcKeyPair = (PEMKeyPair) pem.readObject();
    PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(bcKeyPair.getPrivateKeyInfo().getEncoded());
    PrivateKey key = kf.generatePrivate(keySpec);

    Certificate[] certificates = new Certificate[] { cert, testCACert };
    crypto.getTrustStore().setKeyEntry("key", key, "123456".toCharArray(), certificates);
    pem.close();
}