Example usage for java.security PrivateKey getEncoded

List of usage examples for java.security PrivateKey getEncoded

Introduction

In this page you can find the example usage for java.security PrivateKey getEncoded.

Prototype

public byte[] getEncoded();

Source Link

Document

Returns the key in its primary encoding format, or null if this key does not support encoding.

Usage

From source file:com.mhise.util.MHISEUtil.java

public static void writeKey(PrivateKey pKey, Context context) throws Exception {

    String keyFile = "privateKey.key";
    FileOutputStream fos = context.openFileOutput(keyFile, Context.MODE_PRIVATE);
    byte[] kb = pKey.getEncoded();
    fos.write(kb);/*from w  ww  .j  a v  a 2  s  . c o  m*/
    fos.close();

}

From source file:com.vmware.certificate.Client.java

private String encodePrivateKeyToString(PrivateKey key) throws UnsupportedEncodingException {
    if (key == null) {
        return null;
    }//from   w  ww  . jav a2 s. co m
    byte[] privBytes = key.getEncoded();
    String encoded = new String(Base64.encodeBase64(privBytes));
    StringBuffer pemencode = new StringBuffer();
    for (int x = 0; x < encoded.length(); x++) {

        if ((x > 0) && (x % 64 == 0)) {
            pemencode.append("\n");
            pemencode.append(encoded.charAt(x));
        } else {
            pemencode.append(encoded.charAt(x));

        }
    }
    return "-----BEGIN PRIVATE KEY-----\n" + pemencode.toString() + "\n" + "-----END PRIVATE KEY-----";
}

From source file:test.integ.be.e_contract.sts.CXFSTSClientTest.java

private static X509Certificate getCertificate(PrivateKey privateKey, PublicKey publicKey) throws Exception {
    X500Name subjectName = new X500Name("CN=Test");
    X500Name issuerName = subjectName; // self-signed
    BigInteger serial = new BigInteger(128, new SecureRandom());
    SubjectPublicKeyInfo publicKeyInfo = SubjectPublicKeyInfo.getInstance(publicKey.getEncoded());
    DateTime notBefore = new DateTime();
    DateTime notAfter = notBefore.plusMonths(1);
    X509v3CertificateBuilder x509v3CertificateBuilder = new X509v3CertificateBuilder(issuerName, serial,
            notBefore.toDate(), notAfter.toDate(), subjectName, publicKeyInfo);
    AlgorithmIdentifier sigAlgId = new DefaultSignatureAlgorithmIdentifierFinder().find("SHA1withRSA");
    AlgorithmIdentifier digAlgId = new DefaultDigestAlgorithmIdentifierFinder().find(sigAlgId);
    AsymmetricKeyParameter asymmetricKeyParameter = PrivateKeyFactory.createKey(privateKey.getEncoded());

    ContentSigner contentSigner = new BcRSAContentSignerBuilder(sigAlgId, digAlgId)
            .build(asymmetricKeyParameter);
    X509CertificateHolder x509CertificateHolder = x509v3CertificateBuilder.build(contentSigner);

    byte[] encodedCertificate = x509CertificateHolder.getEncoded();

    CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
    X509Certificate certificate = (X509Certificate) certificateFactory
            .generateCertificate(new ByteArrayInputStream(encodedCertificate));
    return certificate;
}

From source file:org.oscarehr.sharingcenter.actions.SecurityInfrastructureServlet.java

