Example usage for java.security.spec PKCS8EncodedKeySpec getEncoded

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

Introduction

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

Prototype

public byte[] getEncoded() 

Source Link

Document

Returns the key bytes, encoded according to the PKCS #8 standard.

Usage

From source file:net.nicholaswilliams.java.licensing.encryption.KeyFileUtilities.java

protected static byte[] writeEncryptedPrivateKey(PrivateKey privateKey, char[] passphrase) {
    PKCS8EncodedKeySpec pkcs8EncodedKeySpec = new PKCS8EncodedKeySpec(privateKey.getEncoded());
    return Encryptor.encryptRaw(pkcs8EncodedKeySpec.getEncoded(), passphrase);
}

From source file:Main.java

/**
 * save private key and public key of a keypair in the directory
 *
 * @param dir//w w  w.  jav a  2s .  c  om
 * @param keyPair
 * @param name keys will be stored as name_private.key and name_public.key
 * @throws IOException
 */
public static void saveKeyPair(File dir, KeyPair keyPair, String name) throws IOException {

    // Store Public Key.
    X509EncodedKeySpec x509EncodedKeySpec = new X509EncodedKeySpec(keyPair.getPublic().getEncoded());
    FileOutputStream fos = new FileOutputStream(new File(dir, name + "_public.key"));
    fos.write(x509EncodedKeySpec.getEncoded());
    fos.close();

    // Store Private Key.
    PKCS8EncodedKeySpec pkcs8EncodedKeySpec = new PKCS8EncodedKeySpec(keyPair.getPrivate().getEncoded());
    fos = new FileOutputStream(new File(dir, name + "_private.key"));
    fos.write(pkcs8EncodedKeySpec.getEncoded());
    fos.close();
}

From source file:com.vmware.identity.rest.idm.data.PrivateKeyDTO.java

private static String encodePrivateKey(PrivateKey key)
        throws InvalidKeySpecException, NoSuchAlgorithmException {
    if (key == null) {
        return null;
    }/*  w  w w .  java2  s .  co m*/

    KeyFactory keyFactory = KeyFactory.getInstance(key.getAlgorithm());
    PKCS8EncodedKeySpec spec = keyFactory.getKeySpec(key, PKCS8EncodedKeySpec.class);
    byte[] packed = spec.getEncoded();
    String encodePrivateKey = Base64.encodeBase64String(packed);
    Arrays.fill(packed, (byte) 0);
    return encodePrivateKey;
}

From source file:com.vexsoftware.votifier.crypto.RSAIO.java

/**
 * Saves the key pair to the disk./*w  w  w.  jav  a  2  s .  c om*/
 * 
 * @param directory
 *            The directory to save to
 * @param keyPair
 *            The key pair to save
 * @throws Exception
 *             If an error occurs
 */
public static void save(File directory, KeyPair keyPair) throws Exception {
    PrivateKey privateKey = keyPair.getPrivate();
    PublicKey publicKey = keyPair.getPublic();

    // Store the public key.
    X509EncodedKeySpec publicSpec = new X509EncodedKeySpec(publicKey.getEncoded());
    FileOutputStream out = new FileOutputStream(directory + "/public.key");
    out.write(DatatypeConverter.printBase64Binary(publicSpec.getEncoded()).getBytes());
    out.close();

    // Store the private key.
    PKCS8EncodedKeySpec privateSpec = new PKCS8EncodedKeySpec(privateKey.getEncoded());
    out = new FileOutputStream(directory + "/private.key");
    out.write(DatatypeConverter.printBase64Binary(privateSpec.getEncoded()).getBytes());
    out.close();
}

From source file:com.sixsq.slipstream.cookie.CryptoUtils.java

static private String savePrivateKey(PrivateKey privateKey) throws GeneralSecurityException {
    KeyFactory fact = KeyFactory.getInstance(keyPairAlgorithm);
    PKCS8EncodedKeySpec spec = fact.getKeySpec(privateKey, PKCS8EncodedKeySpec.class);
    byte[] encoded = spec.getEncoded();
    String privateKeyStr = new Base64().encodeToString(encoded);
    return privateKeyStr;
}

From source file:com.vexsoftware.votifier.util.rsa.RSAIO.java

/**
 * Saves the key pair to the disk.//from   w  w w .  ja v  a 2 s .  co m
 * 
 * @param directory
 *            The directory to save to
 * @param keyPair
 *            The key pair to save
 * @throws Exception
 *            If an error occurs
 */
