Example usage for java.security.spec PKCS8EncodedKeySpec PKCS8EncodedKeySpec

List of usage examples for java.security.spec PKCS8EncodedKeySpec PKCS8EncodedKeySpec

Introduction

In this page you can find the example usage for java.security.spec PKCS8EncodedKeySpec PKCS8EncodedKeySpec.

Prototype

public PKCS8EncodedKeySpec(byte[] encodedKey) 

Source Link

Document

Creates a new PKCS8EncodedKeySpec with the given encoded key.

Usage

From source file:com.xinferin.licensing.LicenceGenerator.java

/**
 * Main method to initialise the private key from the database
 * @throws Exception/*  www .  ja va  2 s  .  co m*/
 */
private void initialisePrivateKey() throws Exception {

    if (encodedPrivateKey == null)
        throw new Exception("An encoded Base64 private key has not been specified.");

    try {
        //Read key files back and decode them from BASE64
        byte[] privateKeyBytes = Base64.decodeBase64(encodedPrivateKey);

        // Convert back to public and private key objects
        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        EncodedKeySpec privateKeySpec = new PKCS8EncodedKeySpec(privateKeyBytes);
        privateKey = keyFactory.generatePrivate(privateKeySpec);

    } catch (InvalidKeySpecException e) {
        throw new Exception("Invalid key specifications. Not a valid key entry." + e.getCause());
    } catch (NoSuchAlgorithmException e) {
        throw new Exception("There is no such algorithm. Please check the JDK ver." + e.getCause());
    }
}

From source file:RGSDigestTools.SignatureTool.java

public void initKeysWithFiles(String PrivkeyResource, String PubkeyResource)
        throws KeyStoreException, CertificateException, NoSuchAlgorithmException, IOException,
        UnrecoverableEntryException, InvalidKeySpecException {
    //        KeyStore ks = TrustStoreLoader.loadKeyStore(pKeyStorePath,pKeyStorePasswd);
    //        KeyStore.PasswordProtection passProtection = new KeyStore.PasswordProtection(pPrivKeyPasswd.toCharArray());
    //        KeyStore.PrivateKeyEntry DSKeyEnt = (KeyStore.PrivateKeyEntry)ks.getEntry(pDSAlias, passProtection);
    //      //from   w ww. j a  v  a 2 s. com
    InputStream is_piv = SignatureTool.class.getResourceAsStream(PrivkeyResource);
    ByteArrayOutputStream baos_priv = new ByteArrayOutputStream();
    int read_priv = is_piv.read();
    while (read_priv != -1) {
        baos_priv.write(read_priv);
        read_priv = is_piv.read();
    }
    byte[] keyBytes_priv = baos_priv.toByteArray();
    PKCS8EncodedKeySpec spec_pkcs8 = new PKCS8EncodedKeySpec(keyBytes_priv);
    KeyFactory keyFactoryPriv = KeyFactory.getInstance("RSA");
    this.signKey = keyFactoryPriv.generatePrivate(spec_pkcs8);

    //        this.signKey = DSKeyEnt.getPrivateKey();

    InputStream is = SignatureTool.class.getResourceAsStream(PubkeyResource);
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    int read = is.read();
    while (read != -1) {
        baos.write(read);
        read = is.read();
    }

    byte[] keyBytes = baos.toByteArray();
    X509EncodedKeySpec spec = new X509EncodedKeySpec(keyBytes);
    KeyFactory keyFactory = KeyFactory.getInstance("RSA");
    this.verifyKey = keyFactory.generatePublic(spec);
}

From source file:org.samlsnort.util.KeyStoreTool.java

public static void importIntoKeystore(File certificateChainFile, File privateKeyFile, String alias)
        throws Exception {

    FileInputStream certificateStream = new FileInputStream(certificateChainFile);
    CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
    Certificate[] chain = {};/*from  w w  w  . j  a  v a  2  s  . co m*/
    chain = certificateFactory.generateCertificates(certificateStream).toArray(chain);
    certificateStream.close();

    byte[] encodedKey = new byte[(int) privateKeyFile.length()];
    FileInputStream keyInputStream = new FileInputStream(privateKeyFile);
    keyInputStream.read(encodedKey);
    keyInputStream.close();
    KeyFactory rSAKeyFactory = KeyFactory.getInstance("RSA");
    PrivateKey privateKey = rSAKeyFactory.generatePrivate(new PKCS8EncodedKeySpec(encodedKey));

    keyStore.setEntry(alias, new KeyStore.PrivateKeyEntry(privateKey, chain),
            new KeyStore.PasswordProtection(Configuration.getInstance().getKeystorePassword().toCharArray()));

    saveKeystore();
}

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;/*from   www .j a  v a 2  s. c om*/
    } 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:org.ejbca.core.protocol.ws.client.CvcRequestCommand.java