private String createNewInfrastructure(String alias, String commonName, String organizationalUnit,
        String organization, String locality, String state, String country) {

    InfrastructureDao dao = SpringUtils.getBean(InfrastructureDao.class);

    if (alias == null) {
        return "error";
    }/*  w w w  . java2 s . c  om*/

    if (dao.aliasExists(alias)) {
        return "exists";
    } else {
        InfrastructureDataObject infrastructure = new InfrastructureDataObject();
        infrastructure.setAlias(alias);
        infrastructure.setCommonName(commonName);
        infrastructure.setOrganizationalUnit(organizationalUnit);
        infrastructure.setOrganization(organization);
        infrastructure.setLocality(locality);
        infrastructure.setState(state);
        infrastructure.setCountry(country);

        //Generate, encode, and set the public and private keys
        try {
            KeyPair keyPair = SslUtility.generateKeyPair();
            PublicKey publicKey = keyPair.getPublic();
            PrivateKey privateKey = keyPair.getPrivate();

            Base64 base64 = new Base64();
            String encodedPubKey = new String(base64.encode(publicKey.getEncoded()),
                    MiscUtils.DEFAULT_UTF8_ENCODING);
            String encodedPrivKey = new String(base64.encode(privateKey.getEncoded()),
                    MiscUtils.DEFAULT_UTF8_ENCODING);

            infrastructure.setBase64EncodedPublicKey(encodedPubKey);
            infrastructure.setBase64EncodedPrivateKey(encodedPrivKey);

            dao.persist(infrastructure);

        } catch (SslException e) {
            return "sslerror";
        } catch (UnsupportedEncodingException e) {
            return "encodingerror";
        }
    }

    return "success";

}

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

/**
 * Get the PKCS#8 encoded bytes for the key.
 *
 * @param privateKey The key to encode./*w ww  .j  a  va2s . c om*/
 * @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

/**
 * Convert a KeyStore to PEM format.//  w w  w . j  av  a2 s .co  m
 */
public static byte[] getSinglePemFromKeyStore(final KeyStore ks, final char[] password)
        throws KeyStoreException, CertificateEncodingException, IOException, UnrecoverableKeyException,
        NoSuchAlgorithmException {
    final ByteArrayOutputStream buffer = new ByteArrayOutputStream();

    // Find the key private key entry in the keystore
    final Enumeration<String> e = ks.aliases();
    Object o = null;
    String alias = "";
    PrivateKey serverPrivKey = null;
    while (e.hasMoreElements()) {
        o = e.nextElement();
        if (o instanceof String) {
            if ((ks.isKeyEntry((String) o))
                    && ((serverPrivKey = (PrivateKey) ks.getKey((String) o, password)) != null)) {
                alias = (String) o;
                break;
            }
        }
    }

    byte[] privKeyEncoded = "".getBytes();

    if (serverPrivKey != null) {
        privKeyEncoded = serverPrivKey.getEncoded();
    }

    final Certificate[] chain = KeyTools.getCertChain(ks, (String) o);
    final X509Certificate userX509Certificate = (X509Certificate) chain[0];

    final byte[] output = userX509Certificate.getEncoded();
    String sn = CertTools.getSubjectDN(userX509Certificate);

    String subjectdnpem = sn.replace(',', '/');
    String issuerdnpem = CertTools.getIssuerDN(userX509Certificate).replace(',', '/');

    buffer.write(BAG_ATTRIBUTES);
    buffer.write(FRIENDLY_NAME);
    buffer.write(alias.getBytes());
    buffer.write(NL);
    buffer.write(BEGIN_PRIVATE_KEY);
    buffer.write(NL);

    final byte[] privKey = Base64.encode(privKeyEncoded);
    buffer.write(privKey);
    buffer.write(NL);
    buffer.write(END_PRIVATE_KEY);
    buffer.write(NL);
    buffer.write(BAG_ATTRIBUTES);
    buffer.write(FRIENDLY_NAME);
    buffer.write(alias.getBytes());
    buffer.write(NL);
    buffer.write(SUBJECT_ATTRIBUTE);
    buffer.write(subjectdnpem.getBytes());
    buffer.write(NL);
    buffer.write(ISSUER_ATTRIBUTE);
    buffer.write(issuerdnpem.getBytes());
    buffer.write(NL);
    buffer.write(BEGIN_CERTIFICATE);
    buffer.write(NL);

    final byte[] userCertB64 = Base64.encode(output);
    buffer.write(userCertB64);
    buffer.write(NL);
    buffer.write(END_CERTIFICATE);
    buffer.write(NL);

    if (!CertTools.isSelfSigned(userX509Certificate)) {
        for (int num = 1; num < chain.length; num++) {
            final X509Certificate tmpX509Cert = (X509Certificate) chain[num];
            sn = CertTools.getSubjectDN(tmpX509Cert);

            String cn = CertTools.getPartFromDN(sn, "CN");
            if (StringUtils.isEmpty(cn)) {
                cn = "Unknown";
            }

            subjectdnpem = sn.replace(',', '/');
            issuerdnpem = CertTools.getIssuerDN(tmpX509Cert).replace(',', '/');

            buffer.write(BAG_ATTRIBUTES);
            buffer.write(FRIENDLY_NAME);
            buffer.write(cn.getBytes());
            buffer.write(NL);
            buffer.write(SUBJECT_ATTRIBUTE);
            buffer.write(subjectdnpem.getBytes());
            buffer.write(NL);
            buffer.write(ISSUER_ATTRIBUTE);
            buffer.write(issuerdnpem.getBytes());
            buffer.write(NL);

            final byte[] tmpOutput = tmpX509Cert.getEncoded();
            buffer.write(BEGIN_CERTIFICATE);
            buffer.write(NL);

            final byte[] tmpCACertB64 = Base64.encode(tmpOutput);
            buffer.write(tmpCACertB64);
            buffer.write(NL);
            buffer.write(END_CERTIFICATE);
            buffer.write(NL);
        }
    }
    return buffer.toByteArray();
}

