Example usage for java.security KeyFactory generatePrivate

List of usage examples for java.security KeyFactory generatePrivate

Introduction

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

Prototype

public final PrivateKey generatePrivate(KeySpec keySpec) throws InvalidKeySpecException 

Source Link

Document

Generates a private key object from the provided key specification (key material).

Usage

From source file:com.cellngine.crypto.RSACipher.java

private PrivateKey getPrivateKey(final RSAPrivateKeySpec keySpec) {
    final KeyFactory factory = this.getKeyFactory();

    try {/*ww w .  jav  a 2 s .c o m*/
        return factory.generatePrivate(keySpec);
    } catch (final InvalidKeySpecException e) {
        LOG.error("Unable to get key spec from factory", e);
        return null;
    }
}

From source file:com.adito.security.pki.dsa.SshDssPrivateKey.java

/**
 * Creates a new SshDssPrivateKey object.
 *
 * @param key//  w  ww . ja  v a 2s  .  c  om
 *
 * @throws InvalidKeyException
 */
public SshDssPrivateKey(byte[] key) throws InvalidKeyException {
    try {
        DSAPrivateKeySpec dsaKey;

        // Extract the key information
        ByteArrayReader bar = new ByteArrayReader(key);
        String header = bar.readString();

        if (!header.equals(getAlgorithmName())) {
            throw new InvalidKeyException();
        }

        BigInteger p = bar.readBigInteger();
        BigInteger q = bar.readBigInteger();
        BigInteger g = bar.readBigInteger();
        BigInteger x = bar.readBigInteger();
        dsaKey = new DSAPrivateKeySpec(x, p, q, g);

        KeyFactory kf = KeyFactory.getInstance("DSA");
        prvkey = (DSAPrivateKey) kf.generatePrivate(dsaKey);
    } catch (Exception e) {
        throw new InvalidKeyException();
    }
}

From source file:bftsmart.reconfiguration.util.RSAKeyLoaderO.java

private PrivateKey getPrivateKeyFromString(String key) throws Exception {

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

    EncodedKeySpec privateKeySpec = new PKCS8EncodedKeySpec(Base64.decodeBase64(key));

    PrivateKey privateKey = keyFactory.generatePrivate(privateKeySpec);

    return privateKey;

}

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

