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, Provider provider) throws NoSuchAlgorithmException 

Source Link

Document

Returns a KeyFactory object that converts public/private keys of the specified algorithm.

Usage

From source file:org.ejbca.util.keystore.KeyTools.java

public static PublicKey getECPublicKeyWithParams(final PublicKey pk, final PublicKey pkwithparams)
        throws NoSuchAlgorithmException, NoSuchProviderException, InvalidKeySpecException {
    PublicKey ret = pk;/*from w w w. j a  v  a2  s  .  c o  m*/
    if ((pk instanceof PublicKeyEC) && (pkwithparams instanceof PublicKeyEC)) {
        final PublicKeyEC pkec = (PublicKeyEC) pk;
        // The public key of IS and DV certificate do not have any parameters so we have to do some magic to get a complete EC public key
        final ECParameterSpec spec = pkec.getParams();
        if (spec == null) {
            final PublicKeyEC pkecp = (PublicKeyEC) pkwithparams;
            final ECParameterSpec pkspec = pkecp.getParams();
            if (pkspec != null) {
                final org.bouncycastle.jce.spec.ECParameterSpec bcspec = EC5Util.convertSpec(pkspec, false);
                final java.security.spec.ECPoint p = pkec.getW();
                final org.bouncycastle.math.ec.ECPoint ecp = EC5Util.convertPoint(pkspec, p, false);
                final ECPublicKeySpec pubKey = new ECPublicKeySpec(ecp, bcspec);
                final KeyFactory keyfact = KeyFactory.getInstance("ECDSA", "BC");
                ret = keyfact.generatePublic(pubKey);
            } else {
                log.info("pkwithparams does not have any params.");
            }
        }
    } else {
        log.info("Either pk or pkwithparams is not a PublicKeyEC: " + pk.toString() + ", "
                + pkwithparams.toString());
    }
    return ret;
}

From source file:org.panbox.core.crypto.CryptCore.java

/**
 * Creates a public key from a byte[]//ww  w.j av a2  s.c  o m
 * 
 * @param keyType
 *            type for example "RSA"
 * @param keyBytes
 *            the byte[] with the key
 * @return the public key or null on error
 * @throws InvalidKeySpecException
 * @throws NoSuchAlgorithmException
 */
public static PublicKey createPublicKeyFromBytes(byte[] keyBytes) {
    PublicKey pk = null;
    try {
        KeyFactory keyFactory = KeyFactory.getInstance(KeyConstants.KEY_FACTORY, new BouncyCastleProvider());
        pk = keyFactory.generatePublic(new X509EncodedKeySpec(keyBytes));
    } catch (NoSuchAlgorithmException | InvalidKeySpecException e) {
        logger.warn("Exception caught in CryptCore." + "createPublicKeyFromBytes, returning null", e);
    }
    return pk;
}

From source file:Networking.Client.java

public boolean SignatureVerification() {
    Signature sig = null;/*w w  w  .  j ava 2s.  co  m*/
    Boolean result = false;
    try {
        X509EncodedKeySpec pubKeySpec = new X509EncodedKeySpec(PubToVerify);
        KeyFactory keyFact = KeyFactory.getInstance("DSA", "SUN");
        PublicKey pubkeyToVerify = keyFact.generatePublic(pubKeySpec);
        confirmIdentity = checkAgainstRT(pubkeyToVerify.hashCode());
        sig = Signature.getInstance("SHA1withDSA", "SUN");
        sig.initVerify(pubkeyToVerify);

        byte[] g_pow_y_sign = this.node.getG_pow_y().toByteArray();
        byte[] g_pow_x_sign = this.node.getG_pow_x().toByteArray();
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        outputStream.write(g_pow_x_sign);
        outputStream.write(g_pow_y_sign);
        byte[] c = outputStream.toByteArray();

        sig.update(c);
        result = (sig.verify(sigToVerify));
    } catch (SignatureException | InvalidKeyException | NoSuchAlgorithmException | NoSuchProviderException
            | InvalidKeySpecException | IOException ex) {
        Logger.getLogger(Client.class.getName()).log(Level.SEVERE, null, ex);
    }
    return result;
}

From source file:org.panbox.core.crypto.CryptCore.java

/**
 * Converts a given RSA PrivateKey instance to a KeyPair instance. The
 * PublicKey will be extracted from PrivateKey instance.
 * /*from   www. ja  v  a 2 s.c o m*/
 * @param pKey
 *            The RSA PrivateKey used to generate the KeyPair
 * @return KeyPair instance including the private and public key.
 * @throws NoSuchAlgorithmException
 * @throws InvalidKeySpecException
 */
