Example usage for java.security PrivateKey getFormat

List of usage examples for java.security PrivateKey getFormat

Introduction

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

Prototype

public String getFormat();

Source Link

Document

Returns the name of the primary encoding format of this key, or null if this key does not support encoding.

Usage

From source file:Main.java

public static void main(String[] argv) throws Exception {
    String algorithm = "DSA"; // or RSA, DH, etc.

    // Generate a 1024-bit Digital Signature Algorithm (DSA) key pair
    KeyPairGenerator keyGen = KeyPairGenerator.getInstance(algorithm);
    keyGen.initialize(1024);// w ww. j av  a2s  . c  om
    KeyPair keypair = keyGen.genKeyPair();
    PrivateKey privateKey = keypair.getPrivate();
    PublicKey publicKey = keypair.getPublic();
    String format = privateKey.getFormat(); // PKCS#8
    format = publicKey.getFormat(); // X.509
}

From source file:MainClass.java

public static void main(String args[]) throws Exception {
    MainClass kpge = new MainClass();
    KeyPair kp = kpge.generateKeyPair(999);
    System.out.println("\n-- Private Key ----");
    PrivateKey priKey = kp.getPrivate();
    System.out.println("   Algorithm=" + priKey.getAlgorithm());
    System.out.println("   Encoded=" + priKey.getEncoded());
    System.out.println("   Format=" + priKey.getFormat());
}

From source file:com.wandrell.util.ksgen.BouncyCastleKeyStoreFactory.java

/**
 * Returns a signed certificate.// www.  j  av  a 2s . c o m
 *
 * @param builder
 *            builder to create the certificate
 * @param key
 *            private key for the certificate
 * @return a signed certificate
 * @throws OperatorCreationException
 *             if there was a problem creation a bouncy castle operator
 * @throws CertificateException
 *             if any of the certificates in the keystore could not be
 *             loaded
 */
private final X509Certificate getSignedCertificate(final X509v3CertificateBuilder builder, final PrivateKey key)
        throws OperatorCreationException, CertificateException {
    final ContentSigner signer; // Content signer
    final String provider; // Provider
    final X509Certificate signed; // Signed certificate

    provider = BouncyCastleProvider.PROVIDER_NAME;
    signer = new JcaContentSignerBuilder(getSignatureAlgorithm()).setProvider(provider).build(key);

    signed = new JcaX509CertificateConverter().setProvider(provider).getCertificate(builder.build(signer));

    LOGGER.debug("Signed certificate with {} private key {}, using algorithm {}", key.getAlgorithm(),
            Arrays.asList(key.getEncoded()), key.getFormat());

    return signed;
}

From source file:org.ejbca.core.ejb.ca.caadmin.CAAdminSessionBean.java

