Example usage for java.security KeyStore getKey

List of usage examples for java.security KeyStore getKey

Introduction

In this page you can find the example usage for java.security KeyStore getKey.

Prototype

public final Key getKey(String alias, char[] password)
        throws KeyStoreException, NoSuchAlgorithmException, UnrecoverableKeyException 

Source Link

Document

Returns the key associated with the given alias, using the given password to recover it.

Usage

From source file:com.tremolosecurity.openunison.util.OpenUnisonUtils.java

private static void printSecreyKey(Options options, CommandLine cmd, TremoloType tt, KeyStore ks)
        throws KeyStoreException, NoSuchAlgorithmException, UnrecoverableKeyException {
    String alias = loadOption(cmd, "alias", options);
    SecretKey key = (SecretKey) ks.getKey(alias, tt.getKeyStorePassword().toCharArray());
    String val = Base64.encode(key.getEncoded());
    logger.info(val);
}

From source file:com.netscape.cmstools.pkcs11.PKCS11KeyRemoveCLI.java

public void execute(String[] args) throws Exception {

    CommandLine cmd = parser.parse(options, args);

    if (cmd.hasOption("help")) {
        printHelp();//w  w w.j a  v  a 2 s .  c  o m
        return;
    }

    if (cmd.hasOption("verbose")) {
        PKILogger.setLevel(PKILogger.Level.INFO);

    } else if (cmd.hasOption("debug")) {
        PKILogger.setLevel(PKILogger.Level.DEBUG);
    }

    String[] cmdArgs = cmd.getArgs();

    if (cmdArgs.length < 1) {
        throw new Exception("Missing key ID.");
    }

    String alias = cmdArgs[0];

    String tokenName = getConfig().getTokenName();
    CryptoToken token = CryptoUtil.getKeyStorageToken(tokenName);

    KeyStore ks = KeyStore.getInstance("pkcs11");
    ks.load(new JSSLoadStoreParameter(token));

    Key key = ks.getKey(alias, null);

    if (key == null) {
        throw new Exception("Key not found: " + alias);
    }

    ks.deleteEntry(alias);
}

From source file:com.netscape.cmstools.pkcs11.PKCS11KeyShowCLI.java

public void execute(String[] args) throws Exception {

    CommandLine cmd = parser.parse(options, args);

    if (cmd.hasOption("help")) {
        printHelp();//  w  w  w.j  ava2  s .  c o m
        return;
    }

    if (cmd.hasOption("verbose")) {
        PKILogger.setLevel(PKILogger.Level.INFO);

    } else if (cmd.hasOption("debug")) {
        PKILogger.setLevel(PKILogger.Level.DEBUG);
    }

    String[] cmdArgs = cmd.getArgs();

    if (cmdArgs.length < 1) {
        throw new Exception("Missing key ID.");
    }

    String alias = cmdArgs[0];

    String tokenName = getConfig().getTokenName();
    CryptoToken token = CryptoUtil.getKeyStorageToken(tokenName);

    KeyStore ks = KeyStore.getInstance("pkcs11");
    ks.load(new JSSLoadStoreParameter(token));

    Key key = ks.getKey(alias, null);

    if (key == null) {
        throw new Exception("Key not found: " + alias);
    }

    PKCS11KeyCLI.printKeyInfo(alias, key);
}

From source file:org.alfresco.extension.countersign.action.executer.ContentSignatureActionExecuter.java

@Override
protected void executeImpl(Action ruleAction, NodeRef actionedUponNodeRef) {
    NodeService nodeService = serviceRegistry.getNodeService();
    ContentService contentService = serviceRegistry.getContentService();
    byte[] sigBytes;

    if (nodeService.exists(actionedUponNodeRef) == false) {
        return;/*  ww  w. ja  v  a2 s .c om*/
    }

    String location = (String) ruleAction.getParameterValue(PARAM_LOCATION);
    String geolocation = (String) ruleAction.getParameterValue(PARAM_GEOLOCATION);
    String reason = (String) ruleAction.getParameterValue(PARAM_REASON);
    String keyPassword = (String) ruleAction.getParameterValue(PARAM_KEY_PASSWORD);

    // get a hash of the document
    InputStream contentStream = contentService.getReader(actionedUponNodeRef, ContentModel.PROP_CONTENT)
            .getContentInputStream();

    try {
        // get the user's private key
        String user = AuthenticationUtil.getRunAsUser();
        SignatureProvider signatureProvider = signatureProviderFactory.getSignatureProvider(user);
        KeyStore keystore = signatureProvider.getUserKeyStore(keyPassword);
        PrivateKey key = (PrivateKey) keystore.getKey(alias, keyPassword.toCharArray());

        // compute the document hash
        byte[] hash = signatureProvider.computeHash(contentStream);

        // sign the hash
        sigBytes = signatureProvider.signHash(hash, keyPassword);

        // create a "signature" node and associate it with the signed doc
        NodeRef sig = addSignatureNodeAssociation(actionedUponNodeRef, location, reason, "none",
                new java.util.Date(), geolocation, -1, "none");

        // save the signature
        ContentWriter writer = contentService.getWriter(sig, ContentModel.PROP_CONTENT, true);
        writer.putContent(new ByteArrayInputStream(sigBytes));

        // also save the expected hash in the signature
        nodeService.setProperty(sig, CounterSignSignatureModel.PROP_DOCHASH, new String(hash));
    } catch (UnrecoverableKeyException uke) {
        throw new AlfrescoRuntimeException(uke.getMessage());
    } catch (KeyStoreException kse) {
        throw new AlfrescoRuntimeException(kse.getMessage());
    } catch (NoSuchAlgorithmException nsae) {
        throw new AlfrescoRuntimeException(nsae.getMessage());
    } catch (Exception e) {
        throw new AlfrescoRuntimeException(e.getMessage());
    }
}