public static void save(File directory, KeyPair keyPair) throws Exception {
    PrivateKey privateKey = keyPair.getPrivate();
    PublicKey publicKey = keyPair.getPublic();

    // Store the public key.
    X509EncodedKeySpec publicSpec = new X509EncodedKeySpec(publicKey.getEncoded());
    FileOutputStream out = null;
    try {
        out = new FileOutputStream(directory + "/public.key");
        out.write(DatatypeConverter.printBase64Binary(publicSpec.getEncoded()).getBytes());
    } finally {
        try {
            out.close();
        } catch (Exception exception) {
            // ignore
        }
    }

    // Store the private key.
    PKCS8EncodedKeySpec privateSpec = new PKCS8EncodedKeySpec(privateKey.getEncoded());
    try {
        out = new FileOutputStream(directory + "/private.key");
        out.write(DatatypeConverter.printBase64Binary(privateSpec.getEncoded()).getBytes());
    } finally {
        try {
            out.close();
        } catch (Exception exception) {
            // ignore
        }
    }
}

From source file:net.nicholaswilliams.java.licensing.licensor.TestLicenseCreator.java

@BeforeClass
public static void setUpClass() throws Exception {
    TestLicenseCreator.control = EasyMock.createStrictControl();

    TestLicenseCreator.passwordProvider = TestLicenseCreator.control.createMock(PasswordProvider.class);
    TestLicenseCreator.keyDataProvider = TestLicenseCreator.control.createMock(PrivateKeyDataProvider.class);

    try {//w ww.  java 2 s. c o m
        LicenseCreator.getInstance();
        fail("Expected java.lang.IllegalArgumentException, got no exception.");
    } catch (IllegalArgumentException ignore) {
    }

    LicenseCreatorProperties.setPrivateKeyDataProvider(TestLicenseCreator.keyDataProvider);

    try {
        LicenseCreator.getInstance();
        fail("Expected java.lang.IllegalArgumentException, got no exception.");
    } catch (IllegalArgumentException ignore) {
    }

    LicenseCreatorProperties.setPrivateKeyPasswordProvider(TestLicenseCreator.passwordProvider);

    LicenseCreator.getInstance();

    KeyPair keyPair = KeyPairGenerator.getInstance(KeyFileUtilities.keyAlgorithm).generateKeyPair();

    TestLicenseCreator.publicKey = keyPair.getPublic();

    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
    PKCS8EncodedKeySpec pkcs8EncodedKeySpec = new PKCS8EncodedKeySpec(keyPair.getPrivate().getEncoded());
    IOUtils.write(Encryptor.encryptRaw(pkcs8EncodedKeySpec.getEncoded(), keyPassword), outputStream);
    TestLicenseCreator.encryptedPrivateKey = outputStream.toByteArray();
}

From source file:com.intuit.s3encrypt.S3Encrypt.java

public static void saveKeyPair(String filename, KeyPair keyPair) throws IOException {
    PublicKey publicKey = keyPair.getPublic();
    PrivateKey privateKey = keyPair.getPrivate();

    // Save public key to file.
    X509EncodedKeySpec x509EncodedKeySpec = new X509EncodedKeySpec(publicKey.getEncoded());
    FileOutputStream keyfos = new FileOutputStream(filename + ".pub");
    keyfos.write(x509EncodedKeySpec.getEncoded());
    keyfos.close();//ww w. j a  v  a2 s.  com

    // Save private key to file.
    PKCS8EncodedKeySpec pkcs8EncodedKeySpec = new PKCS8EncodedKeySpec(privateKey.getEncoded());
    keyfos = new FileOutputStream(filename);
    keyfos.write(pkcs8EncodedKeySpec.getEncoded());
    keyfos.close();

}

From source file:net.sf.keystore_explorer.crypto.privatekey.Pkcs8Util.java

/**
 * Load an encrypted PKCS #8 private key from the specified stream. The
 * encoding of the private key may be PEM or DER.
 *
 * @param is//from  w  ww.j  ava  2s.c  om
 *            Stream load the encrypted private key from
 * @param password
 *            Password to decrypt
 * @return The private key
 * @throws PrivateKeyUnencryptedException
 *             If private key is unencrypted
 * @throws PrivateKeyPbeNotSupportedException
 *             If private key PBE algorithm is not supported
 * @throws CryptoException
 *             Problem encountered while loading the private key
 * @throws IOException
 *             If an I/O error occurred
 */