@Override
@TransactionAttribute(TransactionAttributeType.SUPPORTS)
public byte[] exportCAKeyStore(AuthenticationToken admin, String caname, String keystorepass,
        String privkeypass, String privateSignatureKeyAlias, String privateEncryptionKeyAlias) {
    log.trace(">exportCAKeyStore");
    try {/*from   w ww. j av a2 s . c  om*/
        final CA thisCa = caSession.getCAForEdit(admin, caname);
        // Make sure we are not trying to export a hard or invalid token
        CAToken thisCAToken = thisCa.getCAToken();
        final CryptoToken cryptoToken = cryptoTokenSession.getCryptoToken(thisCAToken.getCryptoTokenId());
        if (!(cryptoToken instanceof SoftCryptoToken)) {
            throw new IllegalCryptoTokenException("Cannot export anything but a soft token.");
        }
        // Do not allow export without password protection
        if (StringUtils.isEmpty(keystorepass) || StringUtils.isEmpty(privkeypass)) {
            throw new IllegalArgumentException("Cannot export a token without password protection.");
        }
        // Check authorization
        if (!accessSession.isAuthorizedNoLogging(admin, StandardRules.ROLE_ROOT.resource())) {
            String msg = intres.getLocalizedMessage("caadmin.notauthorizedtoexportcatoken", caname);
            Map<String, Object> details = new LinkedHashMap<String, Object>();
            details.put("msg", msg);
            auditSession.log(EventTypes.ACCESS_CONTROL, EventStatus.FAILURE, ModuleTypes.CA, ServiceTypes.CORE,
                    admin.toString(), String.valueOf(thisCa.getCAId()), null, null, details);
            throw new AuthorizationDeniedException(msg);
        }
        // Fetch keys
        final char[] password = keystorepass.toCharArray();
        ((SoftCryptoToken) cryptoToken).checkPasswordBeforeExport(password);
        cryptoToken.activate(password);

        PrivateKey p12PrivateEncryptionKey = cryptoToken
                .getPrivateKey(thisCAToken.getAliasFromPurpose(CATokenConstants.CAKEYPURPOSE_KEYENCRYPT));
        PublicKey p12PublicEncryptionKey = cryptoToken
                .getPublicKey(thisCAToken.getAliasFromPurpose(CATokenConstants.CAKEYPURPOSE_KEYENCRYPT));
        PrivateKey p12PrivateCertSignKey = cryptoToken
                .getPrivateKey(thisCAToken.getAliasFromPurpose(CATokenConstants.CAKEYPURPOSE_CERTSIGN));
        PrivateKey p12PrivateCRLSignKey = cryptoToken
                .getPrivateKey(thisCAToken.getAliasFromPurpose(CATokenConstants.CAKEYPURPOSE_CRLSIGN));
        if (!p12PrivateCertSignKey.equals(p12PrivateCRLSignKey)) {
            throw new Exception("Assertion of equal signature keys failed.");
        }
        // Proceed with the export
        byte[] ret = null;
        String format = null;
        if (thisCa.getCAType() == CAInfo.CATYPE_CVC) {
            log.debug("Exporting private key with algorithm: " + p12PrivateCertSignKey.getAlgorithm()
                    + " of format: " + p12PrivateCertSignKey.getFormat());
            format = p12PrivateCertSignKey.getFormat();
            ret = p12PrivateCertSignKey.getEncoded();
        } else {
            log.debug("Exporting PKCS12 keystore");
            format = "PKCS12";
            KeyStore keystore = KeyStore.getInstance("PKCS12", "BC");
            keystore.load(null, keystorepass.toCharArray());
            // Load keys into keystore
            Certificate[] certificateChainSignature = (Certificate[]) thisCa.getCertificateChain()
                    .toArray(new Certificate[0]);
            Certificate[] certificateChainEncryption = new Certificate[1];
            // certificateChainSignature[0].getSigAlgName(),
            // generate dummy certificate for encryption key.
            certificateChainEncryption[0] = CertTools.genSelfCertForPurpose("CN=dummy2", 36500, null,
                    p12PrivateEncryptionKey, p12PublicEncryptionKey, thisCAToken.getEncryptionAlgorithm(), true,
                    X509KeyUsage.keyEncipherment, true);
            log.debug("Exporting with sigAlgorithm "
                    + AlgorithmTools.getSignatureAlgorithm(certificateChainSignature[0]) + "encAlgorithm="
                    + thisCAToken.getEncryptionAlgorithm());
            if (keystore.isKeyEntry(privateSignatureKeyAlias)) {
                throw new Exception("Key \"" + privateSignatureKeyAlias + "\"already exists in keystore.");
            }
            if (keystore.isKeyEntry(privateEncryptionKeyAlias)) {
                throw new Exception("Key \"" + privateEncryptionKeyAlias + "\"already exists in keystore.");
            }

            keystore.setKeyEntry(privateSignatureKeyAlias, p12PrivateCertSignKey, privkeypass.toCharArray(),
                    certificateChainSignature);
            keystore.setKeyEntry(privateEncryptionKeyAlias, p12PrivateEncryptionKey, privkeypass.toCharArray(),
                    certificateChainEncryption);
            // Return KeyStore as byte array and clean up
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            keystore.store(baos, keystorepass.toCharArray());
            if (keystore.isKeyEntry(privateSignatureKeyAlias)) {
                keystore.deleteEntry(privateSignatureKeyAlias);
            }
            if (keystore.isKeyEntry(privateEncryptionKeyAlias)) {
                keystore.deleteEntry(privateEncryptionKeyAlias);
            }
            ret = baos.toByteArray();
        }
        String msg = intres.getLocalizedMessage("caadmin.exportedca", caname, format);
        Map<String, Object> details = new LinkedHashMap<String, Object>();
        details.put("msg", msg);
        auditSession.log(EjbcaEventTypes.CA_EXPORTTOKEN, EventStatus.SUCCESS, ModuleTypes.CA, ServiceTypes.CORE,
                admin.toString(), String.valueOf(thisCa.getCAId()), null, null, details);
        log.trace("<exportCAKeyStore");
        return ret;
    } catch (Exception e) {
        String msg = intres.getLocalizedMessage("caadmin.errorexportca", caname, "PKCS12", e.getMessage());
        Map<String, Object> details = new LinkedHashMap<String, Object>();
        details.put("msg", msg);
        auditSession.log(EjbcaEventTypes.CA_EXPORTTOKEN, EventStatus.FAILURE, ModuleTypes.CA, ServiceTypes.CORE,
                admin.toString(), null, null, null, details);
        throw new EJBException(e);
    }
}

