Example usage for java.security PrivateKey getAlgorithm

List of usage examples for java.security PrivateKey getAlgorithm

Introduction

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

Prototype

public String getAlgorithm();

Source Link

Document

Returns the standard algorithm name for this key.

Usage

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

/**
 * Construct a {@code PrivateKeyDTO} from a {@link PrivateKey}.
 *
 * @param privateKey the private key to build the DTO from.
 * @throws InvalidKeySpecException if the requested key specification is inappropriate for the
 *  given key, or the given key cannot be processed (e.g., the given key has an unrecognized
 *  algorithm or format).//www .j  a v a 2s . co m
 * @throws NoSuchAlgorithmException if no Provider supports a KeyFactorySpi implementation for
 *  the specified algorithm.
 */
public PrivateKeyDTO(PrivateKey privateKey) throws InvalidKeySpecException, NoSuchAlgorithmException {
    this.privateKey = privateKey;
    this.algorithm = privateKey == null ? null : privateKey.getAlgorithm();

    this.encoded = encodePrivateKey(privateKey);
}

From source file:net.sf.keystore_explorer.gui.actions.GenerateCsrAction.java

/**
 * Do action./*from  ww w  .j  a va 2 s  . c o  m*/
 */
@Override
protected void doAction() {
    File csrFile = null;
    FileOutputStream fos = null;

    try {
        KeyStoreHistory history = kseFrame.getActiveKeyStoreHistory();
        KeyStoreState currentState = history.getCurrentState();
        Provider provider = history.getExplicitProvider();

        String alias = kseFrame.getSelectedEntryAlias();

        Password password = getEntryPassword(alias, currentState);

        if (password == null) {
            return;
        }

        KeyStore keyStore = currentState.getKeyStore();

        PrivateKey privateKey = (PrivateKey) keyStore.getKey(alias, password.toCharArray());

        String keyPairAlg = privateKey.getAlgorithm();
        KeyPairType keyPairType = KeyPairUtil.getKeyPairType(privateKey);

        if (keyPairType == null) {
            throw new CryptoException(MessageFormat
                    .format(res.getString("GenerateCsrAction.NoCsrForKeyPairAlg.message"), keyPairAlg));
        }

        // determine dir of current keystore as proposal for CSR file location
        String path = CurrentDirectory.get().getAbsolutePath();
        File keyStoreFile = history.getFile();
        if (keyStoreFile != null) {
            path = keyStoreFile.getAbsoluteFile().getParent();
        }

        DGenerateCsr dGenerateCsr = new DGenerateCsr(frame, alias, privateKey, keyPairType, path, provider);
        dGenerateCsr.setLocationRelativeTo(frame);
        dGenerateCsr.setVisible(true);

        if (!dGenerateCsr.generateSelected()) {
            return;
        }

        CsrType format = dGenerateCsr.getFormat();
        SignatureType signatureType = dGenerateCsr.getSignatureType();
        String challenge = dGenerateCsr.getChallenge();
        String unstructuredName = dGenerateCsr.getUnstructuredName();
        boolean useCertificateExtensions = dGenerateCsr.isAddExtensionsWanted();
        csrFile = dGenerateCsr.getCsrFile();

        X509Certificate firstCertInChain = X509CertUtil
                .orderX509CertChain(X509CertUtil.convertCertificates(keyStore.getCertificateChain(alias)))[0];

        fos = new FileOutputStream(csrFile);

        if (format == CsrType.PKCS10) {
            String csr = Pkcs10Util.getCsrEncodedDerPem(Pkcs10Util.generateCsr(firstCertInChain, privateKey,
                    signatureType, challenge, unstructuredName, useCertificateExtensions, provider));

            fos.write(csr.getBytes());
        } else {
            SpkacSubject subject = new SpkacSubject(
                    X500NameUtils.x500PrincipalToX500Name(firstCertInChain.getSubjectX500Principal()));
            PublicKey publicKey = firstCertInChain.getPublicKey();

            // TODO handle other providers (PKCS11 etc)
            Spkac spkac = new Spkac(challenge, signatureType, subject, publicKey, privateKey);

            spkac.output(fos);
        }
    } catch (FileNotFoundException ex) {
        JOptionPane.showMessageDialog(frame,
                MessageFormat.format(res.getString("GenerateCsrAction.NoWriteFile.message"), csrFile),
                res.getString("GenerateCsrAction.GenerateCsr.Title"), JOptionPane.WARNING_MESSAGE);
        return;
    } catch (Exception ex) {
        DError.displayError(frame, ex);
        return;
    } finally {
        IOUtils.closeQuietly(fos);
    }

    JOptionPane.showMessageDialog(frame, res.getString("GenerateCsrAction.CsrGenerationSuccessful.message"),
            res.getString("GenerateCsrAction.GenerateCsr.Title"), JOptionPane.INFORMATION_MESSAGE);
}