/**
 * Runs the command//  w  ww .  j  a  v a 2 s  .  com
 *
 * @throws IllegalAdminCommandException Error in command args
 * @throws ErrorAdminCommandException Error running command
 */
public void execute() throws IllegalAdminCommandException, ErrorAdminCommandException {

    try {
        if (args.length < 9 || args.length > 11) {
            getPrintStream().println("Number of arguments: " + args.length);
            usage();
            System.exit(-1); // NOPMD, this is not a JEE app
        }

        String username = args[ARG_USERNAME];
        String userpassword = args[ARG_PASSWORD];
        String dn = args[ARG_SUBJECTDN];
        String sequence = args[ARG_SEQUENCE];
        String signatureAlg = args[ARG_SIGNALG];
        String keySpec = args[ARG_KEYSPEC];
        boolean genrequest = args[ARG_GENREQ].equalsIgnoreCase("true");
        String basefilename = args[ARG_BASEFILENAME];
        String authSignKeyFile = null;
        if (args.length > (ARG_AUTHSIGNKEY)) {
            authSignKeyFile = args[ARG_AUTHSIGNKEY];
        }
        String authSignCertFile = null;
        if (args.length > (ARG_AUTHSIGNCERT)) {
            authSignCertFile = args[ARG_AUTHSIGNCERT];
        }

        getPrintStream().println("Enrolling user:");
        getPrintStream().println("Username: " + username);
        getPrintStream().println("Subject name: " + dn);
        getPrintStream().println("Sequence: " + sequence);
        getPrintStream().println("Signature algorithm: " + signatureAlg);
        getPrintStream().println("Key spec: " + keySpec);

        try {
            CryptoProviderTools.installBCProvider();

            String cvcreq = null;
            if (genrequest) {
                getPrintStream().println("Generating a new request with base filename: " + basefilename);
                // Generate keys for the request
                String keytype = "RSA";
                if (signatureAlg.contains("ECDSA")) {
                    keytype = "ECDSA";
                }
                KeyPair keyPair = KeyTools.genKeys(keySpec, keytype);
                String country = CertTools.getPartFromDN(dn, "C");
                String mnemonic = CertTools.getPartFromDN(dn, "CN");
                if (sequence.equalsIgnoreCase("null")) {
                    sequence = RandomStringUtils.randomNumeric(5);
                    getPrintStream().println("No sequence given, using random 5 number sequence: " + sequence);
                }
                //CAReferenceField caRef = new CAReferenceField(country,mnemonic,sequence);
                CAReferenceField caRef = null; // Don't create a caRef in the self signed request
                // We are making a self signed request, so holder ref is same as ca ref
                HolderReferenceField holderRef = new HolderReferenceField(country, mnemonic, sequence);
                CVCertificate request = CertificateGenerator.createRequest(keyPair, signatureAlg, caRef,
                        holderRef);
                byte[] der = request.getDEREncoded();
                if (authSignKeyFile != null) {
                    getPrintStream().println("Reading private key from pkcs8 file " + authSignKeyFile
                            + " to create an authenticated request");
                    byte[] keybytes = FileTools.readFiletoBuffer(authSignKeyFile);
                    KeyFactory keyfact = KeyFactory.getInstance(keytype, "BC");
                    PrivateKey privKey = keyfact.generatePrivate(new PKCS8EncodedKeySpec(keybytes));
                    KeyPair authKeyPair = new KeyPair(null, privKey); // We don't need the public key
                    // Default caRef if we do not pass in a certificate to get caRef from
                    CAReferenceField authCaRef = new CAReferenceField(country, mnemonic, sequence);
                    CVCertificate authCert = null;
                    if (authSignCertFile != null) {
                        getPrintStream().println("Reading cert from cvcert file " + authSignCertFile
                                + " to create an authenticated request");
                        CVCObject parsedObject = CvcPrintCommand.getCVCObject(authSignCertFile);
                        authCert = (CVCertificate) parsedObject;
                        String c = authCert.getCertificateBody().getHolderReference().getCountry();
                        String m = authCert.getCertificateBody().getHolderReference().getMnemonic();
                        String s = authCert.getCertificateBody().getHolderReference().getSequence();
                        authCaRef = new CAReferenceField(c, m, s);
                    }
                    CVCAuthenticatedRequest authRequest = CertificateGenerator
                            .createAuthenticatedRequest(request, authKeyPair, signatureAlg, authCaRef);
                    // Test to verify it yourself first
                    if (authCert != null) {
                        getPrintStream().println("Verifying the request before sending it...");
                        PublicKey pk = KeyTools.getECPublicKeyWithParams(
                                authCert.getCertificateBody().getPublicKey(), keySpec);
                        authRequest.verify(pk);
                    }
                    der = authRequest.getDEREncoded();
                }
                cvcreq = new String(Base64.encode(der));
                // Print the generated request to file
                FileOutputStream fos = new FileOutputStream(basefilename + ".cvreq");
                fos.write(der);
                fos.close();
                getPrintStream().println("Wrote binary request to: " + basefilename + ".cvreq");
                fos = new FileOutputStream(basefilename + ".pkcs8");
                fos.write(keyPair.getPrivate().getEncoded());
                fos.close();
                getPrintStream().println("Wrote private key in " + keyPair.getPrivate().getFormat()
                        + " format to to: " + basefilename + ".pkcs8");
            } else {
                // Read request from file
                getPrintStream().println("Reading request from filename: " + basefilename + ".cvreq");
                byte[] der = FileTools.readFiletoBuffer(basefilename + ".cvreq");
                cvcreq = new String(Base64.encode(der));
            }

            // Edit a user, creating it if it does not exist
            // Actually don't do that, leverage the existing commands and force to use the editUser command instead.
            // This also makes this CLI exactly represent the actual WS-API call 
            // getEjbcaRAWS().editUser(userdata);

            getPrintStream().println("Submitting CVC request for user '" + username + "'.");
            getPrintStream().println();
            // Use the request and request a certificate
            List<Certificate> resp = getEjbcaRAWS().cvcRequest(username, userpassword, cvcreq);

            // Handle the response
            Certificate cert = resp.get(0);
            byte[] b64cert = cert.getCertificateData();
            CVCObject parsedObject = CertificateParser.parseCertificate(Base64.decode(b64cert));
            CVCertificate cvcert = (CVCertificate) parsedObject;
            FileOutputStream fos = new FileOutputStream(basefilename + ".cvcert");
            fos.write(cvcert.getDEREncoded());
            fos.close();
            getPrintStream().println("Wrote binary certificate to: " + basefilename + ".cvcert");
            getPrintStream().println("You can look at the certificate with the command cvcwscli.sh cvcprint "
                    + basefilename + ".cvcert");
        } catch (AuthorizationDeniedException_Exception e) {
            getPrintStream().println("Error : " + e.getMessage());
        } catch (UserDoesntFullfillEndEntityProfile_Exception e) {
            getPrintStream()
                    .println("Error : Given userdata doesn't fullfill end entity profile. : " + e.getMessage());
        }

    } catch (Exception e) {
        if (e instanceof EjbcaException_Exception) {
            EjbcaException_Exception e1 = (EjbcaException_Exception) e;
            getPrintStream()
                    .println("Error code is: " + e1.getFaultInfo().getErrorCode().getInternalErrorCode());
        }
        throw new ErrorAdminCommandException(e);
    }
}

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:com.ibm.mqlight.api.security.KeyStoreUtils.java