From source file:test.integ.be.e_contract.mycarenet.async.AsyncClientTest.java

@Test
public void testEcho() throws Exception {
    // setup/* ww w  .j a  va  2  s.co  m*/
    String xkms2Location = "https://pilot.mycarenet.be/mycarenet-ws/care-provider/xkms2";
    XKMS2Client xkms2Client = new XKMS2Client(xkms2Location);
    SessionKey sessionKey = new SessionKey();

    Security.addProvider(new BeIDProvider());
    KeyStore keyStore = KeyStore.getInstance("BeID");
    keyStore.load(null);
    PrivateKey authnPrivateKey = (PrivateKey) keyStore.getKey("Authentication", null);
    X509Certificate authnCertificate = (X509Certificate) keyStore.getCertificate("Authentication");

    // operate
    xkms2Client.registerSessionKey(sessionKey, authnPrivateKey, authnCertificate);

    // verify
    assertTrue(sessionKey.isValid());

    try {
        // setup
        Config config = new Config();
        PackageLicenseKey packageLicenseKey = config.getPackageLicenseKey();
        LOG.debug("package license key username: " + packageLicenseKey.getUsername());
        LOG.debug("package license key password: " + packageLicenseKey.getPassword());
        AsyncClient asyncClient = new AsyncClient("https://pilot.mycarenet.be/mycarenet-ws/care-provider/async",
                sessionKey, packageLicenseKey);
        String message = "hello world";

        // operate
        String result;
        try {
            result = asyncClient.echo(message);
        } finally {
            LOG.debug("payload: " + asyncClient.getPayload());
        }

        // verify
        assertEquals(result, message);
    } finally {
        // operate
        xkms2Client.revokeSessionKey(sessionKey, authnPrivateKey, authnCertificate);

        // verify
        assertFalse(sessionKey.isValid());
    }
}

From source file:test.integ.be.e_contract.mycarenet.sts.RequestFactoryTest.java

@Test
public void testCreateRequest() throws Exception {
    Security.addProvider(new BeIDProvider());
    KeyStore keyStore = KeyStore.getInstance("BeID");
    keyStore.load(null);// w w  w.j av  a  2 s.  com
    PrivateKey authnPrivateKey = (PrivateKey) keyStore.getKey("Authentication", null);
    X509Certificate authnCertificate = (X509Certificate) keyStore.getCertificate("Authentication");

    KeyStore eHealthKeyStore = KeyStore.getInstance("PKCS12");
    FileInputStream fileInputStream = new FileInputStream(this.config.getEHealthPKCS12Path());
    eHealthKeyStore.load(fileInputStream, this.config.getEHealthPKCS12Password().toCharArray());
    Enumeration<String> aliasesEnum = eHealthKeyStore.aliases();
    String alias = aliasesEnum.nextElement();
    X509Certificate eHealthCertificate = (X509Certificate) eHealthKeyStore.getCertificate(alias);
    PrivateKey eHealthPrivateKey = (PrivateKey) eHealthKeyStore.getKey(alias,
            this.config.getEHealthPKCS12Password().toCharArray());

    RequestFactory requestFactory = new RequestFactory();

    List<Attribute> attributes = new LinkedList<Attribute>();
    attributes.add(new Attribute("urn:be:fgov:identification-namespace",
            "urn:be:fgov:ehealth:1.0:certificateholder:person:ssin"));
    attributes.add(new Attribute("urn:be:fgov:identification-namespace", "urn:be:fgov:person:ssin"));

    List<AttributeDesignator> attributeDesignators = new LinkedList<AttributeDesignator>();
    attributeDesignators.add(new AttributeDesignator("urn:be:fgov:identification-namespace",
            "urn:be:fgov:ehealth:1.0:certificateholder:person:ssin"));
    attributeDesignators
            .add(new AttributeDesignator("urn:be:fgov:identification-namespace", "urn:be:fgov:person:ssin"));
    attributeDesignators.add(new AttributeDesignator("urn:be:fgov:certified-namespace:ehealth",
            "urn:be:fgov:person:ssin:nurse:boolean"));

    Element requestElement = requestFactory.createRequest(authnCertificate, eHealthPrivateKey,
            eHealthCertificate, attributes, attributeDesignators);

    assertNotNull(requestElement);

    LOG.debug("request: " + toString(requestElement));
}

