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) throws NoSuchAlgorithmException 

Source Link

Document

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

Usage

From source file:net.firejack.platform.web.security.x509.KeyUtils.java

public static void verify(String cert64, String public64) throws CertificateException, NoSuchAlgorithmException,
        InvalidKeySpecException, SignatureException, NoSuchProviderException, InvalidKeyException {
    if (StringUtils.isBlank(cert64)) {
        throw new CertificateException("Certificate is empty");
    } else if (StringUtils.isBlank(public64)) {
        throw new InvalidKeyException("Public key is empty");
    }//  w  w  w . j  a  va  2 s  .  c  o m
    byte[] cert = Base64.decode(cert64);
    byte[] key = Base64.decode(public64);
    X509CertImpl x509 = new X509CertImpl(cert);

    KeyFactory keyFactory = KeyFactory.getInstance("RSA");
    EncodedKeySpec publicKeySpec = new X509EncodedKeySpec(key);
    PublicKey publicKey = keyFactory.generatePublic(publicKeySpec);

    Calendar utc = Calendar.getInstance(TimeZone.getTimeZone("UTC"));

    x509.verify(publicKey);
    x509.checkValidity(utc.getTime());
}

From source file:org.kaaproject.kaa.common.endpoint.security.KeyUtil.java

/**
 * Gets the public key from bytes./*ww  w . ja  v a  2s  .c o m*/
 *
 * @param keyBytes the key bytes
 * @return the public
 * @throws InvalidKeyException invalid key exception
 */
public static PublicKey getPublic(byte[] keyBytes) throws InvalidKeyException {
    try {
        X509EncodedKeySpec spec = new X509EncodedKeySpec(keyBytes);
        KeyFactory kf = KeyFactory.getInstance(RSA);
        return kf.generatePublic(spec);
    } catch (NoSuchAlgorithmException | InvalidKeySpecException ex) {
        throw new InvalidKeyException(ex);
    }
}

From source file:org.bankinterface.util.KeyStoreUtil.java

public static void importPKCS8CertChain(KeyStore ks, String alias, byte[] keyBytes, String keyPass,
        byte[] certChain)
        throws InvalidKeySpecException, NoSuchAlgorithmException, CertificateException, KeyStoreException {
    // load the private key
    KeyFactory kf = KeyFactory.getInstance("RSA");
    PKCS8EncodedKeySpec keysp = new PKCS8EncodedKeySpec(keyBytes);
    PrivateKey pk = kf.generatePrivate(keysp);

    // load the cert chain
    CertificateFactory cf = CertificateFactory.getInstance("X.509");
    ByteArrayInputStream bais = new ByteArrayInputStream(certChain);

    Collection<? extends Certificate> certCol = cf.generateCertificates(bais);
    Certificate[] certs = new Certificate[certCol.toArray().length];
    if (certCol.size() == 1) {
        logger.info("Single certificate; no chain");
        bais = new ByteArrayInputStream(certChain);
        Certificate cert = cf.generateCertificate(bais);
        certs[0] = cert;//w  w  w  .j  a va  2 s .  c o  m
    } else {
        logger.info("Certificate chain length : " + certCol.size());
        certs = certCol.toArray(new Certificate[certCol.size()]);
    }

    ks.setKeyEntry(alias, pk, keyPass.toCharArray(), certs);
}

From source file:gemlite.core.util.RSAUtils.java

/**
 * <p>/*  w w w.ja v  a 2  s  . c  o  m*/
 * 
 * </p>
 * 
 * @param encryptedData
 *          ?
 * @param publicKey
 *          (BASE64?)
 * @return
 * @throws Exception
 */
