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:MainClass.java

public static void main(String args[]) throws Exception {
    String cacert = "mytest.cer";
    String lfcert = "lf_signed.cer";
    String lfstore = "lfkeystore";
    char[] lfstorepass = "wshr.ut".toCharArray();
    char[] lfkeypass = "wshr.ut".toCharArray();
    CertificateFactory cf = CertificateFactory.getInstance("X.509");
    FileInputStream in1 = new FileInputStream(cacert);
    java.security.cert.Certificate cac = cf.generateCertificate(in1);
    in1.close();//from w  ww  .  j a  v a 2s .  c  o  m
    FileInputStream in2 = new FileInputStream(lfcert);
    java.security.cert.Certificate lfc = cf.generateCertificate(in2);
    in2.close();
    java.security.cert.Certificate[] cchain = { lfc, cac };
    FileInputStream in3 = new FileInputStream(lfstore);
    KeyStore ks = KeyStore.getInstance("JKS");
    ks.load(in3, lfstorepass);
    PrivateKey prk = (PrivateKey) ks.getKey("lf", lfkeypass);
    ks.setKeyEntry("lf_signed", prk, lfstorepass, cchain);
    FileOutputStream out4 = new FileOutputStream("lfnewstore");
    ks.store(out4, "newpass".toCharArray());
    out4.close();
}

From source file:MainClass.java

public static void main(String[] args) throws Exception {
    PdfReader reader;//w w  w  .  j  a va2  s. com
    KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
    ks.load(new FileInputStream(".keystore"), "string".toCharArray());
    PrivateKey key = (PrivateKey) ks.getKey("key", "value".toCharArray());
    Certificate[] chain = ks.getCertificateChain("foobar");
    reader = new PdfReader("2.pdf");
    FileOutputStream os = new FileOutputStream("1.pdf");
    PdfStamper stamper = PdfStamper.createSignature(reader, os, '\0');
    PdfSignatureAppearance appearance = stamper.getSignatureAppearance();
    appearance.setCrypto(key, chain, null, PdfSignatureAppearance.SELF_SIGNED);
    appearance.setReason("personal");
    appearance.setLocation("Foobar");
    appearance.setVisibleSignature("yoursig");
    stamper.close();
}

From source file:Main.java

public static void main(String[] argv) throws Exception {
    FileInputStream is = new FileInputStream("your.keystore");

    KeyStore keystore = KeyStore.getInstance(KeyStore.getDefaultType());
    keystore.load(is, "my-keystore-password".toCharArray());

    String alias = "myalias";

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

        // Get public key
        PublicKey publicKey = cert.getPublicKey();

        // Return a key pair
        new KeyPair(publicKey, (PrivateKey) key);
    }/*from   ww w.j  a v  a2s  .  co m*/
}

From source file:com.threerings.getdown.tools.AppletParamSigner.java

public static void main(String[] args) {
    try {//from w  w  w  .j  ava  2 s.  co m
        if (args.length != 7) {
            System.err
                    .println("AppletParamSigner keystore storepass alias keypass " + "appbase appname imgpath");
            System.exit(255);
        }

        String keystore = args[0];
        String storepass = args[1];
        String alias = args[2];
        String keypass = args[3];
        String appbase = args[4];
        String appname = args[5];
        String imgpath = args[6];
        String params = appbase + appname + imgpath;

        KeyStore store = KeyStore.getInstance("JKS");
        store.load(new BufferedInputStream(new FileInputStream(keystore)), storepass.toCharArray());
        PrivateKey key = (PrivateKey) store.getKey(alias, keypass.toCharArray());
        Signature sig = Signature.getInstance("SHA1withRSA");
        sig.initSign(key);
        sig.update(params.getBytes());
        String signed = new String(Base64.encodeBase64(sig.sign()));
        System.out.println("<param name=\"appbase\" value=\"" + appbase + "\" />");
        System.out.println("<param name=\"appname\" value=\"" + appname + "\" />");
        System.out.println("<param name=\"bgimage\" value=\"" + imgpath + "\" />");
        System.out.println("<param name=\"signature\" value=\"" + signed + "\" />");

    } catch (Exception e) {
        System.err.println("Failed to produce signature.");
        e.printStackTrace();
    }
}