From source file:energy.usef.environment.tool.security.KeystoreService.java

public byte[] loadSecretKey() {
    char[] ksPassword = toCharArray(keystorePassword);
    char[] ksKeyPassword = toCharArray(keystorePKPassword);

    Key key = null;//from  ww  w  .  j a  v  a 2  s  .  c  o  m
    try (InputStream is = new FileInputStream(keystoreFilename)) {
        KeyStore ks = KeyStore.getInstance(JCEKS);
        ks.load(is, ksPassword);
        key = ks.getKey(keystorePKAlias, ksKeyPassword);
    } catch (IOException | NoSuchAlgorithmException | CertificateException | KeyStoreException
            | UnrecoverableKeyException e) {
        LOGGER.error("Exception occured during the loading of the secret key. {}", e);
        throw new RuntimeException(e);
    }
    if (key == null) {
        return new byte[0];
    }
    LOGGER.info("Algorithm: " + key.getAlgorithm());
    LOGGER.info("Format: " + key.getFormat());
    return key.getEncoded();
}

From source file:org.wso2.carbon.core.util.CryptoUtil.java

/**
 * Decrypt the given cipher text value using the WSO2 WSAS key
 *
 * @param cipherTextBytes The cipher text to be decrypted
 * @return Decrypted bytes/*from  w  ww  .ja va 2 s  . c o  m*/
 * @throws CryptoException On an error during decryption
 */
public byte[] decrypt(byte[] cipherTextBytes) throws CryptoException {
    try {

        KeyStoreManager keyMan = KeyStoreManager.getInstance(MultitenantConstants.SUPER_TENANT_ID,
                this.getServerConfigService(), this.getRegistryService());
        KeyStore keyStore = keyMan.getPrimaryKeyStore();
        PrivateKey privateKey = (PrivateKey) keyStore.getKey(keyAlias, keyPass.toCharArray());

        Cipher cipher = Cipher.getInstance("RSA", "BC");
        cipher.init(Cipher.DECRYPT_MODE, privateKey);

        return cipher.doFinal(cipherTextBytes);

    } catch (Exception e) {
        e.printStackTrace();
        throw new CryptoException("errorDuringDecryption", e);
    }
}

From source file:org.wso2.carbon.mss.security.JWTSecurityInterceptor.java

private PublicKey getPublicKey(String keyStorePath, String keyStorePassword, String alias) throws IOException,
        KeyStoreException, CertificateException, NoSuchAlgorithmException, UnrecoverableKeyException {

    try (InputStream inputStream = getClass().getClassLoader().getResourceAsStream(keyStorePath)) {
        KeyStore keystore = KeyStore.getInstance(KeyStore.getDefaultType());
        keystore.load(inputStream, keyStorePassword.toCharArray());

        Key key = keystore.getKey(alias, keyStorePassword.toCharArray());
        if (key instanceof PrivateKey) {
            // Get certificate of public key
            java.security.cert.Certificate cert = keystore.getCertificate(alias);

            // Get public key
            return cert.getPublicKey();
        }/*ww w  .jav a 2s.  c o  m*/
    }
    return null;
}

From source file:org.kse.gui.actions.ExportKeyPairAction.java

/**
 * Do action./*from ww  w  .  j  a v  a2  s.co m*/
 */
@Override
protected void doAction() {
    File exportFile = null;

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

        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());
        Certificate[] certificates = keyStore.getCertificateChain(alias);

        DExportKeyPair dExportKeyPair = new DExportKeyPair(frame, alias,
                applicationSettings.getPasswordQualityConfig());
        dExportKeyPair.setLocationRelativeTo(frame);
        dExportKeyPair.setVisible(true);

        if (!dExportKeyPair.isExportSelected()) {
            return;
        }

        exportFile = dExportKeyPair.getExportFile();
        Password exportPassword = dExportKeyPair.getExportPassword();
        ExportFormat exportFormat = dExportKeyPair.getExportFormat();

        if (exportFormat == ExportFormat.PKCS12) {
            exportAsPkcs12(exportFile, alias, privateKey, certificates, exportPassword);
        } else {
            exportAsPem(exportFile, privateKey, certificates, exportPassword);
        }

        JOptionPane.showMessageDialog(frame,
                res.getString("ExportKeyPairAction.ExportKeyPairSuccessful.message"),
                res.getString("ExportKeyPairAction.ExportKeyPair.Title"), JOptionPane.INFORMATION_MESSAGE);
    } catch (FileNotFoundException ex) {
        String message = MessageFormat.format(res.getString("ExportKeyPairAction.NoWriteFile.message"),
                exportFile);
        JOptionPane.showMessageDialog(frame, message, res.getString("ExportKeyPairAction.ExportKeyPair.Title"),
                JOptionPane.WARNING_MESSAGE);
    } catch (Exception ex) {
        DError.displayError(frame, ex);
    }
}