From source file:org.globus.gsi.bc.BouncyCastleOpenSSLKey.java

protected byte[] getEncoded(PrivateKey key) {
    String format = key.getFormat();
    if (format != null && (format.equalsIgnoreCase("PKCS#8") || format.equalsIgnoreCase("PKCS8"))) {
        try {//  www .j a  v  a  2s  .  c  om
            ASN1Primitive keyInfo = BouncyCastleUtil.toASN1Primitive(key.getEncoded());
            PrivateKeyInfo pkey = new PrivateKeyInfo((ASN1Sequence) keyInfo);
            ASN1Primitive derKey = pkey.getPrivateKey();
            return BouncyCastleUtil.toByteArray(derKey);
        } catch (IOException e) {
            // that should never happen
            logger.warn("This shouldn't have happened.", e);
            return new byte[] {};
        }
    } else if (format != null && format.equalsIgnoreCase("PKCS#1") && key instanceof RSAPrivateCrtKey) {
        // this condition will rarely be true
        RSAPrivateCrtKey pKey = (RSAPrivateCrtKey) key;
        RSAPrivateKeyStructure st = new RSAPrivateKeyStructure(pKey.getModulus(), pKey.getPublicExponent(),
                pKey.getPrivateExponent(), pKey.getPrimeP(), pKey.getPrimeQ(), pKey.getPrimeExponentP(),
                pKey.getPrimeExponentQ(), pKey.getCrtCoefficient());
        ASN1Primitive ob = st.toASN1Primitive();

        try {
            return BouncyCastleUtil.toByteArray(ob);
        } catch (IOException e) {
            // that should never happen
            return new byte[0];
        }
    } else {
        return new byte[0];
    }
}

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

private static void initializeKeyStore(KeyStore keyStore, Configuration config)
        throws CertificateException, IOException, InvalidKeyException, KeyStoreException,
        NoSuchAlgorithmException, NoSuchProviderException, SignatureException, UnrecoverableKeyException {
    String keyAlias = config.get(PROP_KEY_ALIAS, DEFAULT_KEY_ALIAS);
    String certAlias = config.get(PROP_CERT_ALIAS, DEFAULT_CERT_ALIAS);
    String keyAlgName = config.get(PROP_KEY_ALGORITHM, DEFAULT_KEY_ALGORITHM);
    String sigAlgName = config.get(PROP_SIG_ALGORITHM, DEFAULT_SIG_ALGORITHM);
    String keyStorePassword = config.get(PROP_KEYSTORE_PASSWORD);
    String keyPassword = config.get(PROP_KEY_PASSWORD);
    int keyBits = config.getInt(PROP_KEY_BITS, DEFAULT_KEY_BITS);
    long expireIn = config.getTimeInterval(PROP_EXPIRE_IN, DEFAULT_EXPIRE_IN);
    String x500String = config.get(PROP_X500_NAME, DEFAULT_X500_NAME);

    CertAndKeyGen keypair = new CertAndKeyGen(keyAlgName, sigAlgName);
    keypair.generate(keyBits);//from   ww w  . j  av a  2s .  c  o  m

    PrivateKey privKey = keypair.getPrivateKey();
    log.debug3("PrivKey: " + privKey.getAlgorithm() + " " + privKey.getFormat());

    X509Certificate[] chain = new X509Certificate[1];

    X500Name x500Name = new X500Name(x500String);
    chain[0] = keypair.getSelfCertificate(x500Name, expireIn);
    log.debug3("Certificate: " + chain[0].toString());

    keyStore.load(null, keyStorePassword.toCharArray());
    keyStore.setCertificateEntry(certAlias, chain[0]);
    keyStore.setKeyEntry(keyAlias, privKey, keyPassword.toCharArray(), chain);
    Key myKey = keyStore.getKey(keyAlias, keyPassword.toCharArray());
    log.debug("MyKey: " + myKey.getAlgorithm() + " " + myKey.getFormat());
}

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