From source file:nl.b3p.viewer.admin.stripes.CycloramaConfigurationActionBean.java

private String getBase64EncodedPrivateKeyFromPfxUpload(InputStream in, String password)
        throws KeyStoreException, IOException, NoSuchAlgorithmException, CertificateException,
        UnrecoverableKeyException {

    String base64 = null;//from  ww w.j  a  va  2 s . c om

    PrivateKey privateKey = null;

    KeyStore ks = java.security.KeyStore.getInstance(CERT_TYPE);
    ks.load(new BufferedInputStream(in), password.toCharArray());

    Enumeration<String> aliases = ks.aliases();

    while (aliases.hasMoreElements()) {
        String alias = aliases.nextElement();

        Key ksKey = ks.getKey(alias, password.toCharArray());
        String keyFormat = ksKey.getFormat();

        if ((ksKey instanceof RSAPrivateCrtKeyImpl) && keyFormat.equals(KEY_FORMAT)) {
            privateKey = (PrivateKey) ksKey;
        }
    }

    if (privateKey != null) {
        Base64 encoder = new Base64();
        base64 = new String(encoder.encode(privateKey.getEncoded()));
    }

    return base64;
}

From source file:org.tolven.config.model.CredentialManager.java

private void writeDER(char[] password, PrivateKey privateKey, File file)
        throws IOException, GeneralSecurityException {
    byte[] bytes = null;
    if (password == null) {
        bytes = privateKey.getEncoded();
    } else {/*from  w w  w.  ja  v  a  2  s  .c o m*/
        SecretKeyFactory secretKeyFactory = SecretKeyFactory.getInstance("PBEWithMD5AndDES");
        PBEKeySpec passwordSpec = new PBEKeySpec(password);
        SecretKey secretKey = secretKeyFactory.generateSecret(passwordSpec);
        Cipher cipher = Cipher.getInstance(secretKey.getAlgorithm());
        cipher.init(Cipher.ENCRYPT_MODE, secretKey);
        byte[] encryptedPrivateKey = cipher.doFinal(privateKey.getEncoded());
        EncryptedPrivateKeyInfo encryptedPrivateKeyInfo = new EncryptedPrivateKeyInfo(cipher.getParameters(),
                encryptedPrivateKey);
        bytes = encryptedPrivateKeyInfo.getEncoded();
    }
    FileUtils.writeByteArrayToFile(file, bytes);
}

From source file:org.wso2.carbon.security.keystore.KeyStoreAdmin.java

/**
 * This method will list 1. Certificate aliases 2. Private key alise 3. Private key value to a
 * given keystore./*from   www  .  j av a 2s.c  om*/
 *
 * @param keyStoreName The name of the keystore
 * @return Instance of KeyStoreData
 * @throws SecurityConfigException will be thrown
 */