From source file:edu.vt.middleware.crypt.util.CryptReaderWriterTest.java

/**
 * @param  key  Key to write and read./*from w w w  . ja v  a  2 s  . co m*/
 * @param  password  Key encryption password.
 *
 * @throws  Exception  On test failure.
 */
@Test(groups = { "functest", "util" }, dataProvider = "privkeydata")
public void testReadWriteDerPrivateKey(final PrivateKey key, final String password) throws Exception {
    logger.info("Testing " + key.getAlgorithm() + " private key.");

    final File keyFile = new File(getKeyPath(key, "DER", null));
    keyFile.getParentFile().mkdir();
    CryptWriter.writeEncodedKey(key, keyFile);
    AssertJUnit.assertEquals(key, CryptReader.readPrivateKey(keyFile));
}

From source file:edu.vt.middleware.crypt.util.CryptReaderWriterTest.java

/**
 * @param  key  Key to write and read.// w  ww .  jav  a  2s.c  o  m
 * @param  password  Key encryption password.
 *
 * @throws  Exception  On test failure.
 */
@Test(groups = { "functest", "util" }, dataProvider = "privkeydata")
public void testReadWritePemPrivateKey(final PrivateKey key, final String password) throws Exception {
    logger.info("Testing " + key.getAlgorithm() + " private key.");

    final char[] pwchars;
    if (password != null) {
        pwchars = password.toCharArray();
    } else {
        pwchars = null;
    }

    final File keyFile = new File(getKeyPath(key, "PEM", pwchars));
    keyFile.getParentFile().mkdir();
    CryptWriter.writePemKey(key, pwchars, new SecureRandom(), keyFile);

    final PrivateKey keyFromFile;
    if (pwchars != null) {
        keyFromFile = CryptReader.readPrivateKey(keyFile, pwchars);
    } else {
        keyFromFile = CryptReader.readPrivateKey(keyFile);
    }
    AssertJUnit.assertEquals(key, keyFromFile);
}

From source file:org.tolven.connectors.passwordstore.PasswordStoreImpl.java

/**
 * Returns a password.//from  ww  w. jav  a  2 s  .  com
 */
public char[] getPassword(String alias) {
    char[] password = getPasswordStore().get(alias);
    if (password == null) {
        String encryptedPassword = getEncryptedPassword(alias);
        if (encryptedPassword == null) {
            return null;
        }
        try {
            String keyStoreAlias = getKeyStore().aliases().nextElement();
            PrivateKey privateKey = (PrivateKey) getKeyStore().getKey(keyStoreAlias, getKeyStorePassword());
            Cipher cipher = Cipher.getInstance(privateKey.getAlgorithm());
            cipher.init(Cipher.DECRYPT_MODE, privateKey);
            byte[] encryptedBytes = Base64.decodeBase64(encryptedPassword.getBytes(Charset.forName("UTF-8")));
            byte[] unencryptedBytes = cipher.doFinal(encryptedBytes);
            password = toCharArray(unencryptedBytes);
            getPasswordStore().put(alias, password);
        } catch (Exception ex) {
            throw new RuntimeException("Could not get password for alias: " + alias, ex);
        }
    }
    return password;
}

