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.zacwolf.commons.crypto.Crypter_Blowfish.java

/**
 * @param keyStore/*from  www  .  ja  va2  s  . co  m*/
 * @param keystorepass
 * @param alias
 * @param cipher
 * @throws UnrecoverableKeyException
 * @throws NoSuchAlgorithmException
 * @throws KeyStoreException
 */
public Crypter_Blowfish(final KeyStore keyStore, final char[] keystorepass, final String alias,
        final String cipher) throws UnrecoverableKeyException, NoSuchAlgorithmException, KeyStoreException {
    this(keyStore.getKey(alias, keystorepass).getEncoded(), cipher);
}

From source file:mitm.BouncyCastleSslEngineSource.java

private void initializeSSLContext() throws GeneralSecurityException, IOException {
    KeyStore ks = loadKeyStore();
    caCert = ks.getCertificate(authority.alias());
    caPrivKey = (PrivateKey) ks.getKey(authority.alias(), authority.password());

    TrustManager[] trustManagers = null;
    if (trustAllServers) {
        trustManagers = InsecureTrustManagerFactory.INSTANCE.getTrustManagers();
    } else {//w  w w.j  a  v  a 2  s  .c om
        trustManagers = new TrustManager[] { new MergeTrustManager(ks) };
    }

    KeyManager[] keyManagers = null;
    if (sendCerts) {
        keyManagers = CertificateHelper.getKeyManagers(ks, authority);
    } else {
        keyManagers = new KeyManager[0];
    }

    sslContext = CertificateHelper.newClientContext(keyManagers, trustManagers);
    SSLEngine sslEngine = sslContext.createSSLEngine();
    if (!tryHostNameVerificationJava7(sslEngine) && !tryHostNameVerificationJava6(sslEngine)) {
        LOG.warn(
                "Host Name Verification is not supported, causes insecure HTTPS connection to upstream servers.");
    }
}

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

/**
 * @see org.alfresco.repo.action.executer.ActionExecuterAbstractBase#executeImpl(org.alfresco.service.cmr.repository.NodeRef,
 * org.alfresco.service.cmr.repository.NodeRef)
 *//*w  w w  . j  a  v  a2  s .  co m*/