public static KeyPair privateKeyToKeyPair(PrivateKey pKey)
        throws NoSuchAlgorithmException, InvalidKeySpecException {
    KeyFactory keyFactory = KeyFactory.getInstance(KeyConstants.KEY_FACTORY, new BouncyCastleProvider());
    RSAPrivateCrtKey rsaPKey = (RSAPrivateCrtKey) pKey;
    RSAPublicKeySpec publicKeySpec = new java.security.spec.RSAPublicKeySpec(rsaPKey.getModulus(),
            rsaPKey.getPublicExponent());
    return new KeyPair(keyFactory.generatePublic(publicKeySpec), pKey);
}

From source file:com.eucalyptus.crypto.DefaultCryptoProvider.java

/**
 * Get the PKCS#8 encoded bytes for the key.
 *
 * @param privateKey The key to encode./*from w w  w  .j a  v a 2s. com*/
 * @return The bytes
 */
@Override
public byte[] getEncoded(final PrivateKey privateKey) {
    if ("pkcs8".equals(PRIVATE_KEY_FORMAT))
        try {
            return KeyFactory.getInstance(KEY_ALGORITHM, PROVIDER)
                    .getKeySpec(privateKey, PKCS8EncodedKeySpec.class).getEncoded();
        } catch (Exception e) {
            LOG.error(e, e);
        }
    return privateKey.getEncoded();
}

From source file:org.cesecore.keys.util.KeyTools.java

/**
 * An ECDSA key can be stripped of the curve parameters so it only contains the public point, and this is not enough to use the key for
 * verification. However, if we know the curve name we can fill in the curve parameters and get a usable EC public key
 * /*  w  w  w . j a  v a  2s  .c o  m*/
 * @param pk
 *            PublicKey, org.ejbca.cvc.PublicKeyEC, that might miss parameters, if parameters are there we do not touch the public key just return it unchanged
 * @param keySpec
 *            name of curve for example brainpoolp224r1
 * @return PublicKey with parameters from the named curve
 * @throws NoSuchProviderException
 * @throws NoSuchAlgorithmException
 * @throws InvalidKeySpecException
 */
public static PublicKey getECPublicKeyWithParams(final PublicKey pk, final String keySpec)
        throws NoSuchAlgorithmException, NoSuchProviderException, InvalidKeySpecException {
    PublicKey ret = pk;
    if ((pk instanceof PublicKeyEC) && (keySpec != null)) {
        final PublicKeyEC pkec = (PublicKeyEC) pk;
        // The public key of IS and DV certificate do not have any parameters so we have to do some magic to get a complete EC public key
        final ECParameterSpec spec = pkec.getParams();
        if (spec == null) {
            // we did not have the parameter specs, lets create them because we know which curve we are using
            final org.bouncycastle.jce.spec.ECParameterSpec bcspec = ECNamedCurveTable
                    .getParameterSpec(keySpec);
            final java.security.spec.ECPoint p = pkec.getW();
            final org.bouncycastle.math.ec.ECPoint ecp = EC5Util.convertPoint(bcspec.getCurve(), p, false);
            final ECPublicKeySpec pubKey = new ECPublicKeySpec(ecp, bcspec);
            final KeyFactory keyfact = KeyFactory.getInstance("ECDSA", "BC");
            ret = keyfact.generatePublic(pubKey);
        }
    }
    return ret;
}

From source file:org.cesecore.keys.util.KeyTools.java

/**
 * An ECDSA key can be stripped of the curve parameters so it only contains the public point, and this is not enough to use the key for
 * verification. However, if we know the curve name we can fill in the curve parameters and get a usable EC public key
 * /*  w w w . j  a  v  a2  s . c  o m*/
 * @param pk
 *            PublicKey, org.ejbca.cvc.PublicKeyEC, that might miss parameters, if parameters are there we do not touch the public key just return it unchanged
 * @param pkwithparams
 *            PublicKey, org.ejbca.cvc.PublicKeyEC, that contains all parameters.
 * @return PublicKey with parameters from the named curve
 *
 * @throws InvalidKeySpecException if the key specification in pkwithparams was invalid
 */