/**
 * Creates a {@link PrivateKey} instance from the passed private key PEM format file and certificate chain.
 *
 * @param pemKeyFile//from  w w  w.ja  va  2 s  .  c  o m
 *            A PEM format file containing the private key.
 * @param passwordChars
 *            The password that protects the private key.
 * @return the private key, created by this method.
 * @throws IOException if the file cannot be read.
 * @throws GeneralSecurityException if a cryptography problem is encountered.
 */
public static PrivateKey createPrivateKey(File pemKeyFile, char[] passwordChars)
        throws IOException, GeneralSecurityException {
    final String methodName = "createPrivateKey";
    logger.entry(methodName, pemKeyFile);

    // Read the private key from the PEM format file
    final PemFile privateKeyPemFile = new PemFile(pemKeyFile);
    final byte[] privateKeyBytes = privateKeyPemFile.getPrivateKeyBytes();

    final PrivateKey privateKey;
    if (privateKeyPemFile.containsEncryptedPrivateKey()) {
        // We should be able to do the follows (using standard JDK classes):
        //    EncryptedPrivateKeyInfo encryptPrivateKeyInfo = new EncryptedPrivateKeyInfo(privateKeyBytes);
        //    Cipher cipher = Cipher.getInstance(encryptPrivateKeyInfo.getAlgName());
        //    PBEKeySpec pbeKeySpec = new PBEKeySpec(passwordChars);
        //    SecretKeyFactory secFac = SecretKeyFactory.getInstance(encryptPrivateKeyInfo.getAlgName());
        //    Key pbeKey = secFac.generateSecret(pbeKeySpec);
        //    AlgorithmParameters algParams = encryptPrivateKeyInfo.getAlgParameters();
        //    cipher.init(Cipher.DECRYPT_MODE, pbeKey, algParams);
        //    KeySpec keySpec = encryptPrivateKeyInfo.getKeySpec(cipher);
        //    privateKey = KeyFactory.getInstance("RSA").generatePrivate(keySpec);
        // but this can fail with a: "Unsupported key protection algorithm" if key was generated with openssl
        //
        // Instead we use the Apache commons SSL PKCS8Key class from Julius Davies (see not-yet-commons-ssl in Maven)
        // which seems more reliable
        final PKCS8Key key = new PKCS8Key(privateKeyBytes, passwordChars);
        privateKey = key.getPrivateKey();
    } else {
        final KeySpec keySpec = new PKCS8EncodedKeySpec(privateKeyBytes);
        InvalidKeySpecException keyFactoryException = null;
        PrivateKey key = null;
        for (String alg : new String[] { "RSA", "DSA", "DiffieHellman", "EC" }) {
            try {
                key = KeyFactory.getInstance(alg).generatePrivate(keySpec);
                break;
            } catch (InvalidKeySpecException e) {
                if (keyFactoryException == null)
                    keyFactoryException = e;
            }
        }
        if (key == null)
            throw keyFactoryException;
        privateKey = key;
    }

    logger.exit(methodName, privateKey);

    return privateKey;
}

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//from  ww w.j  av  a2s.co 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:mitm.common.security.keystore.hibernate.SerializableKeyEntry.java