protected void executeImpl(Action ruleAction, NodeRef actionedUponNodeRef) {

    if (serviceRegistry.getNodeService().exists(actionedUponNodeRef) == false) {
        // node doesn't exist - can't do anything
        return;
    }

    String location = (String) ruleAction.getParameterValue(PARAM_LOCATION);
    String geolocation = (String) ruleAction.getParameterValue(PARAM_GEOLOCATION);
    String reason = (String) ruleAction.getParameterValue(PARAM_REASON);
    String position = (String) ruleAction.getParameterValue(PARAM_POSITION);
    String keyPassword = (String) ruleAction.getParameterValue(PARAM_KEY_PASSWORD);
    String signatureJson = (String) ruleAction.getParameterValue(PARAM_SIGNATURE_JSON);
    Boolean visible = (Boolean) ruleAction.getParameterValue(PARAM_VISIBLE);
    Boolean graphic = (Boolean) ruleAction.getParameterValue(PARAM_GRAPHIC);

    boolean useSignatureField = false;
    String user = AuthenticationUtil.getRunAsUser();
    String positionType = "predefined";
    String positionLoc = "center";
    JSONObject box;
    int page = -1;

    // parse out the position JSON
    JSONObject positionObj = null;

    try {
        positionObj = (JSONObject) parser.parse(position);
    } catch (ParseException e) {
        logger.error("Could not parse position JSON from Share");
        throw new AlfrescoRuntimeException("Could not parse position JSON from Share");
    }

    // get the page
    page = Integer.parseInt(String.valueOf(positionObj.get("page")));

    // get the positioning type
    positionType = String.valueOf(positionObj.get("type"));

    // get the position (field or predefined)
    positionLoc = String.valueOf(positionObj.get("position"));

    // get the box (if required)
    box = (JSONObject) positionObj.get("box");

    int width = 350;
    int height = 75;

    File tempDir = null;

    // current date, used for both signing the PDF and creating the
    // associated signature object
    Calendar now = Calendar.getInstance();

    try {
        // get the keystore, pk and cert chain
        SignatureProvider signatureProvider = signatureProviderFactory.getSignatureProvider(user);
        KeyStore keystore = signatureProvider.getUserKeyStore(keyPassword);
        PrivateKey key = (PrivateKey) keystore.getKey(alias, keyPassword.toCharArray());
        Certificate[] chain = keystore.getCertificateChain(alias);

        // open original pdf
        ContentReader pdfReader = getReader(actionedUponNodeRef);
        PdfReader reader = new PdfReader(pdfReader.getContentInputStream());

        // create temp dir to store file
        File alfTempDir = TempFileProvider.getTempDir();
        tempDir = new File(alfTempDir.getPath() + File.separatorChar + actionedUponNodeRef.getId());
        tempDir.mkdir();
        File file = new File(tempDir,
                serviceRegistry.getFileFolderService().getFileInfo(actionedUponNodeRef).getName());
        OutputStream cos = serviceRegistry.getContentService()
                .getWriter(actionedUponNodeRef, ContentModel.PROP_CONTENT, true).getContentOutputStream();

        PdfStamper stamp = PdfStamper.createSignature(reader, cos, '\0', file, true);
        PdfSignatureAppearance sap = stamp.getSignatureAppearance();
        sap.setCrypto(key, chain, null, PdfSignatureAppearance.SELF_SIGNED);

        // set reason for signature, location of signer, and date
        sap.setReason(reason);
        sap.setLocation(location);
        sap.setSignDate(now);

        // get the image for the signature
        BufferedImage sigImage = SignatureToImage.convertJsonToImage(signatureJson, width, height);
        // save the signature image back to the signatureProvider
        signatureProvider.saveSignatureImage(sigImage, signatureJson);

        if (visible) {
            //if this is a graphic sig, set the graphic here
            if (graphic) {
                sap.setRenderingMode(PdfSignatureAppearance.RenderingMode.GRAPHIC);
                sap.setSignatureGraphic(Image.getInstance(sigImage, Color.WHITE));
            } else {
                sap.setRenderingMode(PdfSignatureAppearance.RenderingMode.NAME_AND_DESCRIPTION);
            }

            // either insert the sig at a defined field or at a defined position / drawn loc
            if (positionType.equalsIgnoreCase(POSITION_TYPE_PREDEFINED)) {
                Rectangle pageRect = reader.getPageSizeWithRotation(page);
                sap.setVisibleSignature(positionBlock(positionLoc, pageRect, width, height), page, null);
            } else if (positionType.equalsIgnoreCase(POSITION_TYPE_DRAWN)) {
                Rectangle pageRect = reader.getPageSizeWithRotation(page);
                sap.setVisibleSignature(positionBlock(pageRect, box), page, null);
            } else {
                sap.setVisibleSignature(positionLoc);
                useSignatureField = true;
            }
        }

        // close the stamp, applying the changes to the PDF
        stamp.close();
        reader.close();
        cos.close();

        //delete the temp file
        file.delete();

        // apply the "signed" aspect
        serviceRegistry.getNodeService().addAspect(actionedUponNodeRef, CounterSignSignatureModel.ASPECT_SIGNED,
                new HashMap<QName, Serializable>());

        // create a "signature" node and associate it with the signed doc
        addSignatureNodeAssociation(actionedUponNodeRef, location, reason,
                useSignatureField ? positionLoc : "none", now.getTime(), geolocation, page, positionLoc);

    } catch (IOException e) {
        throw new AlfrescoRuntimeException(e.getMessage(), e);
    } catch (ContentIOException e) {
        throw new AlfrescoRuntimeException(e.getMessage(), e);
    } catch (DocumentException e) {
        throw new AlfrescoRuntimeException(e.getMessage(), e);
    } catch (KeyStoreException e) {
        throw new AlfrescoRuntimeException(e.getMessage(), e);
    } catch (UnrecoverableKeyException e) {
        throw new AlfrescoRuntimeException(e.getMessage(), e);
    } catch (NoSuchAlgorithmException e) {
        throw new AlfrescoRuntimeException(e.getMessage(), e);
    } finally {
        if (tempDir != null) {
            try {
                tempDir.delete();
            } catch (Exception ex) {
                throw new AlfrescoRuntimeException(ex.getMessage(), ex);
            }
        }
    }
}

From source file:org.openanzo.security.keystore.TestSecretKeyEncoder.java