public static PublicKey getECPublicKeyWithParams(final PublicKey pk, final PublicKey pkwithparams)
        throws InvalidKeySpecException {
    PublicKey ret = pk;
    if ((pk instanceof PublicKeyEC) && (pkwithparams instanceof PublicKeyEC)) {
        final PublicKeyEC pkec = (PublicKeyEC) pk;
        // The public key of IS and DV certificate do not have any parameters so we have to do some magic to get a complete EC public key
        final ECParameterSpec spec = pkec.getParams();
        if (spec == null) {
            final PublicKeyEC pkecp = (PublicKeyEC) pkwithparams;
            final ECParameterSpec pkspec = pkecp.getParams();
            if (pkspec != null) {
                final org.bouncycastle.jce.spec.ECParameterSpec bcspec = EC5Util.convertSpec(pkspec, false);
                final java.security.spec.ECPoint p = pkec.getW();
                final org.bouncycastle.math.ec.ECPoint ecp = EC5Util.convertPoint(pkspec, p, false);
                final ECPublicKeySpec pubKey = new ECPublicKeySpec(ecp, bcspec);
                KeyFactory keyfact;
                try {
                    keyfact = KeyFactory.getInstance("ECDSA", BouncyCastleProvider.PROVIDER_NAME);
                } catch (NoSuchAlgorithmException e) {
                    throw new IllegalStateException("ECDSA was an unknown algorithm", e);
                } catch (NoSuchProviderException e) {
                    throw new IllegalStateException("BouncyCastle was not found as a provider.", e);
                }
                ret = keyfact.generatePublic(pubKey);
            } else {
                log.info("pkwithparams does not have any params.");
            }
        }
    } else {
        log.info("Either pk or pkwithparams is not a PublicKeyEC: " + pk.toString() + ", "
                + pkwithparams.toString());
    }
    return ret;
}

From source file:org.apache.cloudstack.network.ssl.CertServiceImpl.java

public PrivateKey parsePrivateKey(final String key) throws IOException {
    Preconditions.checkArgument(!Strings.isNullOrEmpty(key));
    try (final PemReader pemReader = new PemReader(new StringReader(key));) {
        final PemObject pemObject = pemReader.readPemObject();
        final byte[] content = pemObject.getContent();
        final PKCS8EncodedKeySpec privKeySpec = new PKCS8EncodedKeySpec(content);
        final KeyFactory factory = KeyFactory.getInstance("RSA", "BC");
        return factory.generatePrivate(privKeySpec);
    } catch (NoSuchAlgorithmException | NoSuchProviderException e) {
        throw new IOException("No encryption provider available.", e);
    } catch (final InvalidKeySpecException e) {
        throw new IOException("Invalid Key format.", e);
    }/*w w  w  .jav  a2 s  .  co  m*/
}

From source file:com.orange.oidc.secproxy_service.KryptoUtils.java

public static RSAPrivateKey privKeyFromJwk(String jwkp) {
    RSAPrivateKey privKey = null;

    try {//from w  ww .  j a va2  s.com
        JSONObject jk = new JSONObject(jwkp).getJSONArray("keys").getJSONObject(0);

        BigInteger n = new BigInteger(1, decodeB64(jk.getString("n")));
        BigInteger d = new BigInteger(1, decodeB64(jk.getString("d")));
        // BigInteger e = new BigInteger(1, decodeB64(jk.getString("e")));

        // Log.d("privKeyFromJwk","n "+n);
        // Log.d("privKeyFromJwk","d "+d);
        // Log.d("privKeyFromJwk","e "+e);

        RSAPrivateKeySpec privRsaSpec = new RSAPrivateKeySpec(n, d);
        KeyFactory keyfact = KeyFactory.getInstance("RSA", "SC");
        privKey = (RSAPrivateKey) keyfact.generatePrivate(privRsaSpec);
        // Log.d("privKeyFromJwk","priv key length "+privRsaSpec.getModulus().toByteArray().length);

    } catch (Exception e) {
        e.printStackTrace();
    }

    return privKey;
}

From source file:org.ejbca.util.keystore.KeyTools.java

/**
 * Creates PKCS12-file that can be imported in IE or Firefox. The alias for the private key is
 * set to 'privateKey' and the private key password is null.
 *
 * @param alias the alias used for the key entry
 * @param privKey RSA private key/*from  w  ww. j a v  a2  s  .c o  m*/
 * @param cert user certificate
 * @param cachain CA-certificate chain or null if only one cert in chain, in that case use 'cert'.
 * @return KeyStore containing PKCS12-keystore
 * @exception Exception if input parameters are not OK or certificate generation fails
 */