public static byte[] decryptByPublicKey(byte[] encryptedData, String publicKey) throws Exception {
    byte[] keyBytes = Base64Utils.decode(publicKey);
    X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(keyBytes);
    KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
    Key publicK = keyFactory.generatePublic(x509KeySpec);
    Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
    cipher.init(Cipher.DECRYPT_MODE, publicK);
    int inputLen = encryptedData.length;
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    int offSet = 0;
    byte[] cache;
    int i = 0;
    // ?
    while (inputLen - offSet > 0) {
        if (inputLen - offSet > MAX_DECRYPT_BLOCK) {
            cache = cipher.doFinal(encryptedData, offSet, MAX_DECRYPT_BLOCK);
        } else {
            cache = cipher.doFinal(encryptedData, offSet, inputLen - offSet);
        }
        out.write(cache, 0, cache.length);
        i++;
        offSet = i * MAX_DECRYPT_BLOCK;
    }
    byte[] decryptedData = out.toByteArray();
    out.close();
    return decryptedData;
}

From source file:cloudeventbus.pki.CertificateUtils.java

public static PrivateKey loadPrivateKey(String fileName)
        throws IOException, NoSuchAlgorithmException, InvalidKeySpecException {
    final Path path = Paths.get(fileName);
    final byte[] encodedPrivateKey = Files.readAllBytes(path);
    final KeyFactory keyFactory = KeyFactory.getInstance("RSA");
    final PKCS8EncodedKeySpec privateKeySpec = new PKCS8EncodedKeySpec(encodedPrivateKey);
    return keyFactory.generatePrivate(privateKeySpec);
}

From source file:JALPTest.java

/**
 * Creates a Producer using the given command line params.
 *
 * @param xml            the ApplicationMetadataXML
 * @param socketPath      a String which is the path to the socket
 * @param privateKeyPath   a String which is the path to the private key in DER format
 * @param publicKeyPath      a String which is the path to the public key in DER format
 * @param certPath         a String which is the path to the certificate
 * @param hasDigest         a Boolean, true to set a digest method in the producer
 * @return   the created Producer/*  w w w . j a v  a  2 s. c  o m*/
 * @throws Exception
 */
private static Producer createProducer(ApplicationMetadataXML xml, String socketPath, String privateKeyPath,
        String publicKeyPath, String certPath, Boolean hasDigest) throws Exception {
    Producer producer = new Producer(xml);
    producer.setSocketFile(socketPath);

    if (privateKeyPath != null && !"".equals(privateKeyPath)) {

        File privateKeyFile = new File(privateKeyPath);
        DataInputStream privateDis = new DataInputStream(new FileInputStream(privateKeyFile));
        byte[] privateKeyBytes = new byte[(int) privateKeyFile.length()];
        privateDis.readFully(privateKeyBytes);
        privateDis.close();

        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        KeySpec privateKs = new PKCS8EncodedKeySpec(privateKeyBytes);
        PrivateKey privateKey = keyFactory.generatePrivate(privateKs);

        File publicKeyFile = new File(publicKeyPath);
        DataInputStream publicDis = new DataInputStream(new FileInputStream(publicKeyFile));
        byte[] publicKeyBytes = new byte[(int) publicKeyFile.length()];
        publicDis.readFully(publicKeyBytes);
        publicDis.close();

        KeySpec publicKs = new X509EncodedKeySpec(publicKeyBytes);
        PublicKey publicKey = keyFactory.generatePublic(publicKs);

        producer.setPrivateKey(privateKey);
        producer.setPublicKey(publicKey);
    }

    if (certPath != null && !"".equals(certPath)) {
        InputStream inputStream = new FileInputStream(certPath);
        CertificateFactory cf = CertificateFactory.getInstance("X.509");
        X509Certificate cert = (X509Certificate) cf.generateCertificate(inputStream);
        inputStream.close();
        producer.setCertificate(cert);
    }

    if (hasDigest) {
        producer.setDigestMethod(DMType.SHA256);
    }

    return producer;
}

From source file:org.apache.james.jdkim.tagvalue.PublicKeyRecordImpl.java

/**
 * @see org.apache.james.jdkim.api.PublicKeyRecord#getPublicKey()
 *///from w  ww .ja  v  a2s. co m
