parse RSA Private Key - Java Security

Java examples for Security:RSA

Description

parse RSA Private Key

Demo Code


//package com.java2s;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.security.KeyFactory;
import java.security.NoSuchAlgorithmException;
import java.security.interfaces.RSAPrivateKey;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.PKCS8EncodedKeySpec;
import sun.misc.BASE64Decoder;

public class Main {
    public static RSAPrivateKey parsePrivateKey(String file) {

        try {//from   www .  ja v a 2s  .  co  m
            File privateKeyFile = new File(file);
            byte[] encodedKey = new byte[(int) privateKeyFile.length()];
            FileInputStream fis = new FileInputStream(privateKeyFile);
            fis.read(encodedKey);
            fis.close();

            ByteBuffer keyBytes = new BASE64Decoder()
                    .decodeBufferToByteBuffer(encodedKey.toString());
            PKCS8EncodedKeySpec privateKeySpec = new PKCS8EncodedKeySpec(
                    keyBytes.array());
            KeyFactory kf = KeyFactory.getInstance("RSA");// , "IBMJCEFIPS");
            RSAPrivateKey pk = (RSAPrivateKey) kf
                    .generatePrivate(privateKeySpec);
            return pk;
        } catch (FileNotFoundException e) {
            throw new RuntimeException(e);
        } catch (IOException e) {
            throw new RuntimeException(e);
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException(e);
        } catch (InvalidKeySpecException e) {
            throw new RuntimeException(e);
        }

        // String data = new String(IOUtil.readFile(file));
        // data = data.replaceAll("\\\\r", "");
        // data = data.replaceAll("\\\\n", "");
        //
        // StringSeq ss = new StringSeq(data);
        // ss.a("-----BEGIN RSA PRIVATE KEY-----");
        // String r = ss.a("-----END RSA PRIVATE KEY-----");
        // byte[] decoded = decode(r.getBytes());
        // return new BigInteger(decoded);
    }
}

Related Tutorials