public KeyStoreData getKeystoreInfo(String keyStoreName) throws SecurityConfigException {
    try {

        if (keyStoreName == null) {
            throw new Exception("keystore name cannot be null");
        }

        KeyStore keyStore;
        String keyStoreType;
        String privateKeyPassowrd = null;
        if (KeyStoreUtil.isPrimaryStore(keyStoreName)) {
            KeyStoreManager keyMan = KeyStoreManager.getInstance(tenantId);
            keyStore = keyMan.getPrimaryKeyStore();
            ServerConfiguration serverConfig = ServerConfiguration.getInstance();
            keyStoreType = serverConfig
                    .getFirstProperty(RegistryResources.SecurityManagement.SERVER_PRIMARY_KEYSTORE_TYPE);
            privateKeyPassowrd = serverConfig
                    .getFirstProperty(RegistryResources.SecurityManagement.SERVER_PRIVATE_KEY_PASSWORD);
        } else {
            String path = SecurityConstants.KEY_STORES + "/" + keyStoreName;
            if (!registry.resourceExists(path)) {
                throw new SecurityConfigException("Key Store not found");
            }
            Resource resource = registry.get(path);
            KeyStoreManager manager = KeyStoreManager.getInstance(tenantId);
            keyStore = manager.getKeyStore(keyStoreName);
            keyStoreType = resource.getProperty(SecurityConstants.PROP_TYPE);

            String encpass = resource.getProperty(SecurityConstants.PROP_PRIVATE_KEY_PASS);
            if (encpass != null) {
                CryptoUtil util = CryptoUtil.getDefaultCryptoUtil();
                privateKeyPassowrd = new String(util.base64DecodeAndDecrypt(encpass));
            }
        }
        // Fill the information about the certificates
        Enumeration<String> aliases = keyStore.aliases();
        List<org.wso2.carbon.security.keystore.service.CertData> certDataList = new ArrayList<>();
        Format formatter = new SimpleDateFormat("dd/MM/yyyy");

        while (aliases.hasMoreElements()) {
            String alias = aliases.nextElement();
            if (keyStore.isCertificateEntry(alias)) {
                X509Certificate cert = (X509Certificate) keyStore.getCertificate(alias);
                certDataList.add(fillCertData(cert, alias, formatter));
            }
        }

        // Create a cert array
        CertData[] certs = certDataList.toArray(new CertData[certDataList.size()]);

        // Create a KeyStoreData bean, set the name and fill in the cert information
        KeyStoreData keyStoreData = new KeyStoreData();
        keyStoreData.setKeyStoreName(keyStoreName);
        keyStoreData.setCerts(certs);
        keyStoreData.setKeyStoreType(keyStoreType);

        aliases = keyStore.aliases();
        while (aliases.hasMoreElements()) {
            String alias = aliases.nextElement();
            // There be only one entry in WSAS related keystores
            if (keyStore.isKeyEntry(alias)) {
                X509Certificate cert = (X509Certificate) keyStore.getCertificate(alias);
                keyStoreData.setKey(fillCertData(cert, alias, formatter));

                PrivateKey key = (PrivateKey) keyStore.getKey(alias, privateKeyPassowrd.toCharArray());
                String pemKey;
                pemKey = "-----BEGIN PRIVATE KEY-----\n";
                pemKey += Base64.encode(key.getEncoded());
                pemKey += "\n-----END PRIVATE KEY-----";
                keyStoreData.setKeyValue(pemKey);
                break;

            }
        }
        return keyStoreData;
    } catch (Exception e) {
        String msg = "Error has encounted while loading the keystore to the given keystore name "
                + keyStoreName;
        log.error(msg, e);
        throw new SecurityConfigException(msg);
    }

}

From source file:org.wso2.carbon.security.keystore.KeyStoreAdmin.java