public PublicKey getPublicKey() {
    try {
        String p = getValue("p").toString();
        byte[] key = Base64.decodeBase64(p.getBytes());
        KeyFactory keyFactory;
        keyFactory = KeyFactory.getInstance(getValue("k").toString());
        X509EncodedKeySpec pubSpec = new X509EncodedKeySpec(key);
        RSAPublicKey rsaKey;
        rsaKey = (RSAPublicKey) keyFactory.generatePublic(pubSpec);
        return rsaKey;
    } catch (NoSuchAlgorithmException e) {
        throw new IllegalStateException("Unknown algorithm: " + e.getMessage());
    } catch (InvalidKeySpecException e) {
        throw new IllegalStateException("Invalid key spec: " + e.getMessage());
    }
}

From source file:jenkins.bouncycastle.api.PEMEncodable.java

/**
 * Creates a {@link PEMEncodable} by decoding PEM formated data from a {@link String}
 * //from  ww w  .  j a  v a 2s .  co m
 * @param pem {@link String} with the PEM data
 * @param passphrase passphrase for the encrypted PEM data. null if PEM data is not passphrase protected. The caller
 * is responsible for zeroing out the char[] after use to ensure the password does not stay in memory, e.g. with
 * <code>Arrays.fill(passphrase, (char)0)</code>
 * @return {@link PEMEncodable} object
 * @throws IOException launched if a problem exists reading the PEM information
 * @throws UnrecoverableKeyException in case PEM is passphrase protected and none or wrong is provided
 */
@Nonnull
public static PEMEncodable decode(@Nonnull String pem, @Nullable final char[] passphrase)
        throws IOException, UnrecoverableKeyException {

    try (PEMParser parser = new PEMParser(new StringReader(pem));) {

        Object object = parser.readObject();

        JcaPEMKeyConverter kConv = new JcaPEMKeyConverter().setProvider("BC");

        // handle supported PEM formats.
        if (object instanceof PEMEncryptedKeyPair) {
            if (passphrase != null) {
                PEMDecryptorProvider dp = new JcePEMDecryptorProviderBuilder().build(passphrase);
                PEMEncryptedKeyPair ekp = (PEMEncryptedKeyPair) object;
                return new PEMEncodable(kConv.getKeyPair(ekp.decryptKeyPair(dp)));
            } else {
                throw new UnrecoverableKeyException();
            }
        } else if (object instanceof PKCS8EncryptedPrivateKeyInfo) {
            if (passphrase != null) {
                InputDecryptorProvider dp = new JceOpenSSLPKCS8DecryptorProviderBuilder().build(passphrase);
                PKCS8EncryptedPrivateKeyInfo epk = (PKCS8EncryptedPrivateKeyInfo) object;
                return new PEMEncodable(kConv.getPrivateKey(epk.decryptPrivateKeyInfo(dp)));
            } else {
                throw new UnrecoverableKeyException();
            }
        } else if (object instanceof PEMKeyPair) {
            return new PEMEncodable(kConv.getKeyPair((PEMKeyPair) object));
        } else if (object instanceof PrivateKeyInfo) {
            PrivateKey pk = kConv.getPrivateKey((PrivateKeyInfo) object);

            // JENKINS-35661 in this case we know how to get the public key too
            if (pk instanceof RSAPrivateCrtKey) {
                // obtain public key spec from the private key
                RSAPrivateCrtKey rsaPK = (RSAPrivateCrtKey) pk;
                RSAPublicKeySpec pubKeySpec = new RSAPublicKeySpec(rsaPK.getModulus(),
                        rsaPK.getPublicExponent());
                KeyFactory kf = KeyFactory.getInstance("RSA");
                return new PEMEncodable(new KeyPair(kf.generatePublic(pubKeySpec), rsaPK));
            }

            return new PEMEncodable(pk);
        } else if (object instanceof SubjectPublicKeyInfo) {
            return new PEMEncodable(kConv.getPublicKey((SubjectPublicKeyInfo) object));
        } else if (object instanceof X509CertificateHolder) {
            JcaX509CertificateConverter cConv = new JcaX509CertificateConverter().setProvider("BC");
            return new PEMEncodable(cConv.getCertificate((X509CertificateHolder) object));
        } else {
            throw new IOException(
                    "Could not parse PEM, only key pairs, private keys, public keys and certificates are supported. Received "
                            + object.getClass().getName());
        }
    } catch (OperatorCreationException e) {
        throw new IOException(e.getMessage(), e);
    } catch (PKCSException | InvalidKeySpecException e) {
        LOGGER.log(Level.WARNING, "Could not read PEM encrypted information", e);
        throw new UnrecoverableKeyException();
    } catch (CertificateException e) {
        throw new IOException("Could not read certificate", e);
    } catch (NoSuchAlgorithmException e) {
        throw new AssertionError(
                "RSA algorithm support is mandated by Java Language Specification. See https://docs.oracle.com/javase/7/docs/api/java/security/KeyFactory.html");
    }
}

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

