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:se.leap.bitmaskclient.ConfigHelper.java

protected static RSAPrivateKey parseRsaKeyFromString(String RsaKeyString) {
    RSAPrivateKey key = null;//w w  w  .j av  a  2s  .co m
    try {
        KeyFactory kf = KeyFactory.getInstance("RSA", "BC");

        RsaKeyString = RsaKeyString.replaceFirst("-----BEGIN RSA PRIVATE KEY-----", "")
                .replaceFirst("-----END RSA PRIVATE KEY-----", "");
        PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(Base64.decode(RsaKeyString, Base64.DEFAULT));
        key = (RSAPrivateKey) kf.generatePrivate(keySpec);
    } catch (InvalidKeySpecException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        return null;
    } catch (NoSuchAlgorithmException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        return null;
    } catch (NoSuchProviderException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        return null;
    }

    return key;
}

From source file:org.wso2.carbon.identity.test.common.testng.utils.ReadCertStoreSampleUtil.java

public static PrivateKey getSamplePrivateKey() throws Exception {
    // Read in the key into a String
    StringBuilder pkcs8Lines = new StringBuilder();
    BufferedReader rdr = new BufferedReader(new StringReader(PRIVATE_KEY));
    String line;/*from  w ww.  ja  v  a  2  s  .  c  o  m*/
    while ((line = rdr.readLine()) != null) {
        pkcs8Lines.append(line);
    }

    // Remove the "BEGIN" and "END" lines, as well as any whitespace

    String pkcs8Pem = pkcs8Lines.toString();
    pkcs8Pem = pkcs8Pem.replace("-----BEGIN PRIVATE KEY-----", "");
    pkcs8Pem = pkcs8Pem.replace("-----END PRIVATE KEY-----", "");
    pkcs8Pem = pkcs8Pem.replaceAll("\\s+", "");

    // Base64 decode the result

    byte[] pkcs8EncodedBytes = Base64.decodeBase64(pkcs8Pem);

    // extract the private key

    PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(pkcs8EncodedBytes);
    KeyFactory kf = KeyFactory.getInstance("RSA");
    return kf.generatePrivate(keySpec);
}

From source file:org.kde.kdeconnect.Helpers.SecurityHelpers.RsaHelper.java

public static PrivateKey getPrivateKey(Context context) throws Exception {

    try {//w w w . jav a 2 s  .  co  m
        SharedPreferences globalSettings = PreferenceManager.getDefaultSharedPreferences(context);
        byte[] privateKeyBytes = Base64.decode(globalSettings.getString("privateKey", ""), 0);
        PrivateKey privateKey = KeyFactory.getInstance("RSA")
                .generatePrivate(new PKCS8EncodedKeySpec(privateKeyBytes));
        return privateKey;
    } catch (Exception e) {
        throw e;
    }

}

From source file:enc_mods.aes.java