From source file:MainClass.java

public static void main(String[] args) throws Exception {
    String keystoreFile = "keyStoreFile.bin";
    String caAlias = "caAlias";
    String certToSignAlias = "cert";
    String newAlias = "newAlias";

    char[] password = new char[] { 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h' };
    char[] caPassword = new char[] { 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h' };
    char[] certPassword = new char[] { 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h' };

    FileInputStream input = new FileInputStream(keystoreFile);
    KeyStore keyStore = KeyStore.getInstance("JKS");
    keyStore.load(input, password);/*  w  ww .j  a  v a 2s . co m*/
    input.close();

    PrivateKey caPrivateKey = (PrivateKey) keyStore.getKey(caAlias, caPassword);
    java.security.cert.Certificate caCert = keyStore.getCertificate(caAlias);

    byte[] encoded = caCert.getEncoded();
    X509CertImpl caCertImpl = new X509CertImpl(encoded);

    X509CertInfo caCertInfo = (X509CertInfo) caCertImpl.get(X509CertImpl.NAME + "." + X509CertImpl.INFO);

    X500Name issuer = (X500Name) caCertInfo.get(X509CertInfo.SUBJECT + "." + CertificateIssuerName.DN_NAME);

    java.security.cert.Certificate cert = keyStore.getCertificate(certToSignAlias);
    PrivateKey privateKey = (PrivateKey) keyStore.getKey(certToSignAlias, certPassword);
    encoded = cert.getEncoded();
    X509CertImpl certImpl = new X509CertImpl(encoded);
    X509CertInfo certInfo = (X509CertInfo) certImpl.get(X509CertImpl.NAME + "." + X509CertImpl.INFO);

    Date firstDate = new Date();
    Date lastDate = new Date(firstDate.getTime() + 365 * 24 * 60 * 60 * 1000L);
    CertificateValidity interval = new CertificateValidity(firstDate, lastDate);

    certInfo.set(X509CertInfo.VALIDITY, interval);

    certInfo.set(X509CertInfo.SERIAL_NUMBER, new CertificateSerialNumber((int) (firstDate.getTime() / 1000)));

    certInfo.set(X509CertInfo.ISSUER + "." + CertificateSubjectName.DN_NAME, issuer);

    AlgorithmId algorithm = new AlgorithmId(AlgorithmId.md5WithRSAEncryption_oid);
    certInfo.set(CertificateAlgorithmId.NAME + "." + CertificateAlgorithmId.ALGORITHM, algorithm);
    X509CertImpl newCert = new X509CertImpl(certInfo);

    newCert.sign(caPrivateKey, "MD5WithRSA");

    keyStore.setKeyEntry(newAlias, privateKey, certPassword, new java.security.cert.Certificate[] { newCert });

    FileOutputStream output = new FileOutputStream(keystoreFile);
    keyStore.store(output, password);
    output.close();

}

From source file:org.apache.xml.security.samples.signature.CreateNullURIReference.java

/**
 * Method main/*  ww w  . ja v a 2  s  .  co m*/
 *
 * @param unused
 * @throws Exception
 */
public static void main(String unused[]) throws Exception {
    //J-
    String keystoreType = "JKS";
    String keystoreFile = "data/org/apache/xml/security/samples/input/keystore.jks";
    String keystorePass = "xmlsecurity";
    String privateKeyAlias = "test";
    String privateKeyPass = "xmlsecurity";
    String certificateAlias = "test";
    File signatureFile = new File("signature.xml");
    //J+
    KeyStore ks = KeyStore.getInstance(keystoreType);
    FileInputStream fis = new FileInputStream(keystoreFile);

    ks.load(fis, keystorePass.toCharArray());

    PrivateKey privateKey = (PrivateKey) ks.getKey(privateKeyAlias, privateKeyPass.toCharArray());
    javax.xml.parsers.DocumentBuilderFactory dbf = javax.xml.parsers.DocumentBuilderFactory.newInstance();

    dbf.setNamespaceAware(true);

    javax.xml.parsers.DocumentBuilder db = dbf.newDocumentBuilder();
    org.w3c.dom.Document doc = db.newDocument();
    String BaseURI = signatureFile.toURL().toString();

    Constants.setSignatureSpecNSprefix(null);

    XMLSignature sig = new XMLSignature(doc, BaseURI, XMLSignature.ALGO_ID_SIGNATURE_DSA);
    byte[][] memoryData = { "The secret data".getBytes(), "dataset 2".getBytes(), };

    sig.addResourceResolver(new NullURIReferenceResolver(memoryData));
    doc.appendChild(sig.getElement());

    {
        sig.addDocument(null, null, Constants.ALGO_ID_DIGEST_SHA1);
        sig.addDocument(null, null, Constants.ALGO_ID_DIGEST_SHA1);
    }

    {
        X509Certificate cert = (X509Certificate) ks.getCertificate(certificateAlias);

        sig.addKeyInfo(cert);
        sig.addKeyInfo(cert.getPublicKey());
        System.out.println("Start signing");
        sig.sign(privateKey);
        System.out.println("Finished signing");
    }

    FileOutputStream f = new FileOutputStream(signatureFile);

    XMLUtils.outputDOMc14nWithComments(doc, f);
    f.close();
    System.out.println("Wrote signature to " + BaseURI);
}

From source file:TestSign.java

/**
 * Method main/*from  w  w  w .  j  ava  2 s .co m*/
 *
 * @param unused
 * @throws Exception
 */
public static void main(String unused[]) throws Exception {
    //J-
    String keystoreType = "JKS";
    String keystoreFile = "data/org/apache/xml/security/samples/input/keystore.jks";
    String keystorePass = "xmlsecurity";
    String privateKeyAlias = "test";
    String privateKeyPass = "xmlsecurity";
    String certificateAlias = "test";
    File signatureFile = new File("signature.xml");
    //J+
    KeyStore ks = KeyStore.getInstance(keystoreType);
    FileInputStream fis = new FileInputStream(keystoreFile);

    ks.load(fis, keystorePass.toCharArray());

    PrivateKey privateKey = (PrivateKey) ks.getKey(privateKeyAlias, privateKeyPass.toCharArray());
    javax.xml.parsers.DocumentBuilderFactory dbf = javax.xml.parsers.DocumentBuilderFactory.newInstance();

    dbf.setNamespaceAware(true);

    javax.xml.parsers.DocumentBuilder db = dbf.newDocumentBuilder();
    org.w3c.dom.Document doc = db.newDocument();
    String BaseURI = signatureFile.toURL().toString();
    XMLSignature sig = new XMLSignature(doc, BaseURI, XMLSignature.ALGO_ID_SIGNATURE_DSA);

    doc.appendChild(sig.getElement());

    {
        ObjectContainer obj = new ObjectContainer(doc);
        Element anElement = doc.createElementNS(null, "InsideObject");

        anElement.appendChild(doc.createTextNode("A text in a box"));
        obj.appendChild(anElement);

        String Id = "TheFirstObject";

        obj.setId(Id);
        sig.appendObject(obj);

        Transforms transforms = new Transforms(doc);

        transforms.addTransform(Transforms.TRANSFORM_C14N_WITH_COMMENTS);
        sig.addDocument("#" + Id, transforms, Constants.ALGO_ID_DIGEST_SHA1);
    }

    {
        X509Certificate cert = (X509Certificate) ks.getCertificate(certificateAlias);

        sig.addKeyInfo(cert);
        sig.addKeyInfo(cert.getPublicKey());
        System.out.println("Start signing");
        sig.sign(privateKey);
        System.out.println("Finished signing");
    }

    FileOutputStream f = new FileOutputStream(signatureFile);

    XMLUtils.outputDOMc14nWithComments(doc, f);
    f.close();
    System.out.println("Wrote signature to " + BaseURI);

    for (int i = 0; i < sig.getSignedInfo().getSignedContentLength(); i++) {
        System.out.println("--- Signed Content follows ---");
        System.out.println(new String(sig.getSignedInfo().getSignedContentItem(i)));
    }
}

From source file:prototype.samples.ExternalSigning.java

/**
 * External signing example//from  w w  w.ja v  a 2  s  . co m
 */
public static void main(String[] args) throws Exception {
    System.setProperty("digidoc4j.mode", "TEST");
    Configuration configuration = new Configuration(Configuration.Mode.TEST);
    Container container = ContainerBuilder.aContainer().withConfiguration(configuration)
            .withDataFile("testFiles/test.txt", "text/plain").build();

    SignatureToken externalSigner = new ExternalSigner(getSignerCert()) {
        @Override
        public byte[] sign(DigestAlgorithm digestAlgorithm, byte[] dataToSign) {

            // IMPLEMENT YOUR EXTERNAL SIGNING HERE

            try {
                KeyStore keyStore = KeyStore.getInstance("PKCS12");
                try (FileInputStream stream = new FileInputStream("testFiles/signout.p12")) {
                    keyStore.load(stream, "test".toCharArray());
                }
                PrivateKey privateKey = (PrivateKey) keyStore.getKey("1", "test".toCharArray());
                final String javaSignatureAlgorithm = "NONEwith" + privateKey.getAlgorithm();

                return AsyncSigning.encrypt(javaSignatureAlgorithm, privateKey, addPadding(dataToSign));
            } catch (Exception e) {
                throw new DigiDoc4JException("Loading private key failed");
            }
        }

        private byte[] addPadding(byte[] digest) {
            return ArrayUtils.addAll(SHA256.digestInfoPrefix(), digest);
        }
    };

    Signature signature = SignatureBuilder.aSignature(container).withSignatureToken(externalSigner)
            .invokeSigning();

    container.addSignature(signature);
    container.save("prototype.bdoc");
}

From source file:org.apache.xml.security.samples.signature.HereSigner.java

/**
 * Method main//from   w w  w  .  java 2 s  .c  o  m
 *
 * @param unused
 * @throws Exception
 */
public static void main(String unused[]) throws Exception {
    //J-
    String keystoreType = "JKS";
    String keystoreFile = "data/org/apache/xml/security/samples/input/keystore.jks";
    String keystorePass = "xmlsecurity";
    String privateKeyAlias = "test";
    String privateKeyPass = "xmlsecurity";
    String certificateAlias = "test";
    File signatureFile = new File("hereSignature.xml");
    //J+
    KeyStore ks = KeyStore.getInstance(keystoreType);
    FileInputStream fis = new FileInputStream(keystoreFile);

    ks.load(fis, keystorePass.toCharArray());

    PrivateKey privateKey = (PrivateKey) ks.getKey(privateKeyAlias, privateKeyPass.toCharArray());
    javax.xml.parsers.DocumentBuilderFactory dbf = javax.xml.parsers.DocumentBuilderFactory.newInstance();

    dbf.setNamespaceAware(true);

    javax.xml.parsers.DocumentBuilder db = dbf.newDocumentBuilder();
    org.w3c.dom.Document doc = db.newDocument();

    String BaseURI = signatureFile.toURL().toString();
    Constants.setSignatureSpecNSprefix("prof");
    XMLSignature sig = new XMLSignature(doc, BaseURI, XMLSignature.ALGO_ID_SIGNATURE_DSA);

    doc.appendChild(sig.getElement());
    sig.getSignedInfo()
            .addResourceResolver(new org.apache.xml.security.samples.utils.resolver.OfflineResolver());

    {
        ObjectContainer ob1 = new ObjectContainer(doc);
        ob1.setId("object-1");
        ob1.appendChild(doc.createTextNode("\nSigned Text\n"));
        Element c = doc.createElementNS(null, "element");
        c.setAttributeNS(null, "name", "val");
        ob1.appendChild(c);
        sig.appendObject(ob1);

        Transforms transforms = new Transforms(doc);
        XPathContainer xc = new XPathContainer(doc);
        xc.setXPathNamespaceContext("prof", Constants.SignatureSpecNS);

        //J-
        String xpath = "\n" + "count(" + "\n" + " ancestor-or-self::prof:Object " + "\n" + " | " + "\n"
                + " here()/ancestor::prof:Signature[1]/child::prof:Object[@Id='object-1']" + "\n"
                + ") <= count(" + "\n" + " ancestor-or-self::prof:Object" + "\n" + ") " + "\n";
        //J+

        xc.setXPath(xpath);
        HelperNodeList nl = new HelperNodeList();
        nl.appendChild(doc.createTextNode("\n"));
        nl.appendChild(xc.getElement());
        nl.appendChild(doc.createTextNode("\n"));

        transforms.addTransform(Transforms.TRANSFORM_XPATH, nl);
        transforms.addTransform(Transforms.TRANSFORM_C14N_WITH_COMMENTS);
        sig.addDocument("", transforms, Constants.ALGO_ID_DIGEST_SHA1);
    }

    {
        X509Certificate cert = (X509Certificate) ks.getCertificate(certificateAlias);

        sig.addKeyInfo(cert);
        sig.addKeyInfo(cert.getPublicKey());
        System.out.println("Start signing");
        sig.sign(privateKey);
        System.out.println("Finished signing");
    }

    SignedInfo s = sig.getSignedInfo();
    for (int i = 0; i < s.getSignedContentLength(); i++) {
        System.out.println(new String(s.getSignedContentItem(i)));
    }

    FileOutputStream f = new FileOutputStream(signatureFile);

    XMLUtils.outputDOMc14nWithComments(doc, f);

    f.close();
    System.out.println("Wrote signature to " + BaseURI);
}

From source file:CertificateSigner.java

public static void main(String[] args) {
    String ksname = null; // the keystore name
    String alias = null; // the private key alias
    String inname = null; // the input file name
    String outname = null; // the output file name
    for (int i = 0; i < args.length; i += 2) {
        if (args[i].equals("-keystore"))
            ksname = args[i + 1];/*w  w w .j ava2 s  .co m*/
        else if (args[i].equals("-alias"))
            alias = args[i + 1];
        else if (args[i].equals("-infile"))
            inname = args[i + 1];
        else if (args[i].equals("-outfile"))
            outname = args[i + 1];
        else
            usage();
    }

    if (ksname == null || alias == null || inname == null || outname == null)
        usage();

    try {
        Console console = System.console();
        if (console == null)
            error("No console");
        char[] password = console.readPassword("Keystore password: ");
        KeyStore store = KeyStore.getInstance("JKS", "SUN");
        InputStream in = new FileInputStream(ksname);
        store.load(in, password);
        Arrays.fill(password, ' ');
        in.close();

        char[] keyPassword = console.readPassword("Key password for %s: ", alias);
        PrivateKey issuerPrivateKey = (PrivateKey) store.getKey(alias, keyPassword);
        Arrays.fill(keyPassword, ' ');

        if (issuerPrivateKey == null)
            error("No such private key");

        in = new FileInputStream(inname);

        CertificateFactory factory = CertificateFactory.getInstance("X.509");

        X509Certificate inCert = (X509Certificate) factory.generateCertificate(in);
        in.close();
        byte[] inCertBytes = inCert.getTBSCertificate();

        X509Certificate issuerCert = (X509Certificate) store.getCertificate(alias);
        Principal issuer = issuerCert.getSubjectDN();
        String issuerSigAlg = issuerCert.getSigAlgName();

        FileOutputStream out = new FileOutputStream(outname);

        X509CertInfo info = new X509CertInfo(inCertBytes);
        info.set(X509CertInfo.ISSUER, new CertificateIssuerName((X500Name) issuer));

        X509CertImpl outCert = new X509CertImpl(info);
        outCert.sign(issuerPrivateKey, issuerSigAlg);
        outCert.derEncode(out);

        out.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
}