/**
 * This method will list 1. Certificate aliases 2. Private key alise 3. Private key value to a
 * given keystore.//from  ww w.j av a 2s  .  co  m
 *
 * @param keyStoreName The name of the keystore
 * @param pageNumber   page number
 * @return Instance of KeyStoreData
 * @throws SecurityConfigException will be thrown
 */
public PaginatedKeyStoreData getPaginatedKeystoreInfo(String keyStoreName, int pageNumber)
        throws SecurityConfigException {
    try {

        if (keyStoreName == null) {
            throw new Exception("keystore name cannot be null");
        }

        KeyStore keyStore;
        String keyStoreType;
        String privateKeyPassowrd = null;
        if (KeyStoreUtil.isPrimaryStore(keyStoreName)) {
            KeyStoreManager keyMan = KeyStoreManager.getInstance(tenantId);
            keyStore = keyMan.getPrimaryKeyStore();
            ServerConfiguration serverConfig = ServerConfiguration.getInstance();
            keyStoreType = serverConfig
                    .getFirstProperty(RegistryResources.SecurityManagement.SERVER_PRIMARY_KEYSTORE_TYPE);
            privateKeyPassowrd = serverConfig
                    .getFirstProperty(RegistryResources.SecurityManagement.SERVER_PRIVATE_KEY_PASSWORD);
        } else {
            String path = SecurityConstants.KEY_STORES + "/" + keyStoreName;
            if (!registry.resourceExists(path)) {
                throw new SecurityConfigException("Key Store not found");
            }
            Resource resource = registry.get(path);
            KeyStoreManager manager = KeyStoreManager.getInstance(tenantId);
            keyStore = manager.getKeyStore(keyStoreName);
            keyStoreType = resource.getProperty(SecurityConstants.PROP_TYPE);

            String encpass = resource.getProperty(SecurityConstants.PROP_PRIVATE_KEY_PASS);
            if (encpass != null) {
                CryptoUtil util = CryptoUtil.getDefaultCryptoUtil();
                privateKeyPassowrd = new String(util.base64DecodeAndDecrypt(encpass));
            }
        }
        // Fill the information about the certificates
        Enumeration<String> aliases = keyStore.aliases();
        List<org.wso2.carbon.security.keystore.service.CertData> certDataList = new ArrayList<>();
        Format formatter = new SimpleDateFormat("dd/MM/yyyy");

        while (aliases.hasMoreElements()) {
            String alias = aliases.nextElement();
            if (keyStore.isCertificateEntry(alias)) {
                X509Certificate cert = (X509Certificate) keyStore.getCertificate(alias);
                certDataList.add(fillCertData(cert, alias, formatter));
            }
        }

        // Create a cert array
        CertData[] certs = certDataList.toArray(new CertData[certDataList.size()]);

        // Create a KeyStoreData bean, set the name and fill in the cert information
        PaginatedKeyStoreData keyStoreData = new PaginatedKeyStoreData();
        keyStoreData.setKeyStoreName(keyStoreName);
        keyStoreData.setPaginatedCertData(doPaging(pageNumber, certs));
        keyStoreData.setKeyStoreType(keyStoreType);

        aliases = keyStore.aliases();
        while (aliases.hasMoreElements()) {
            String alias = aliases.nextElement();
            // There be only one entry in WSAS related keystores
            if (keyStore.isKeyEntry(alias)) {
                X509Certificate cert = (X509Certificate) keyStore.getCertificate(alias);
                keyStoreData.setKey(fillCertData(cert, alias, formatter));

                PrivateKey key = (PrivateKey) keyStore.getKey(alias, privateKeyPassowrd.toCharArray());
                String pemKey;
                pemKey = "-----BEGIN PRIVATE KEY-----\n";
                pemKey += Base64.encode(key.getEncoded());
                pemKey += "\n-----END PRIVATE KEY-----";
                keyStoreData.setKeyValue(pemKey);
                break;

            }
        }
        return keyStoreData;
    } catch (Exception e) {
        String msg = "Error has encounted while loading the keystore to the given keystore name "
                + keyStoreName;
        log.error(msg, e);
        throw new SecurityConfigException(msg);
    }

}