/**
* Decrypts an AES key from a file using an RSA private key
*//*  w  w w  . j  a  v a  2s.co m*/
public void loadKey(File in, File privateKeyFile) {
    try {
        // read private key to be used to decrypt the AES key
        byte[] encodedKey = new byte[(int) privateKeyFile.length()];
        new FileInputStream(privateKeyFile).read(encodedKey);

        // create private key
        PKCS8EncodedKeySpec privateKeySpec = new PKCS8EncodedKeySpec(encodedKey);
        KeyFactory kf = KeyFactory.getInstance("RSA");
        PrivateKey pk = kf.generatePrivate(privateKeySpec);

        // read AES key
        cipher.init(Cipher.DECRYPT_MODE, pk);
        key = new byte[AES_Key_Size / 8];
        CipherInputStream is = new CipherInputStream(new FileInputStream(in), cipher);
        is.read(key);
        secretkey = new SecretKeySpec(key, "AES");
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:com.shekhargulati.reactivex.rxokhttp.SslCertificates.java

private SslCertificates(final Builder builder) throws SslCertificateException {
    if ((builder.caCertPath == null) || (builder.clientCertPath == null) || (builder.clientKeyPath == null)) {
        throw new SslCertificateException(
                "caCertPath, clientCertPath, and clientKeyPath must all be specified");
    }//from  w  w w .  j  a  v a 2  s .  c o m

    try {
        final CertificateFactory cf = CertificateFactory.getInstance("X.509");
        final Certificate caCert = cf.generateCertificate(Files.newInputStream(builder.caCertPath));
        final Certificate clientCert = cf.generateCertificate(Files.newInputStream(builder.clientCertPath));

        final PEMKeyPair clientKeyPair = (PEMKeyPair) new PEMParser(
                Files.newBufferedReader(builder.clientKeyPath, Charset.defaultCharset())).readObject();

        final PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(
                clientKeyPair.getPrivateKeyInfo().getEncoded());
        final KeyFactory kf = KeyFactory.getInstance("RSA");
        final PrivateKey clientKey = kf.generatePrivate(spec);

        final KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
        trustStore.load(null, null);
        trustStore.setEntry("ca", new KeyStore.TrustedCertificateEntry(caCert), null);

        final KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
        keyStore.load(null, KEY_STORE_PASSWORD);
        keyStore.setCertificateEntry("client", clientCert);
        keyStore.setKeyEntry("key", clientKey, KEY_STORE_PASSWORD, new Certificate[] { clientCert });

        this.sslContext = SSLContexts.custom().loadTrustMaterial(trustStore)
                .loadKeyMaterial(keyStore, KEY_STORE_PASSWORD).useTLS().build();
    } catch (java.security.cert.CertificateException | IOException | NoSuchAlgorithmException
            | InvalidKeySpecException | KeyStoreException | UnrecoverableKeyException
            | KeyManagementException e) {
        throw new SslCertificateException(e);
    }
}

From source file:umu.eadmin.servicios.umu2stork.UtilesRsa.java

public PrivateKey readPrivateKey(String filename) throws IOException {
    try {/*w ww  . j  a va 2 s.  co  m*/
        logger.info("Start decoding RSA key in PEM format: " + filename);
        File keyFile = new File(filename);

        BufferedReader br = new BufferedReader(new FileReader(keyFile));
        StringBuffer keyBase64 = new StringBuffer();
        String line = br.readLine();
        while (line != null) {
            if (!(line.startsWith("-----BEGIN")) && !(line.startsWith("-----END"))) {
                keyBase64.append(line);
            }
            line = br.readLine();
        }
        br.close();
        logger.info("Decode RSA Key");
        byte[] fileBytes = new BASE64Decoder().decodeBuffer(keyBase64.toString());

        PKCS8EncodedKeySpec ks = new PKCS8EncodedKeySpec(fileBytes);
        KeyFactory kf = KeyFactory.getInstance("RSA");

        logger.info("RSA Decode End: " + filename);
        pk = kf.generatePrivate(ks);
        return (pk);
    } catch (InvalidKeySpecException ex1) {
        throw new IOException("Invalid Key Spec: " + ex1.toString());
    } catch (NoSuchAlgorithmException ex2) {
        throw new IOException("No Such Algorithm: " + ex2.toString());
    }
}

From source file:servlets.SecretKeyProvider.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods.//from  www .j  a v  a 2 s .  c  om
 *
 * @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.javaweb.utils.RSAUtils.java

/**
 * ?//www. j  av a2 s  . c  o  m
 *
 * @param privateKey
 * @return
 * @throws Exception
 */
public static PrivateKey getPrivateKey(String privateKey) throws Exception {
    byte[] keyBytes = Base64.decodeBase64(privateKey);
    PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(keyBytes);
    KeyFactory keyFactory = KeyFactory.getInstance("RSA");

    return keyFactory.generatePrivate(spec);
}

From source file:com.shekhargulati.reactivex.docker.client.ssl.DockerCertificates.java

private DockerCertificates(final Builder builder) throws DockerCertificateException {
    if ((builder.caCertPath == null) || (builder.clientCertPath == null) || (builder.clientKeyPath == null)) {
        throw new DockerCertificateException(
                "caCertPath, clientCertPath, and clientKeyPath must all be specified");
    }/* w  w w  .  j  a  v a2  s. c  om*/

    try {
        final CertificateFactory cf = CertificateFactory.getInstance("X.509");
        final Certificate caCert = cf.generateCertificate(Files.newInputStream(builder.caCertPath));
        final Certificate clientCert = cf.generateCertificate(Files.newInputStream(builder.clientCertPath));

        final PEMKeyPair clientKeyPair = (PEMKeyPair) new PEMParser(
                Files.newBufferedReader(builder.clientKeyPath, Charset.defaultCharset())).readObject();

        final PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(
                clientKeyPair.getPrivateKeyInfo().getEncoded());
        final KeyFactory kf = KeyFactory.getInstance("RSA");
        final PrivateKey clientKey = kf.generatePrivate(spec);

        final KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
        trustStore.load(null, null);
        trustStore.setEntry("ca", new KeyStore.TrustedCertificateEntry(caCert), null);

        final KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
        keyStore.load(null, KEY_STORE_PASSWORD);
        keyStore.setCertificateEntry("client", clientCert);
        keyStore.setKeyEntry("key", clientKey, KEY_STORE_PASSWORD, new Certificate[] { clientCert });

        this.sslContext = SSLContexts.custom().loadTrustMaterial(trustStore)
                .loadKeyMaterial(keyStore, KEY_STORE_PASSWORD).useTLS().build();
    } catch (CertificateException | IOException | NoSuchAlgorithmException | InvalidKeySpecException
            | KeyStoreException | UnrecoverableKeyException | KeyManagementException e) {
        throw new DockerCertificateException(e);
    }
}

From source file:com.sammyun.util.RSAUtils.java

/**
 * RSA??/*from w  w w  .  jav a2 s  . co m*/
 * 
 * @param content ???
 * @param privateKey ?
 * @param input_charset ??
 * @return ??
 */
public static String sign(String content, String privateKey, String input_charset) {
    try {
        PKCS8EncodedKeySpec priPKCS8 = new PKCS8EncodedKeySpec(Base64Util.decode(privateKey));
        KeyFactory keyf = KeyFactory.getInstance("RSA");
        PrivateKey priKey = keyf.generatePrivate(priPKCS8);
        java.security.Signature signature = java.security.Signature.getInstance(SIGN_ALGORITHMS);
        signature.initSign(priKey);
        signature.update(content.getBytes(input_charset));
        byte[] signed = signature.sign();
        return Base64Util.encode(signed);
    } catch (Exception e) {
        e.printStackTrace();
    }

    return null;
}