From source file:org.riksa.a3.fragment.ImportKeyPairFragment.java

private boolean validatePrivateKey(String keyString) throws ViewNotFoundException {
    ImageView imageView = A3Utils.findView(getActivity(), ImageView.class, R.id.pk_icon_private_key_valid);
    TextView textView = A3Utils.findView(getActivity(), TextView.class, R.id.pk_text_private_key_valid);
    textView.setText(R.string.pk_text_private_key_invalid);
    imageView.setImageResource(R.drawable.btn_check_buttonless_off);
    if (keyString == null || keyString.length() == 0) {
        return false;
    }/*ww w.  j  a  v a 2 s .co m*/

    log.debug("privateKey={}", keyString);

    PrivateKey privateKey = PrivateKeyFactory.createPrivateKey(keyString.getBytes());
    if (privateKey == null) {
        return false;
    }

    String algorithm = privateKey.getAlgorithm();
    int bits = PrivateKeyFactory.getBits(privateKey);
    textView.setText(getString(R.string.pk_text_private_key_valid, algorithm, bits));
    imageView.setImageResource(R.drawable.btn_check_buttonless_on);
    return true;

}

From source file:vellum.cryptostore.RsaStoreTest.java

public void testGenerate(int iterationCount) throws Exception {
    long millis = System.currentTimeMillis();
    RsaKeyStore ks = new RsaKeyStore();
    ks.generate(alias, keySize);//from   w w w .jav a 2s.  c  o m
    ByteArrayOutputStream kos = new ByteArrayOutputStream();
    ks.storePublic(kos);
    ByteArrayInputStream kis = new ByteArrayInputStream(kos.toByteArray());
    PublicKey loadedPublicKey = ks.loadPublic(kis);
    System.out.printf("loaded public key %s %s: %s\n", alias, loadedPublicKey.getAlgorithm(),
            Base64.encodeBase64String(loadedPublicKey.getEncoded()));
    assertTrue("loaded public key",
            Arrays.equals(ks.getKeyPair().getPublic().getEncoded(), loadedPublicKey.getEncoded()));
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    new RsaStore().store(baos, type, alias, text.getBytes(), ks.getKeyPair().getPublic());
    millis = Millis.elapsed(millis);
    System.out.printf("store %s %d %dms: %s\n", alias, iterationCount, millis, text);
    millis = System.currentTimeMillis();
    ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());
    kos = new ByteArrayOutputStream();
    ks.storePrivate(kos, password);
    kis = new ByteArrayInputStream(kos.toByteArray());
    PrivateKey loadedPrivateKey = ks.loadPrivate(kis, alias, password);
    assertTrue("loaded private key",
            Arrays.equals(ks.getKeyPair().getPrivate().getEncoded(), loadedPrivateKey.getEncoded()));
    millis = Millis.elapsed(millis);
    System.out.printf("loaded private key %s %d %dms: %s\n", alias, iterationCount, millis,
            loadedPrivateKey.getAlgorithm());
    millis = System.currentTimeMillis();
    byte[] loadBytes = new RsaStore().load(bais, type, alias, loadedPrivateKey);
    millis = Millis.elapsed(millis);
    System.out.printf("load %s %d %dms: %s\n", alias, iterationCount, millis, new String(loadBytes));
    assertTrue("loaded bytes", Arrays.equals(loadBytes, text.getBytes()));
}

From source file:cl.nic.dte.util.XMLUtil.java