public static KeyStore createP12(final String alias, final PrivateKey privKey, final Certificate cert,
        final Certificate[] cachain) throws IOException, KeyStoreException, CertificateException,
        NoSuchProviderException, NoSuchAlgorithmException, InvalidKeySpecException {
    if (log.isTraceEnabled()) {
        log.trace(">createP12: alias=" + alias + ", privKey, cert=" + CertTools.getSubjectDN(cert)
                + ", cachain.length=" + ((cachain == null) ? 0 : cachain.length));
    }
    // Certificate chain
    if (cert == null) {
        throw new IllegalArgumentException("Parameter cert cannot be null.");
    }
    int len = 1;
    if (cachain != null) {
        len += cachain.length;
    }
    final Certificate[] chain = new Certificate[len];
    // To not get a ClassCastException we need to generate a real new certificate with BC
    final CertificateFactory cf = CertTools.getCertificateFactory();
    chain[0] = cf.generateCertificate(new ByteArrayInputStream(cert.getEncoded()));

    if (cachain != null) {
        for (int i = 0; i < cachain.length; i++) {
            final X509Certificate tmpcert = (X509Certificate) cf
                    .generateCertificate(new ByteArrayInputStream(cachain[i].getEncoded()));
            chain[i + 1] = tmpcert;
        }
    }
    if (chain.length > 1) {
        for (int i = 1; i < chain.length; i++) {
            final X509Certificate cacert = (X509Certificate) cf
                    .generateCertificate(new ByteArrayInputStream(chain[i].getEncoded()));
            // Set attributes on CA-cert
            try {
                final PKCS12BagAttributeCarrier caBagAttr = (PKCS12BagAttributeCarrier) chain[i];
                // We construct a friendly name for the CA, and try with some parts from the DN if they exist.
                String cafriendly = CertTools.getPartFromDN(CertTools.getSubjectDN(cacert), "CN");
                // On the ones below we +i to make it unique, O might not be otherwise
                if (cafriendly == null) {
                    cafriendly = CertTools.getPartFromDN(CertTools.getSubjectDN(cacert), "O") + i;
                }
                if (cafriendly == null) {
                    cafriendly = CertTools.getPartFromDN(CertTools.getSubjectDN(cacert), "OU" + i);
                }
                if (cafriendly == null) {
                    cafriendly = "CA_unknown" + i;
                }
                caBagAttr.setBagAttribute(PKCSObjectIdentifiers.pkcs_9_at_friendlyName,
                        new DERBMPString(cafriendly));
            } catch (ClassCastException e) {
                log.error("ClassCastException setting BagAttributes, can not set friendly name: ", e);
            }
        }
    }

    // Set attributes on user-cert
    try {
        final PKCS12BagAttributeCarrier certBagAttr = (PKCS12BagAttributeCarrier) chain[0];
        certBagAttr.setBagAttribute(PKCSObjectIdentifiers.pkcs_9_at_friendlyName, new DERBMPString(alias));
        // in this case we just set the local key id to that of the public key
        certBagAttr.setBagAttribute(PKCSObjectIdentifiers.pkcs_9_at_localKeyId,
                createSubjectKeyId(chain[0].getPublicKey()));
    } catch (ClassCastException e) {
        log.error("ClassCastException setting BagAttributes, can not set friendly name: ", e);
    }
    // "Clean" private key, i.e. remove any old attributes
    final KeyFactory keyfact = KeyFactory.getInstance(privKey.getAlgorithm(), "BC");
    final PrivateKey pk = keyfact.generatePrivate(new PKCS8EncodedKeySpec(privKey.getEncoded()));
    // Set attributes for private key
    try {
        final PKCS12BagAttributeCarrier keyBagAttr = (PKCS12BagAttributeCarrier) pk;
        // in this case we just set the local key id to that of the public key
        keyBagAttr.setBagAttribute(PKCSObjectIdentifiers.pkcs_9_at_friendlyName, new DERBMPString(alias));
        keyBagAttr.setBagAttribute(PKCSObjectIdentifiers.pkcs_9_at_localKeyId,
                createSubjectKeyId(chain[0].getPublicKey()));
    } catch (ClassCastException e) {
        log.error("ClassCastException setting BagAttributes, can not set friendly name: ", e);
    }
    // store the key and the certificate chain
    final KeyStore store = KeyStore.getInstance("PKCS12", "BC");
    store.load(null, null);
    store.setKeyEntry(alias, pk, null, chain);
    if (log.isTraceEnabled()) {
        log.trace("<createP12: alias=" + alias + ", privKey, cert=" + CertTools.getSubjectDN(cert)
                + ", cachain.length=" + ((cachain == null) ? 0 : cachain.length));
    }
    return store;
}