/**
 * ?//from   w  ww .j  ava 2s  .  c o  m
 * 
 * @param key ?base64?
 * @throws Exception
 */
public static PrivateKey getPrivateKey(String key) throws Exception {
    byte[] keyBytes;
    keyBytes = Base64Util.decode(key);
    PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(keyBytes);
    KeyFactory keyFactory = KeyFactory.getInstance("RSA");
    PrivateKey privateKey = keyFactory.generatePrivate(keySpec);
    return privateKey;
}

From source file:com.badlogic.gdx.pay.android.ouya.PurchaseManagerAndroidOUYA.java

@Override
public void install(final PurchaseObserver observer, PurchaseManagerConfig config) {
    this.observer = observer;
    this.config = config;

    // Obtain applicationKey and developer ID. Pass in as follows:
    // -------------------------------------------------------------------------
    //      config.addStoreParam(
    //         PurchaseManagerConfig.STORE_NAME_ANDROID_OUYA, 
    //         new Object[] { OUYA_DEVELOPERID_STRING, applicationKeyPathSTRING });
    // -------------------------------------------------------------------------

    Object[] configuration = (Object[]) config.getStoreParam(PurchaseManagerConfig.STORE_NAME_ANDROID_OUYA);
    String developerID = (String) configuration[0];
    applicationKeyPath = (String) configuration[1]; // store our OUYA applicationKey-Path!
    ouyaFacade = OuyaFacade.getInstance();
    ouyaFacade.init((Context) activity, developerID);

    // --- copy all available products to the list of purchasables
    productIDList = new ArrayList<Purchasable>(config.getOfferCount());
    for (int i = 0; i < config.getOfferCount(); i++) {
        productIDList.add(new Purchasable(config.getOffer(i).getIdentifier()));
    }//from ww w.  j  a v a 2 s  .  c  om

    // Create a PublicKey object from the key data downloaded from the developer portal.
    try {
        // Read in the key.der file (downloaded from the developer portal)
        FileHandle fHandle = Gdx.files.internal(applicationKeyPath);
        byte[] applicationKey = fHandle.readBytes();

        X509EncodedKeySpec keySpec = new X509EncodedKeySpec(applicationKey);
        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        ouyaPublicKey = keyFactory.generatePublic(keySpec);
        showMessage(LOGTYPELOG, "succesfully created publicKey");

        // ---- request the productlist ---------
        requestProductList();

        // notify of successful initialization
        observer.handleInstall();

    } catch (Exception e) {
        // notify about the problem
        showMessage(LOGTYPEERROR, "Problem setting up in-app billing: Unable to create encryption key");
        observer.handleInstallError(new RuntimeException(
                "Problem setting up in-app billing: Unable to create encryption key: " + e));
    }
}