public static AUTORIZACIONDocument generateAuthorization(AUTORIZACIONDocument template, PrivateKey pKey)
        throws NoSuchAlgorithmException, SignatureException, TransformerException, InvalidKeyException,
        IOException {/*from   www .  j  a va 2 s.c o  m*/
    // Generation of keys

    KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA");
    kpg.initialize(1024);
    KeyPair kp = kpg.generateKeyPair();

    CAFType caf = template.getAUTORIZACION().getCAF();
    CAFType.DA.RSAPK rsapk = caf.getDA().addNewRSAPK();

    rsapk.setM(((RSAPublicKey) kp.getPublic()).getModulus().toByteArray());
    rsapk.setE(((RSAPublicKey) kp.getPublic()).getPublicExponent().toByteArray());

    ResourceBundle labels = ResourceBundle.getBundle("cl.nic.dte.resources.VerifyResults");

    Signature sig = null;
    if (pKey.getAlgorithm().equals("RSA")) {
        sig = Signature.getInstance("SHA1withRSA");
        caf.addNewFRMA().setAlgoritmo("SHA1withRSA");
    } else if (pKey.getAlgorithm().equals("DSA")) {
        sig = Signature.getInstance("SHA1withDSA");
        caf.addNewFRMA().setAlgoritmo("SHA1withDSA");
    } else {
        throw new NoSuchAlgorithmException(
                labels.getString("ALGORITHM_NOT_SUPPORTED").replaceAll("%1", pKey.getAlgorithm()));
    }

    template.getAUTORIZACION()
            .setRSASK("-----BEGIN RSA PRIVATE KEY-----\n"
                    + new String(Base64.encodeBase64(kp.getPrivate().getEncoded(), true))
                    + "-----END RSA PRIVATE KEY-----\n");

    template.getAUTORIZACION()
            .setRSAPUBK("-----BEGIN RSA PUBLIC KEY-----\n"
                    + new String(Base64.encodeBase64(kp.getPublic().getEncoded(), true))
                    + "-----END RSA PUBLIC KEY-----\n");

    sig.initSign(pKey);
    sig.update(XMLUtil.getCleaned(caf.getDA()));

    caf.getFRMA().setByteArrayValue(Base64.encodeBase64(sig.sign()));
    return template;
}

From source file:jp.primecloud.auto.service.impl.IaasDescribeServiceImpl.java

protected String decryptPasswordData(String passwordData, PrivateKey privateKey) {
    // ??// w  w w .jav  a2 s  . c  o m
    try {
        Cipher cipher = Cipher.getInstance(privateKey.getAlgorithm());
        cipher.init(Cipher.DECRYPT_MODE, privateKey);
        byte[] binary = cipher.doFinal(Base64.decodeBase64(passwordData.getBytes()));
        return new String(binary);
    } catch (GeneralSecurityException e) {
        // ?????????
        throw new AutoApplicationException("ESERVICE-000706", e);
    }
}

From source file:org.apache.cloudstack.network.lb.CertServiceImpl.java

private void validateKeys(PublicKey pubKey, PrivateKey privKey) {

    if (pubKey.getAlgorithm() != privKey.getAlgorithm())
        throw new IllegalArgumentException("Public and private key have different algorithms");

    // No encryption for DSA
    if (pubKey.getAlgorithm() != "RSA")
        return;/*w  ww .j  a  v a2s  . co m*/

    try {

        String data = "ENCRYPT_DATA";
        SecureRandom random = new SecureRandom();
        Cipher cipher = Cipher.getInstance(pubKey.getAlgorithm());
        cipher.init(Cipher.ENCRYPT_MODE, privKey, random);
        byte[] encryptedData = cipher.doFinal(data.getBytes());

        cipher.init(Cipher.DECRYPT_MODE, pubKey, random);
        String decreptedData = new String(cipher.doFinal(encryptedData));
        if (!decreptedData.equals(data))
            throw new IllegalArgumentException("Bad public-private key");

    } catch (BadPaddingException e) {
        throw new IllegalArgumentException("Bad public-private key", e);
    } catch (IllegalBlockSizeException e) {
        throw new IllegalArgumentException("Bad public-private key", e);
    } catch (NoSuchPaddingException e) {
        throw new IllegalArgumentException("Bad public-private key", e);
    } catch (InvalidKeyException e) {
        throw new IllegalArgumentException("Invalid public-private key", e);
    } catch (NoSuchAlgorithmException e) {
        throw new IllegalArgumentException("Invalid algorithm for public-private key", e);
    }
}