/**
 * Creates the key from the given byte array using the stored format and type.
 * /*from  w w w .  j a  v a2  s . co m*/
 * @param keyBytes
 * @return the key
 * @throws KeyStoreException
 * @throws InvalidKeySpecException
 * @throws NoSuchAlgorithmException
 * @throws NoSuchProviderException
 */
private Key getKey(byte[] rawKey)
        throws KeyStoreException, InvalidKeySpecException, NoSuchAlgorithmException, NoSuchProviderException {
    KeySpec keySpec;

    Format keyFormat = toFormat(format);

    switch (keyFormat) {
    case PKCS8:
        keySpec = new PKCS8EncodedKeySpec(rawKey);
        break;
    case X509:
        keySpec = new X509EncodedKeySpec(rawKey);
        break;
    case RAW:
        return new SecretKeySpec(rawKey, algorithm);

    default:
        throw new KeyStoreException("Unknown key format " + keyFormat);
    }

    SecurityFactory securityFactory = getSecurityFactory();

    switch (keyType) {
    case PRIVATE:
        return securityFactory.createKeyFactory(algorithm).generatePrivate(keySpec);
    case PUBLIC:
        return securityFactory.createKeyFactory(algorithm).generatePublic(keySpec);
    case SECRET:
        return securityFactory.createSecretKeyFactory(algorithm).generateSecret(keySpec);

    default:
        throw new KeyStoreException("Unknown key type " + keyType);
    }
}

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

/**
 * ?/*ww  w  .ja  va  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;
}