@Override
protected void setUp() throws Exception {
    super.setUp();

    // Load up a keystore from the src/text/resources. We'd rather load up a saved key
    // rather than create a new one every time so that the test is deterministic. 
    KeyStore keyStore = KeyStore.getInstance(KEY_STORE_ENCODING);
    InputStream keystoreStream = Thread.currentThread().getContextClassLoader()
            .getResourceAsStream("testKeystore");
    if (keystoreStream == null) {
        throw new Exception("Could not find keystore.");
    }//from ww w  . j a  v  a  2s  .  c  o  m
    keyStore.load(keystoreStream, TEST_KEYSTORE_PASSWORD);
    Key key;
    if (keyStore.containsAlias(KEY_NAME)) {
        key = keyStore.getKey(KEY_NAME, TEST_KEYSTORE_PASSWORD);
    } else {
        throw new Exception("Could not find test key in test key store.");
    }
    SecretKeyStore encoder = new SecretKeyStore(null, (File) null);
    encoder.initialize((SecretKey) key, ALGORITHM);
    this.encoder = encoder;
}

From source file:test.integ.be.e_contract.mycarenet.ehbox.EHealthBoxPublicationClientTest.java

@Test
public void testPublishAnnex() throws Exception {
    // STS/*from w ww . j  a  v  a  2  s.com*/
    EHealthSTSClient client = new EHealthSTSClient("https://wwwacc.ehealth.fgov.be/sts_1_1/SecureTokenService");

    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");

    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());

    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 assertion = client.requestAssertion(authnCertificate, authnPrivateKey, eHealthCertificate,
            eHealthPrivateKey, attributes, attributeDesignators);

    assertNotNull(assertion);

    String assertionString = client.toString(assertion);

    // eHealthBox publication
    EHealthBoxPublicationClient publicationClient = new EHealthBoxPublicationClient(
            "https://services-acpt.ehealth.fgov.be/ehBoxPublication/v3");

    ObjectFactory objectFactory = new ObjectFactory();
    PublicationMessageType publicationMessage = objectFactory.createPublicationMessageType();
    String publicationId = UUID.randomUUID().toString().substring(1, 13);
    LOG.debug("publication id: " + publicationId);
    publicationMessage.setPublicationId(publicationId);

    DestinationContextType destinationContext = objectFactory.createDestinationContextType();
    publicationMessage.getDestinationContext().add(destinationContext);
    destinationContext.setQuality("NURSE");
    destinationContext.setType("INSS");
    destinationContext.setId(getUserIdentifier(authnCertificate));

    ContentContextType contentContext = objectFactory.createContentContextType();
    publicationMessage.setContentContext(contentContext);

    PublicationContentType publicationContent = objectFactory.createPublicationContentType();
    contentContext.setContent(publicationContent);
    PublicationDocumentType publicationDocument = objectFactory.createPublicationDocumentType();
    publicationContent.setDocument(publicationDocument);
    publicationDocument.setTitle("test");
    publicationDocument.setMimeType("text/plain");
    publicationDocument.setDownloadFileName("test.txt");
    byte[] message = "hello world".getBytes();
    publicationDocument.setEncryptableTextContent(message);
    MessageDigest messageDigest = MessageDigest.getInstance("SHA-256");
    byte[] digest = messageDigest.digest(message);
    publicationDocument.setDigest(Base64.encodeBase64String(digest));

    List<PublicationAnnexType> publicationAnnexList = publicationContent.getAnnex();
    PublicationAnnexType publicationAnnex = objectFactory.createPublicationAnnexType();
    publicationAnnexList.add(publicationAnnex);
    publicationAnnex.setDownloadFileName("test.txt");
    publicationAnnex.setEncryptableTitle("hello world".getBytes());
    publicationAnnex.setMimeType("application/octet-stream");
    publicationAnnex.setEncryptableTextContent(message);
    messageDigest.reset();
    digest = messageDigest.digest(message);
    publicationAnnex.setDigest(Base64.encodeBase64String(digest));

    ContentSpecificationType contentSpecification = objectFactory.createContentSpecificationType();

    contentContext.setContentSpecification(contentSpecification);
    contentSpecification.setContentType("DOCUMENT");

    publicationClient.setCredentials(eHealthPrivateKey, assertionString);
    publicationClient.publish(publicationMessage);
}

From source file:test.integ.be.e_contract.mycarenet.certra.CertRAClientTest.java