private static void initializeKeyStore(KeyStore keyStore, String domainName, String password)
        throws IOException, CertificateException, InvalidKeyException, SignatureException,
        NoSuchAlgorithmException, NoSuchProviderException, KeyStoreException, UnrecoverableKeyException {
    String keyAlias = domainName + keySuffix;
    String certAlias = domainName + crtSuffix;
    String keyStorePassword = domainName;
    String keyStoreFileName = domainName + ".jceks";
    File keyStoreFile = new File(keyStoreFileName);
    if (keyStoreFile.exists()) {
        log.debug("Key store file " + keyStoreFileName + " exists");
        throw new IOException("Key store file " + keyStoreFileName + " exists");
    }/*from w w w  .j  a  va  2s  .c  o m*/
    String keyAlgName = "RSA";
    String sigAlgName = "MD5WithRSA";
    log.debug("About to create a CertAndKeyGen: " + keyAlgName + " " + sigAlgName);
    CertAndKeyGen keypair;
    try {
        keypair = new CertAndKeyGen(keyAlgName, sigAlgName);
    } catch (NoSuchAlgorithmException e) {
        log.debug("new CertAndKeyGen(" + keyAlgName + "," + sigAlgName + ") threw " + e);
        throw e;
    }
    log.debug("About to generate a key pair");
    try {
        keypair.generate(1024);
    } catch (InvalidKeyException e) {
        log.debug("keypair.generate(1024) threw " + e);
        throw e;
    }
    log.debug("About to get a PrivateKey");
    PrivateKey privKey = keypair.getPrivateKey();
    log.debug("MyKey: " + privKey.getAlgorithm() + " " + privKey.getFormat());
    log.debug("About to get a self-signed certificate");
    X509Certificate[] chain = new X509Certificate[1];
    X500Name x500Name = new X500Name(
            "CN=" + domainName + ", " + "OU=LOCKSS Team, O=Stanford, " + "L=Stanford, S=California, C=US");
    chain[0] = keypair.getSelfCertificate(x500Name, 365 * 24 * 60 * 60);
    log.debug("Certificate: " + chain[0].toString());
    log.debug("About to keyStore.load(null)");
    try {
        keyStore.load(null, keyStorePassword.toCharArray());
    } catch (IOException e) {
        log.debug("keyStore.load() threw " + e);
        throw e;
    } catch (CertificateException e) {
        log.debug("keyStore.load() threw " + e);
        throw e;
    } catch (NoSuchAlgorithmException e) {
        log.debug("keyStore.load() threw " + e);
        throw e;
    }
    log.debug("About to store " + certAlias + " in key store");
    try {
        keyStore.setCertificateEntry(certAlias, chain[0]);
    } catch (KeyStoreException e) {
        log.debug("keyStore.setCertificateEntry() threw " + e);
        throw e;
    }
    log.debug("About to store " + keyAlias + " in key store");
    try {
        keyStore.setKeyEntry(keyAlias, privKey, password.toCharArray(), chain);
    } catch (KeyStoreException e) {
        log.debug("keyStore.setKeyEntry() threw " + e);
        throw e;
    }
    log.debug("About to getKeyEntry()");
    Key myKey = keyStore.getKey(keyAlias, password.toCharArray());
    log.debug("MyKey: " + myKey.getAlgorithm() + " " + myKey.getFormat());
    log.debug("Done storing");
}