public static PrivateKey loadEncrypted(InputStream is, Password password) throws CryptoException, IOException {
    byte[] streamContents = ReadUtil.readFully(is);

    // Check pkcs #8 is not unencrypted
    EncryptionType encType = getEncryptionType(new ByteArrayInputStream(streamContents));

    if (encType == null) {
        // Not a valid PKCS #8 private key
        throw new CryptoException(res.getString("NotValidPkcs8.exception.message"));
    }

    if (encType == UNENCRYPTED) {
        throw new PrivateKeyUnencryptedException(res.getString("Pkcs8IsUnencrypted.exception.message"));
    }

    byte[] encPvk = null;
    // Check if stream is PEM encoded
    PemInfo pemInfo = PemUtil.decode(new ByteArrayInputStream(streamContents));

    if (pemInfo != null) {
        // It is - get DER from PEM
        encPvk = pemInfo.getContent();
    }

    /*
     * If we haven't got the encrypted bytes via PEM then just use
     * stream contents directly (assume it is DER encoded)
     */
    if (encPvk == null) {
        // Read in encrypted private key bytes
        encPvk = streamContents;
    }

    try {
        // Create encrypted private key information from bytes
        EncryptedPrivateKeyInfo epki = new EncryptedPrivateKeyInfo(encPvk);

        // Get wrapping algorithm
        String encAlg = epki.getAlgName();

        // Check algorithm is supported
        if (!checkSupportedForDecrypt(encAlg)) {
            throw new PrivateKeyPbeNotSupportedException(encAlg, MessageFormat
                    .format(res.getString("PrivateKeyWrappingAlgUnsupported.exception.message"), encAlg));
        }

        // Create algorithm parameters and decryption key
        AlgorithmParameters encAlgParams = epki.getAlgParameters();
        PBEKeySpec pbeKeySpec = new PBEKeySpec(password.toCharArray());
        SecretKeyFactory keyFact = SecretKeyFactory.getInstance(encAlg);
        SecretKey pbeKey = keyFact.generateSecret(pbeKeySpec);

        // Create cipher to create
        Cipher cipher = Cipher.getInstance(encAlg);

        // Do decryption
        cipher.init(Cipher.DECRYPT_MODE, pbeKey, encAlgParams);
        PKCS8EncodedKeySpec privateKeySpec = epki.getKeySpec(cipher);

        // Get encoding of private key
        byte[] pvkBytes = privateKeySpec.getEncoded();

        // Determine private key algorithm from key bytes
        String privateKeyAlgorithm = getPrivateKeyAlgorithm(pvkBytes);

        // Use Key Factory to create private key from encoding
        KeyFactory keyFactory = KeyFactory.getInstance(privateKeyAlgorithm);
        PrivateKey pvk = keyFactory.generatePrivate(privateKeySpec);

        return pvk;
    } catch (GeneralSecurityException ex) {
        throw new CryptoException(res.getString("NoLoadPkcs8PrivateKey.exception.message"), ex);
    }
}

From source file:net.arccotangent.pacchat.filesystem.KeyManager.java

private static void saveKeys(PrivateKey privkey, PublicKey pubkey) {
    km_log.i("Saving keys to disk.");

    X509EncodedKeySpec pubSpec = new X509EncodedKeySpec(pubkey.getEncoded());
    PKCS8EncodedKeySpec privSpec = new PKCS8EncodedKeySpec(privkey.getEncoded());

    try {/*  ww  w  . ja va 2  s  . c  o  m*/
        km_log.i(pubkeyFile.createNewFile() ? "Creation of public key file successful."
                : "Creation of public key file failed!");

        FileOutputStream pubOut = new FileOutputStream(pubkeyFile);
        pubOut.write(Base64.encodeBase64(pubSpec.getEncoded()));
        pubOut.flush();
        pubOut.close();

    } catch (IOException e) {
        km_log.e("Error while saving public key!");
        e.printStackTrace();
    }

    try {
        km_log.i(privkeyFile.createNewFile() ? "Creation of private key file successful."
                : "Creation of private key file failed!");

        FileOutputStream privOut = new FileOutputStream(privkeyFile);
        privOut.write(Base64.encodeBase64(privSpec.getEncoded()));
        privOut.flush();
        privOut.close();

    } catch (IOException e) {
        km_log.e("Error while saving private key!");
        e.printStackTrace();
    }

    km_log.i("Finished saving keys to disk. Operation appears successful.");
}