@Before
public void setUp() throws Exception {
    KeyStore keyStore = KeyStore.getInstance("BeID");
    BeIDKeyStoreParameter beIDKeyStoreParameter = new BeIDKeyStoreParameter();
    beIDKeyStoreParameter.addPPDUName("digipass 870");
    beIDKeyStoreParameter.addPPDUName("digipass 875");
    beIDKeyStoreParameter.addPPDUName("digipass 920");
    keyStore.load(beIDKeyStoreParameter);
    this.signPrivateKey = (PrivateKey) keyStore.getKey("Signature", null);
    Certificate[] signCertificates = keyStore.getCertificateChain("Signature");

    this.signCertificateChain = new LinkedList<>();
    for (Certificate signCertificate : signCertificates) {
        this.signCertificateChain.add((X509Certificate) signCertificate);
    }/*from w ww  .ja v  a 2  s .c o m*/

    this.client = new CertRAClient("https://services-acpt.ehealth.fgov.be/CertRa/v1");
}

From source file:at.gv.egovernment.moa.id.config.auth.data.BPKDecryptionParameters.java

/**
 * @return//from  w w  w  . ja  v  a  2s.  c  om
 * @throws IOException 
 */
public PrivateKey getPrivateKey() {
    InputStream in = null;
    try {
        in = new ByteArrayInputStream(keyStore);
        KeyStore store = KeyStoreUtils.loadKeyStore(in, keyStorePassword);

        char[] chPassword = " ".toCharArray();
        if (keyPassword != null)
            chPassword = keyPassword.toCharArray();

        //          Certificate test = store.getCertificate(keyAlias);
        //          Base64Utils.encode(test.getPublicKey().getEncoded());

        return (PrivateKey) store.getKey(keyAlias, chPassword);

    } catch (KeyStoreException e) {
        Logger.error("Can not load private key from keystore.", e);

    } catch (IOException e) {
        Logger.error("Can not load private key from keystore.", e);

    } catch (UnrecoverableKeyException e) {
        Logger.error("Can not load private key from keystore.", e);

    } catch (NoSuchAlgorithmException e) {
        Logger.error("Can not load private key from keystore.", e);

    } finally {
        if (in != null) {
            try {
                in.close();
            } catch (IOException e) {
                Logger.warn("Close InputStream failed.", e);
            }
        }
    }

    return null;
}

From source file:ch.cyberduck.core.ssl.CertificateStoreX509KeyManager.java

@Override
public PrivateKey getPrivateKey(final String alias) {
    try {/*  w  w w  . j  a va 2s .  co m*/
        final KeyStore store;
        try {
            store = this.getKeystore();
        } catch (IOException e) {
            return null;
        }
        if (store.isKeyEntry(alias)) {
            final Key key = store.getKey(alias, "null".toCharArray());
            if (key instanceof PrivateKey) {
                return (PrivateKey) key;
            } else {
                log.warn(String.format("Key %s for alias %s is not a private key", key, alias));
            }
        } else {
            log.warn(String.format("Alias %s is not a key entry", alias));
        }
    } catch (KeyStoreException | NoSuchAlgorithmException | UnrecoverableKeyException e) {
        log.error(String.format("Keystore not loaded %s", e.getMessage()));
    }
    log.warn(String.format("No private key for alias %s", alias));
    // Return null if the alias can't be found
    return null;
}

From source file:org.ejbca.ui.cmpclient.CmpClientMessageHelper.java

private Key getKeyFromKeystore(final KeyStore keystore, final String keystorepwd, final String alias)
        throws UnrecoverableKeyException, KeyStoreException, NoSuchAlgorithmException {
    Key key = keystore.getKey(alias, keystorepwd.toCharArray());
    if (key == null) {
        log.error("getAdminDataFromKeystore: Cannot obtain admin key from the keystore.");
        System.exit(2);//ww w . ja v a  2s .c o  m
    }
    return key;
}

From source file:com.zacwolf.commons.crypto.Crypter_AES.java

/**
 * @param keyStore/* w w  w.j av  a  2s.com*/
 * @param keystorepass
 * @param alias
 * @param cipher
 * @param salter
 * @throws UnrecoverableKeyException
 * @throws NoSuchAlgorithmException
 * @throws KeyStoreException
 */
public Crypter_AES(final KeyStore keyStore, final String keystorepass, final String alias, final String cipher,
        final SecureRandom salter)
        throws UnrecoverableKeyException, NoSuchAlgorithmException, KeyStoreException {
    this(keyStore.getKey(alias, keystorepass.toCharArray()).getEncoded(), cipher, salter);
}