public PrivateKey readPrivateKey(String filename) throws IOException {
    try {/*w  ww  .  j  a  v a 2s. com*/
        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:sec_algo.commonenc.java

/**
* Decrypts an AES key from a file using an RSA private key
*//*from  w w w . ja v a 2 s  . c  o 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
        pkCipher.init(Cipher.DECRYPT_MODE, pk);
        key = new byte[AES_Key_Size / 8];
        CipherInputStream is = new CipherInputStream(new FileInputStream(in), pkCipher);
        is.read(key);
        secretkey = new SecretKeySpec(key, "AES");
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:com.sshtools.j2ssh.transport.publickey.dsa.SshDssPrivateKey.java

/**
 * Creates a new SshDssPrivateKey object.
 *
 * @param key/* ww  w  . j a  v  a 2 s  .  c  o m*/
 *
 * @throws InvalidSshKeyException
 */
public SshDssPrivateKey(byte[] key) throws InvalidSshKeyException {
    try {
        DSAPrivateKeySpec dsaKey;

        // Extract the key information
        ByteArrayReader bar = new ByteArrayReader(key);

        String header = bar.readString();

        if (!header.equals(getAlgorithmName())) {
            throw new InvalidSshKeyException();
        }

        BigInteger p = bar.readBigInteger();
        BigInteger q = bar.readBigInteger();
        BigInteger g = bar.readBigInteger();
        BigInteger x = bar.readBigInteger();

        dsaKey = new DSAPrivateKeySpec(x, p, q, g);

        KeyFactory kf = KeyFactory.getInstance("DSA");
        prvkey = (DSAPrivateKey) kf.generatePrivate(dsaKey);

        log.info(prvkey.getParams().getP().toString(16));
        log.info(prvkey.getParams().getQ().toString(16));
        log.info(prvkey.getParams().getG().toString(16));
        log.info(getY().toString(16));

    } catch (Exception e) {
        throw new InvalidSshKeyException();
    }
}

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

public PrivateKey loadPrivateKey(String path) {
    FileInputStream fis = null;/*ww  w .  j a va 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.brienwheeler.apps.tomcat.TomcatBean.java

private RSAPrivateKey readKeyFile() throws IOException, NoSuchAlgorithmException, InvalidKeySpecException {
    String parse[] = readPEMFile(sslKeyFile, KEY_PATTERN, 2);
    if (parse == null)
        throw new IllegalArgumentException("invalid key file contents");

    if (parse[0].length() == 0) { // BEGIN PRIVATE KEY
        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        return (RSAPrivateKey) keyFactory.generatePrivate(new PKCS8EncodedKeySpec(Base64.decode(parse[1])));
    }/*from   w w w  .j  a v a 2s. c  o  m*/

    if (parse[0].contains("RSA")) { // BEGIN RSA PRIVATE KEY
        Security.addProvider(new BouncyCastleProvider());

        PEMParser pemParser = new PEMParser(new FileReader(sslKeyFile));
        Object parsedObject = pemParser.readObject();
        if (!(parsedObject instanceof PEMKeyPair))
            throw new IllegalArgumentException("invalid key file contents");

        PEMKeyPair keyPair = (PEMKeyPair) parsedObject;
        RSAPrivateKey privateKey = (RSAPrivateKey) BouncyCastleProvider
                .getPrivateKey(keyPair.getPrivateKeyInfo());
        if (privateKey == null)
            throw new IllegalArgumentException("invalid key file contents");
        return privateKey;
    }

    throw new IllegalArgumentException("invalid key file contents");
}

From source file:org.ejbca.ui.cli.ca.CaImportCVCCACommand.java

public void execute(String[] args) throws ErrorAdminCommandException {
    if (args.length < 4) {
        getLogger().info("Description: " + getDescription());
        getLogger().info(//from   w  w  w  .ja v a 2 s  .  c  om
                "Usage 1: " + getCommand() + " <CA name> <pkcs8 RSA private key file> <certificate file>");
        getLogger().info(" Imports a private key and a self signed CVCA certificate and creates a CVCA.");
        getLogger().info("Usage 2: " + getCommand()
                + " <CA name> <pkcs8 private key file> <certificate file> <DN of form C=country,CN=mnemonic,SERIALNUMBER=sequence> <signatureAlgorithm> <validity days>");
        getLogger().info(
                " Imports a private key and generates a new self signed CVCA certificate with the given DN and creates a CVCA.");
        getLogger().info(
                " Signature algorithm can be SHA1WithRSA, SHA256WithRSA, SHA1WithECDSA, SHA224WithECDSA, SHA256WithECDSA, etc.");
        getLogger().info(
                " SERIALNUMBER will not be a part of the CAs DN, it is only used to set a specified sequence (should be of form 00001). Can be left out, and a random sequence is then generated.");
        return;
    }
    try {
        String caName = args[1];
        String pkFile = args[2];
        String certFile = args[3];

        // Import key and certificate
        CryptoProviderTools.installBCProvider();
        byte[] pkbytes = FileTools.readFiletoBuffer(pkFile);
        PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(pkbytes);
        KeyFactory keyfact = KeyFactory.getInstance("RSA", "BC"); // Doesn't matter if we say RSA here, it will fix an EC key as well
        PrivateKey privKey = keyfact.generatePrivate(spec);

        byte[] certbytes = FileTools.readFiletoBuffer(certFile);
        Certificate cert = null;
        try {
            // First check if it was a PEM formatted certificate
            Collection<Certificate> certs = CertTools.getCertsFromPEM(new ByteArrayInputStream(certbytes));
            cert = certs.iterator().next();
        } catch (IOException e) {
            // This was not a PEM certificate, I hope it's binary...
            cert = CertTools.getCertfromByteArray(certbytes);
        }
        PublicKey pubKey = cert.getPublicKey();
        // Verify that the public and private key belongs together
        getLogger().info("Testing keys with algorithm: " + pubKey.getAlgorithm());
        KeyTools.testKey(privKey, pubKey, null);

        Certificate cacert = null;
        if (args.length > 6) {
            // Create a self signed CVCA cert from the DN
            getLogger().info("Generating new self signed certificate.");
            String dn = args[4];
            String sigAlg = args[5];
            Integer valdays = Integer.parseInt(args[6]);

            String country = CertTools.getPartFromDN(dn, "C");
            String mnemonic = CertTools.getPartFromDN(dn, "CN");
            String seq = CertTools.getPartFromDN(dn, "SERIALNUMBER");
            if (StringUtils.isEmpty(seq)) {
                seq = RandomStringUtils.randomNumeric(5);
                getLogger().info("No sequence given, using random 5 number sequence: " + seq);
            }
            HolderReferenceField holderRef = new HolderReferenceField(country, mnemonic, seq);
            CAReferenceField caRef = new CAReferenceField(holderRef.getCountry(), holderRef.getMnemonic(),
                    holderRef.getSequence());
            AuthorizationRoleEnum authRole = AuthorizationRoleEnum.CVCA;
            Date notBefore = new Date();
            Calendar notAfter = Calendar.getInstance();
            notAfter.add(Calendar.DAY_OF_MONTH, valdays);
            CVCertificate cvc = CertificateGenerator.createCertificate(pubKey, privKey, sigAlg, caRef,
                    holderRef, authRole, AccessRightEnum.READ_ACCESS_DG3_AND_DG4, notBefore, notAfter.getTime(),
                    "BC");
            cacert = new CardVerifiableCertificate(cvc);
        } else {
            getLogger().info("Using passed in self signed certificate.");
            cacert = cert;
        }
        try {
            cacert.verify(pubKey);
        } catch (SignatureException e) {
            getLogger().info("Can not verify self signed certificate: " + e.getMessage());
            System.exit(3); // NOPMD
        }

        Certificate[] chain = new Certificate[1];
        chain[0] = cacert;
        ejb.getCAAdminSession().importCAFromKeys(getAdmin(), caName, "foo123", chain, pubKey, privKey, null,
                null);
    } catch (ErrorAdminCommandException e) {
        throw e;
    } catch (Exception e) {
        throw new ErrorAdminCommandException(e);
    }
}

From source file:org.gluu.com.ox_push2.u2f.v2.cert.KeyPairGeneratorImpl.java

public KeyPair keyPairFromJson(String keyPairJson) throws U2FException {
    BigInteger x = null;// w ww .  jav  a 2 s. co  m
    BigInteger y = null;
    BigInteger d = null;

    try {
        JSONObject jsonKeyPair = (JSONObject) new JSONTokener(keyPairJson).nextValue();

        JSONObject jsonPrivateKey = jsonKeyPair.getJSONObject("privateKey");
        d = new BigInteger(Utils.decodeHexString(jsonPrivateKey.getString("d")));

        JSONObject jsonPublicKey = jsonKeyPair.getJSONObject("publicKey");
        x = new BigInteger(Utils.decodeHexString(jsonPublicKey.getString("x")));
        y = new BigInteger(Utils.decodeHexString(jsonPublicKey.getString("y")));
    } catch (JSONException ex) {
        throw new U2FException("Failed to deserialize key pair from JSON", ex);
    } catch (DecoderException ex) {
        throw new U2FException("Failed to deserialize key pair from JSON", ex);
    }

    ECParameterSpec ecSpec = ECNamedCurveTable.getParameterSpec("secp256r1");

    ECCurve curve = ecSpec.getCurve();
    ECPoint validatePoint = curve.validatePoint(x, y);

    ECPublicKeySpec publicKeySpec = new ECPublicKeySpec(validatePoint, ecSpec);
    ECPrivateKeySpec privateKeySpec = new ECPrivateKeySpec(d, ecSpec);

    KeyFactory keyFactory = null;
    try {
        keyFactory = KeyFactory.getInstance("ECDSA", BOUNCY_CASTLE_PROVIDER);
        PrivateKey privateKey = keyFactory.generatePrivate(privateKeySpec);
        PublicKey publicKey = keyFactory.generatePublic(publicKeySpec);

        return new KeyPair(publicKey, privateKey);
    } catch (NoSuchAlgorithmException ex) {
        throw new U2FException("Failed to deserialize key pair from JSON", ex);
    } catch (InvalidKeySpecException ex) {
        throw new U2FException("Failed to deserialize key pair from JSON", ex);
    }
}