Search in sources :

Example 51 with PKCS8EncodedKeySpec

use of java.security.spec.PKCS8EncodedKeySpec in project nhin-d by DirectProject.

the class RESTSmtpAgentConfigFunctional_Test method loadPkcs12FromCertAndKey.

private static byte[] loadPkcs12FromCertAndKey(String certFileName, String keyFileName) throws Exception {
    byte[] retVal = null;
    try {
        KeyStore localKeyStore = KeyStore.getInstance("PKCS12", CryptoExtensions.getJCEProviderName());
        localKeyStore.load(null, null);
        byte[] certData = loadCertificateData(certFileName);
        byte[] keyData = loadCertificateData(keyFileName);
        CertificateFactory cf = CertificateFactory.getInstance("X.509");
        InputStream inStr = new ByteArrayInputStream(certData);
        java.security.cert.Certificate cert = cf.generateCertificate(inStr);
        inStr.close();
        KeyFactory kf = KeyFactory.getInstance("RSA");
        PKCS8EncodedKeySpec keysp = new PKCS8EncodedKeySpec(keyData);
        Key privKey = kf.generatePrivate(keysp);
        char[] array = "".toCharArray();
        localKeyStore.setKeyEntry("privCert", privKey, array, new java.security.cert.Certificate[] { cert });
        ByteArrayOutputStream outStr = new ByteArrayOutputStream();
        localKeyStore.store(outStr, array);
        retVal = outStr.toByteArray();
        outStr.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
    return retVal;
}
Also used : ByteArrayInputStream(java.io.ByteArrayInputStream) InputStream(java.io.InputStream) ByteArrayOutputStream(java.io.ByteArrayOutputStream) KeyStore(java.security.KeyStore) CertificateFactory(java.security.cert.CertificateFactory) IOException(java.io.IOException) ByteArrayInputStream(java.io.ByteArrayInputStream) PKCS8EncodedKeySpec(java.security.spec.PKCS8EncodedKeySpec) KeyFactory(java.security.KeyFactory) Key(java.security.Key)

Example 52 with PKCS8EncodedKeySpec

use of java.security.spec.PKCS8EncodedKeySpec in project nhin-d by DirectProject.

the class CertLoader method loadCertificate.

public static CertCreateFields loadCertificate(File certFile, File keyFile, char[] password) throws Exception {
    byte[] certData = loadFileData(certFile);
    byte[] keyData = loadFileData(keyFile);
    CertificateFactory cf = CertificateFactory.getInstance("X.509");
    InputStream inStr = new ByteArrayInputStream(certData);
    java.security.cert.Certificate holdCert = cf.generateCertificate(inStr);
    X509Certificate cert = (X509Certificate) holdCert;
    IOUtils.closeQuietly(inStr);
    KeyFactory kf = KeyFactory.getInstance("RSA", CryptoExtensions.getJCEProviderName());
    PKCS8EncodedKeySpec keysp = null;
    if (password != null && password.length > 0) {
        EncryptedPrivateKeyInfo encInfo = new EncryptedPrivateKeyInfo(keyData);
        PBEKeySpec keySpec = new PBEKeySpec(password);
        String alg = encInfo.getAlgName();
        SecretKeyFactory secFactory = SecretKeyFactory.getInstance(alg, CryptoExtensions.getJCEProviderName());
        SecretKey secKey = secFactory.generateSecret(keySpec);
        keysp = encInfo.getKeySpec(secKey, CryptoExtensions.getJCEProviderName());
    } else {
        keysp = new PKCS8EncodedKeySpec(keyData);
    }
    PrivateKey privKey = kf.generatePrivate(keysp);
    Map<String, Object> attributes = getAttributes(cert);
    Calendar now = Calendar.getInstance();
    Calendar exp = Calendar.getInstance();
    exp.setTime(cert.getNotAfter());
    long diff = exp.getTimeInMillis() - now.getTimeInMillis();
    long diffDays = diff / (24 * 60 * 60 * 1000);
    // TODO: get the key strength
    // just hard coded
    int keyStr = 1024;
    CertCreateFields retVal = new CertCreateFields(attributes, certFile, keyFile, password, (int) diffDays, keyStr, cert, privKey);
    return retVal;
}
Also used : PBEKeySpec(javax.crypto.spec.PBEKeySpec) PrivateKey(java.security.PrivateKey) ByteArrayInputStream(java.io.ByteArrayInputStream) InputStream(java.io.InputStream) Calendar(java.util.Calendar) CertificateFactory(java.security.cert.CertificateFactory) X509Certificate(java.security.cert.X509Certificate) SecretKey(javax.crypto.SecretKey) ByteArrayInputStream(java.io.ByteArrayInputStream) PKCS8EncodedKeySpec(java.security.spec.PKCS8EncodedKeySpec) EncryptedPrivateKeyInfo(javax.crypto.EncryptedPrivateKeyInfo) SecretKeyFactory(javax.crypto.SecretKeyFactory) KeyFactory(java.security.KeyFactory) SecretKeyFactory(javax.crypto.SecretKeyFactory)

Example 53 with PKCS8EncodedKeySpec

use of java.security.spec.PKCS8EncodedKeySpec in project nhin-d by DirectProject.

the class CreatePKCS12 method create.

/**
	 * Creates a PCKS12 file from the certificate and key files.
	 * @param certFile The X509 DER encoded certificate file.
	 * @param keyFile The PCKS8 DER encoded private key file.
	 * @param password Option password for the private key file.  This is required if the private key file is encrypted.  Should be null or empty
	 * if the private key file is not encrypted.
	 * @param createFile Optional file descriptor for the output file of the pkcs12 file.  If this is null, the file name is based on the 
	 * certificate file name.
	 * @return File descriptor of the created pcks12 file.  Null if an error occurred.  
	 */
public static File create(File certFile, File keyFile, String password, File createFile) {
    File pkcs12File = null;
    CreatePKCS12.certFile = certFile;
    CreatePKCS12.keyFile = keyFile;
    FileOutputStream outStr = null;
    InputStream inStr = null;
    // load cert file
    try {
        KeyStore localKeyStore = KeyStore.getInstance("PKCS12", CryptoExtensions.getJCEProviderName());
        localKeyStore.load(null, null);
        byte[] certData = loadFileData(certFile);
        byte[] keyData = loadFileData(keyFile);
        CertificateFactory cf = CertificateFactory.getInstance("X.509");
        inStr = new ByteArrayInputStream(certData);
        java.security.cert.Certificate cert = cf.generateCertificate(inStr);
        IOUtils.closeQuietly(inStr);
        KeyFactory kf = KeyFactory.getInstance("RSA", CryptoExtensions.getJCEProviderName());
        PKCS8EncodedKeySpec keysp = null;
        if (password != null && !password.isEmpty()) {
            EncryptedPrivateKeyInfo encInfo = new EncryptedPrivateKeyInfo(keyData);
            PBEKeySpec keySpec = new PBEKeySpec(password.toCharArray());
            String alg = encInfo.getAlgName();
            SecretKeyFactory secFactory = SecretKeyFactory.getInstance(alg, CryptoExtensions.getJCEProviderName());
            SecretKey secKey = secFactory.generateSecret(keySpec);
            keysp = encInfo.getKeySpec(secKey, CryptoExtensions.getJCEProviderName());
        } else {
            keysp = new PKCS8EncodedKeySpec(keyData);
        }
        Key privKey = kf.generatePrivate(keysp);
        char[] array = "".toCharArray();
        localKeyStore.setKeyEntry("privCert", privKey, array, new java.security.cert.Certificate[] { cert });
        pkcs12File = getPKCS12OutFile(createFile);
        outStr = new FileOutputStream(pkcs12File);
        localKeyStore.store(outStr, p12Pass.toCharArray());
    } catch (Exception e) {
        System.err.println("Failed to create pcks12 file: " + e.getMessage());
        e.printStackTrace(System.err);
        return null;
    } finally {
        IOUtils.closeQuietly(outStr);
        IOUtils.closeQuietly(inStr);
    }
    return pkcs12File;
}
Also used : PBEKeySpec(javax.crypto.spec.PBEKeySpec) ByteArrayInputStream(java.io.ByteArrayInputStream) InputStream(java.io.InputStream) KeyStore(java.security.KeyStore) CertificateFactory(java.security.cert.CertificateFactory) SecretKey(javax.crypto.SecretKey) ByteArrayInputStream(java.io.ByteArrayInputStream) FileOutputStream(java.io.FileOutputStream) PKCS8EncodedKeySpec(java.security.spec.PKCS8EncodedKeySpec) EncryptedPrivateKeyInfo(javax.crypto.EncryptedPrivateKeyInfo) File(java.io.File) SecretKeyFactory(javax.crypto.SecretKeyFactory) KeyFactory(java.security.KeyFactory) SecretKeyFactory(javax.crypto.SecretKeyFactory) Key(java.security.Key) SecretKey(javax.crypto.SecretKey)

Example 54 with PKCS8EncodedKeySpec

use of java.security.spec.PKCS8EncodedKeySpec in project nhin-d by DirectProject.

the class KeyStoreCreate method importCert.

private static void importCert(String alias, String certFile, String pkFile) {
    try {
        System.out.println("Importing cert with alias \"" + alias + "\"");
        if (service.getByAlias(alias) == null) {
            if (certFile.endsWith("p12")) {
                X509Certificate cert = TestUtils.certFromData(FileUtils.readFileToByteArray(new File(certsBasePath + certFile)));
                service.add(cert, alias);
            } else {
                InputStream inStream = new FileInputStream(certsBasePath + certFile);
                CertificateFactory cf = CertificateFactory.getInstance("X.509");
                X509Certificate cert = (X509Certificate) cf.generateCertificate(inStream);
                inStream.close();
                PrivateKey ff = null;
                if (pkFile != null && pkFile.length() > 0) {
                    InputStream btInstream = fullStream(certsBasePath + pkFile);
                    byte[] key = new byte[btInstream.available()];
                    KeyFactory kf = KeyFactory.getInstance("RSA");
                    btInstream.read(key, 0, btInstream.available());
                    btInstream.close();
                    PKCS8EncodedKeySpec keysp = new PKCS8EncodedKeySpec(key);
                    ff = kf.generatePrivate(keysp);
                }
                service.add(ff != null ? X509CertificateEx.fromX509Certificate(cert, ff) : cert, alias);
            }
            System.out.println("Alias added:\r\n\tCert DN: " + service.getByAlias(alias).getSubjectDN().getName() + "\r\n");
        } else {
            System.out.println("Alias already exists:\r\n\tCert DN: " + service.getByAlias(alias).getSubjectDN().getName() + "\r\n");
        }
    } catch (Exception e) {
        System.out.println("Error importing cert: " + e.getLocalizedMessage());
    }
}
Also used : PrivateKey(java.security.PrivateKey) DataInputStream(java.io.DataInputStream) FileInputStream(java.io.FileInputStream) ByteArrayInputStream(java.io.ByteArrayInputStream) InputStream(java.io.InputStream) PKCS8EncodedKeySpec(java.security.spec.PKCS8EncodedKeySpec) File(java.io.File) CertificateFactory(java.security.cert.CertificateFactory) X509Certificate(java.security.cert.X509Certificate) FileInputStream(java.io.FileInputStream) KeyFactory(java.security.KeyFactory) IOException(java.io.IOException)

Example 55 with PKCS8EncodedKeySpec

use of java.security.spec.PKCS8EncodedKeySpec in project android_frameworks_base by DirtyUnicorns.

the class CertPinInstallReceiverTest method createKey.

private PrivateKey createKey() throws Exception {
    byte[] derKey = Base64.decode(TEST_KEY.getBytes(), Base64.DEFAULT);
    PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(derKey);
    KeyFactory keyFactory = KeyFactory.getInstance("RSA");
    return (PrivateKey) keyFactory.generatePrivate(keySpec);
}
Also used : PrivateKey(java.security.PrivateKey) PKCS8EncodedKeySpec(java.security.spec.PKCS8EncodedKeySpec) KeyFactory(java.security.KeyFactory)

Aggregations

PKCS8EncodedKeySpec (java.security.spec.PKCS8EncodedKeySpec)227 KeyFactory (java.security.KeyFactory)179 PrivateKey (java.security.PrivateKey)148 CertificateFactory (java.security.cert.CertificateFactory)86 ByteArrayInputStream (java.io.ByteArrayInputStream)85 Certificate (java.security.cert.Certificate)72 X509Certificate (java.security.cert.X509Certificate)71 PrivateKeyEntry (java.security.KeyStore.PrivateKeyEntry)59 Entry (java.security.KeyStore.Entry)53 TrustedCertificateEntry (java.security.KeyStore.TrustedCertificateEntry)53 InvalidKeySpecException (java.security.spec.InvalidKeySpecException)50 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)47 X509EncodedKeySpec (java.security.spec.X509EncodedKeySpec)40 PublicKey (java.security.PublicKey)39 IOException (java.io.IOException)30 RSAPrivateKey (java.security.interfaces.RSAPrivateKey)30 SecretKey (javax.crypto.SecretKey)28 InvalidKeyException (java.security.InvalidKeyException)26 Key (java.security.Key)24 KeyStoreException (java.security.KeyStoreException)15