Example usage for java.security KeyPairGenerator generateKeyPair

List of usage examples for java.security KeyPairGenerator generateKeyPair

Introduction

In this page you can find the example usage for java.security KeyPairGenerator generateKeyPair.

Prototype

public KeyPair generateKeyPair() 

Source Link

Document

Generates a key pair.

Usage

From source file:com.emc.ecs.s3.sample.ECSS3Factory.java

public static void main(String[] args) {
    try {/*  w w  w . ja v  a  2s  .  co m*/
        KeyPairGenerator keyGenerator = KeyPairGenerator.getInstance("RSA");
        keyGenerator.initialize(1024, new SecureRandom());
        KeyPair myKeyPair = keyGenerator.generateKeyPair();

        // Serialize.
        byte[] pubKeyBytes = myKeyPair.getPublic().getEncoded();
        byte[] privKeyBytes = myKeyPair.getPrivate().getEncoded();

        String pubKeyStr = new String(Base64.encodeBase64(pubKeyBytes, false), "US-ASCII");
        String privKeyStr = new String(Base64.encodeBase64(privKeyBytes, false), "US-ASCII");

        System.out.println("Public Key: " + pubKeyStr);
        System.out.println("Private Key: " + privKeyStr);
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:testSig.java

public static void main(String[] args) {

    /* Test generating and verifying a DSA signature */

    try {//from ww  w .  j  ava2 s. c o  m

        /* generate a key pair */

        KeyPairGenerator keyGen = KeyPairGenerator.getInstance("DSA");
        keyGen.initialize(1024, new SecureRandom());
        KeyPair pair = keyGen.generateKeyPair();

        /*
         * create a Signature object to use for signing and verifying
         */

        Signature dsa = Signature.getInstance("SHA/DSA");

        /* initialize the Signature object for signing */

        PrivateKey priv = pair.getPrivate();

        dsa.initSign(priv);

        /* Update and sign the data */

        FileInputStream fis = new FileInputStream(args[0]);
        byte b;
        while (fis.available() != 0) {
            b = (byte) fis.read();
            dsa.update(b);
        }
        ;

        fis.close();

        /*
         * Now that all the data to be signed has been read in, sign it
         */
        byte[] sig = dsa.sign();

        /* Verify the signature */

        /* Initialize the Signature object for verification */
        PublicKey pub = pair.getPublic();
        dsa.initVerify(pub);

        /* Update and verify the data */

        fis = new FileInputStream(args[0]);
        while (fis.available() != 0) {
            b = (byte) fis.read();
            dsa.update(b);
        }
        ;

        fis.close();

        boolean verifies = dsa.verify(sig);

        System.out.println("signature verifies: " + verifies);

    } catch (Exception e) {
        System.err.println("Caught exception " + e.toString());
    }

}

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

/**
 * Method main/* w  ww.  j a va2  s  .  c  om*/
 *
 * @param unused
 * @throws Exception
 */
public static void main(String unused[]) throws Exception {

    org.apache.xml.security.Init.init();

    javax.xml.parsers.DocumentBuilderFactory dbf = javax.xml.parsers.DocumentBuilderFactory.newInstance();

    dbf.setNamespaceAware(true);

    javax.xml.parsers.DocumentBuilder db = dbf.newDocumentBuilder();

    // test digests in references
    macAndWrite(db, "secret".getBytes("UTF-8"), XMLSignature.ALGO_ID_MAC_HMAC_SHA1,
            MessageDigestAlgorithm.ALGO_ID_DIGEST_SHA1, "MacSha1_DigestSha1.xml");
    macAndWrite(db, "secret".getBytes("UTF-8"), XMLSignature.ALGO_ID_MAC_HMAC_SHA1,
            MessageDigestAlgorithm.ALGO_ID_DIGEST_SHA256, "MacSha1_DigestSha256.xml");
    macAndWrite(db, "secret".getBytes("UTF-8"), XMLSignature.ALGO_ID_MAC_HMAC_SHA1,
            MessageDigestAlgorithm.ALGO_ID_DIGEST_SHA384, "MacSha1_DigestSha384.xml");
    macAndWrite(db, "secret".getBytes("UTF-8"), XMLSignature.ALGO_ID_MAC_HMAC_SHA1,
            MessageDigestAlgorithm.ALGO_ID_DIGEST_SHA512, "MacSha1_DigestSha512.xml");
    macAndWrite(db, "secret".getBytes("UTF-8"), XMLSignature.ALGO_ID_MAC_HMAC_SHA1,
            MessageDigestAlgorithm.ALGO_ID_DIGEST_RIPEMD160, "MacSha1_DigestRipemd160.xml");
    macAndWrite(db, "secret".getBytes("UTF-8"), XMLSignature.ALGO_ID_MAC_HMAC_SHA1,
            MessageDigestAlgorithm.ALGO_ID_DIGEST_NOT_RECOMMENDED_MD5, "MacSha1_DigestMd5.xml");

    // test digests in hmacs
    macAndWrite(db, "secret".getBytes("UTF-8"), XMLSignature.ALGO_ID_MAC_HMAC_SHA1,
            MessageDigestAlgorithm.ALGO_ID_DIGEST_SHA1, "MacSha1_DigestSha1.xml");
    macAndWrite(db, "secret".getBytes("UTF-8"), XMLSignature.ALGO_ID_MAC_HMAC_SHA256,
            MessageDigestAlgorithm.ALGO_ID_DIGEST_SHA1, "MacSha256_DigestSha1.xml");
    macAndWrite(db, "secret".getBytes("UTF-8"), XMLSignature.ALGO_ID_MAC_HMAC_SHA384,
            MessageDigestAlgorithm.ALGO_ID_DIGEST_SHA1, "MacSha384_DigestSha1.xml");
    macAndWrite(db, "secret".getBytes("UTF-8"), XMLSignature.ALGO_ID_MAC_HMAC_SHA512,
            MessageDigestAlgorithm.ALGO_ID_DIGEST_SHA1, "MacSha512_DigestSha1.xml");
    macAndWrite(db, "secret".getBytes("UTF-8"), XMLSignature.ALGO_ID_MAC_HMAC_RIPEMD160,
            MessageDigestAlgorithm.ALGO_ID_DIGEST_SHA1, "MacRipemd160_DigestSha1.xml");
    macAndWrite(db, "secret".getBytes("UTF-8"), XMLSignature.ALGO_ID_MAC_HMAC_NOT_RECOMMENDED_MD5,
            MessageDigestAlgorithm.ALGO_ID_DIGEST_SHA1, "MacMd5_DigestSha1.xml");

    KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA", "BC");
    KeyPair keyPair = kpg.generateKeyPair();
    PrivateKey privateKey = keyPair.getPrivate();
    PublicKey pubkey = keyPair.getPublic();

    // test digests in RSA
    signAndWrite(db, privateKey, pubkey, XMLSignature.ALGO_ID_SIGNATURE_RSA_SHA1,
            MessageDigestAlgorithm.ALGO_ID_DIGEST_SHA1, "SignatureRsaSha1_DigestSha1.xml");
    signAndWrite(db, privateKey, pubkey, XMLSignature.ALGO_ID_SIGNATURE_RSA_SHA256,
            MessageDigestAlgorithm.ALGO_ID_DIGEST_SHA1, "SignatureRsaSha256_DigestSha1.xml");
    signAndWrite(db, privateKey, pubkey, XMLSignature.ALGO_ID_SIGNATURE_RSA_SHA384,
            MessageDigestAlgorithm.ALGO_ID_DIGEST_SHA1, "SignatureRsaSha384_DigestSha1.xml");
    signAndWrite(db, privateKey, pubkey, XMLSignature.ALGO_ID_SIGNATURE_RSA_SHA512,
            MessageDigestAlgorithm.ALGO_ID_DIGEST_SHA1, "SignatureRsaSha512_DigestSha1.xml");
    signAndWrite(db, privateKey, pubkey, XMLSignature.ALGO_ID_SIGNATURE_RSA_RIPEMD160,
            MessageDigestAlgorithm.ALGO_ID_DIGEST_SHA1, "SignatureRsaRipemd160_DigestSha1.xml");
    signAndWrite(db, privateKey, pubkey, XMLSignature.ALGO_ID_SIGNATURE_NOT_RECOMMENDED_RSA_MD5,
            MessageDigestAlgorithm.ALGO_ID_DIGEST_SHA1, "SignatureRsaMd5_DigestSha1.xml");
}

From source file:MainClass.java

public static void main(String args[]) throws Exception {
    KeyPairGenerator keyGen = KeyPairGenerator.getInstance("DSA");
    SecureRandom random = SecureRandom.getInstance("SHA1PRNG", "SUN");
    random.setSeed(101L);//from  www. ja v  a  2  s. c o m
    keyGen.initialize(1024, random);
    KeyPair keypair = keyGen.generateKeyPair();

    KeyFactory kfactory = KeyFactory.getInstance("DSA");

    DSAPublicKeySpec kspec = (DSAPublicKeySpec) kfactory.getKeySpec(keypair.getPublic(),
            DSAPublicKeySpec.class);

    System.out.println(keypair.getPublic());
    FileOutputStream fos = new FileOutputStream("publicKeys");
    ObjectOutputStream oos = new ObjectOutputStream(fos);

    oos.writeObject(kspec.getY());
    oos.writeObject(kspec.getP());
    oos.writeObject(kspec.getQ());
    oos.writeObject(kspec.getG());

    FileInputStream fin = new FileInputStream("publicKeys");
    ObjectInputStream ois = new ObjectInputStream(fin);

    BigInteger Y = (BigInteger) ois.readObject();
    BigInteger P = (BigInteger) ois.readObject();
    BigInteger Q = (BigInteger) ois.readObject();
    BigInteger G = (BigInteger) ois.readObject();

    DSAPublicKeySpec keyspec = new DSAPublicKeySpec(Y, P, Q, G);
    PublicKey pkey = kfactory.generatePublic(keyspec);
    System.out.println(pkey);
}

From source file:SignatureTest.java

public static void main(String[] args) {
    try {//from  w ww .  j  a  va  2 s.  co m
        if (args[0].equals("-genkeypair")) {
            KeyPairGenerator pairgen = KeyPairGenerator.getInstance("DSA");
            SecureRandom random = new SecureRandom();
            pairgen.initialize(KEYSIZE, random);
            KeyPair keyPair = pairgen.generateKeyPair();
            ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream(args[1]));
            out.writeObject(keyPair.getPublic());
            out.close();
            out = new ObjectOutputStream(new FileOutputStream(args[2]));
            out.writeObject(keyPair.getPrivate());
            out.close();
        } else if (args[0].equals("-sign")) {
            ObjectInputStream keyIn = new ObjectInputStream(new FileInputStream(args[3]));
            PrivateKey privkey = (PrivateKey) keyIn.readObject();
            keyIn.close();

            Signature signalg = Signature.getInstance("DSA");
            signalg.initSign(privkey);

            File infile = new File(args[1]);
            InputStream in = new FileInputStream(infile);
            int length = (int) infile.length();
            byte[] message = new byte[length];
            in.read(message, 0, length);
            in.close();

            signalg.update(message);
            byte[] signature = signalg.sign();

            DataOutputStream out = new DataOutputStream(new FileOutputStream(args[2]));
            int signlength = signature.length;
            out.writeInt(signlength);
            out.write(signature, 0, signlength);
            out.write(message, 0, length);
            out.close();
        } else if (args[0].equals("-verify")) {
            ObjectInputStream keyIn = new ObjectInputStream(new FileInputStream(args[2]));
            PublicKey pubkey = (PublicKey) keyIn.readObject();
            keyIn.close();

            Signature verifyalg = Signature.getInstance("DSA");
            verifyalg.initVerify(pubkey);

            File infile = new File(args[1]);
            DataInputStream in = new DataInputStream(new FileInputStream(infile));
            int signlength = in.readInt();
            byte[] signature = new byte[signlength];
            in.read(signature, 0, signlength);

            int length = (int) infile.length() - signlength - 4;
            byte[] message = new byte[length];
            in.read(message, 0, length);
            in.close();

            verifyalg.update(message);
            if (!verifyalg.verify(signature))
                System.out.print("not ");
            System.out.println("verified");
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:Signing.java

public static void main(String[] args) throws Exception {
        SOAPMessage soapMessage = MessageFactory.newInstance().createMessage();
        SOAPPart soapPart = soapMessage.getSOAPPart();
        SOAPEnvelope soapEnvelope = soapPart.getEnvelope();

        SOAPHeader soapHeader = soapEnvelope.getHeader();
        SOAPHeaderElement headerElement = soapHeader.addHeaderElement(soapEnvelope.createName("Signature",
                "SOAP-SEC", "http://schemas.xmlsoap.org/soap/security/2000-12"));

        SOAPBody soapBody = soapEnvelope.getBody();
        soapBody.addAttribute(/*from   w w  w . j  a  va 2 s.  c o  m*/
                soapEnvelope.createName("id", "SOAP-SEC", "http://schemas.xmlsoap.org/soap/security/2000-12"),
                "Body");
        Name bodyName = soapEnvelope.createName("FooBar", "z", "http://example.com");
        SOAPBodyElement gltp = soapBody.addBodyElement(bodyName);

        Source source = soapPart.getContent();
        Node root = null;
        if (source instanceof DOMSource) {
            root = ((DOMSource) source).getNode();
        } else if (source instanceof SAXSource) {
            InputSource inSource = ((SAXSource) source).getInputSource();
            DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
            dbf.setNamespaceAware(true);
            DocumentBuilder db = null;

            db = dbf.newDocumentBuilder();

            Document doc = db.parse(inSource);
            root = (Node) doc.getDocumentElement();
        }

        dumpDocument(root);

        KeyPairGenerator kpg = KeyPairGenerator.getInstance("DSA");
        kpg.initialize(1024, new SecureRandom());
        KeyPair keypair = kpg.generateKeyPair();

        XMLSignatureFactory sigFactory = XMLSignatureFactory.getInstance();
        Reference ref = sigFactory.newReference("#Body", sigFactory.newDigestMethod(DigestMethod.SHA1, null));
        SignedInfo signedInfo = sigFactory.newSignedInfo(
                sigFactory.newCanonicalizationMethod(CanonicalizationMethod.INCLUSIVE_WITH_COMMENTS,
                        (C14NMethodParameterSpec) null),
                sigFactory.newSignatureMethod(SignatureMethod.DSA_SHA1, null), Collections.singletonList(ref));
        KeyInfoFactory kif = sigFactory.getKeyInfoFactory();
        KeyValue kv = kif.newKeyValue(keypair.getPublic());
        KeyInfo keyInfo = kif.newKeyInfo(Collections.singletonList(kv));

        XMLSignature sig = sigFactory.newXMLSignature(signedInfo, keyInfo);

        System.out.println("Signing the message...");
        PrivateKey privateKey = keypair.getPrivate();
        Element envelope = getFirstChildElement(root);
        Element header = getFirstChildElement(envelope);
        DOMSignContext sigContext = new DOMSignContext(privateKey, header);
        sigContext.putNamespacePrefix(XMLSignature.XMLNS, "ds");
        sigContext.setIdAttributeNS(getNextSiblingElement(header),
                "http://schemas.xmlsoap.org/soap/security/2000-12", "id");
        sig.sign(sigContext);

        dumpDocument(root);

        System.out.println("Validate the signature...");
        Element sigElement = getFirstChildElement(header);
        DOMValidateContext valContext = new DOMValidateContext(keypair.getPublic(), sigElement);
        valContext.setIdAttributeNS(getNextSiblingElement(header),
                "http://schemas.xmlsoap.org/soap/security/2000-12", "id");
        boolean valid = sig.validate(valContext);

        System.out.println("Signature valid? " + valid);
    }

From source file:GenSig.java

public static void main(String[] args) {

    /* Generate a DSA signature */

    if (args.length != 1) {
        System.out.println("Usage: GenSig nameOfFileToSign");
    } else//from   w w w. jav  a2s .c o m
        try {

            /* Generate a key pair */

            KeyPairGenerator keyGen = KeyPairGenerator.getInstance("DSA", "SUN");
            SecureRandom random = SecureRandom.getInstance("SHA1PRNG", "SUN");

            keyGen.initialize(1024, random);

            KeyPair pair = keyGen.generateKeyPair();
            PrivateKey priv = pair.getPrivate();
            PublicKey pub = pair.getPublic();

            /*
             * Create a Signature object and initialize it with the private
             * key
             */

            Signature dsa = Signature.getInstance("SHA1withDSA", "SUN");

            dsa.initSign(priv);

            /* Update and sign the data */

            FileInputStream fis = new FileInputStream(args[0]);
            BufferedInputStream bufin = new BufferedInputStream(fis);
            byte[] buffer = new byte[1024];
            int len;
            while (bufin.available() != 0) {
                len = bufin.read(buffer);
                dsa.update(buffer, 0, len);
            }
            ;

            bufin.close();

            /*
             * Now that all the data to be signed has been read in, generate
             * a signature for it
             */

            byte[] realSig = dsa.sign();

            /* Save the signature in a file */
            FileOutputStream sigfos = new FileOutputStream("sig");
            sigfos.write(realSig);

            sigfos.close();

            /* Save the public key in a file */
            byte[] key = pub.getEncoded();
            FileOutputStream keyfos = new FileOutputStream("suepk");
            keyfos.write(key);

            keyfos.close();

        } catch (Exception e) {
            System.err.println("Caught exception " + e.toString());
        }

}

From source file:RSATest.java

public static void main(String[] args) {
    try {//w  w  w  .  j a  va2s  .c o  m
        if (args[0].equals("-genkey")) {
            KeyPairGenerator pairgen = KeyPairGenerator.getInstance("RSA");
            SecureRandom random = new SecureRandom();
            pairgen.initialize(KEYSIZE, random);
            KeyPair keyPair = pairgen.generateKeyPair();
            ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream(args[1]));
            out.writeObject(keyPair.getPublic());
            out.close();
            out = new ObjectOutputStream(new FileOutputStream(args[2]));
            out.writeObject(keyPair.getPrivate());
            out.close();
        } else if (args[0].equals("-encrypt")) {
            KeyGenerator keygen = KeyGenerator.getInstance("AES");
            SecureRandom random = new SecureRandom();
            keygen.init(random);
            SecretKey key = keygen.generateKey();

            // wrap with RSA public key
            ObjectInputStream keyIn = new ObjectInputStream(new FileInputStream(args[3]));
            Key publicKey = (Key) keyIn.readObject();
            keyIn.close();

            Cipher cipher = Cipher.getInstance("RSA");
            cipher.init(Cipher.WRAP_MODE, publicKey);
            byte[] wrappedKey = cipher.wrap(key);
            DataOutputStream out = new DataOutputStream(new FileOutputStream(args[2]));
            out.writeInt(wrappedKey.length);
            out.write(wrappedKey);

            InputStream in = new FileInputStream(args[1]);
            cipher = Cipher.getInstance("AES");
            cipher.init(Cipher.ENCRYPT_MODE, key);
            crypt(in, out, cipher);
            in.close();
            out.close();
        } else {
            DataInputStream in = new DataInputStream(new FileInputStream(args[1]));
            int length = in.readInt();
            byte[] wrappedKey = new byte[length];
            in.read(wrappedKey, 0, length);

            // unwrap with RSA private key
            ObjectInputStream keyIn = new ObjectInputStream(new FileInputStream(args[3]));
            Key privateKey = (Key) keyIn.readObject();
            keyIn.close();

            Cipher cipher = Cipher.getInstance("RSA");
            cipher.init(Cipher.UNWRAP_MODE, privateKey);
            Key key = cipher.unwrap(wrappedKey, "AES", Cipher.SECRET_KEY);

            OutputStream out = new FileOutputStream(args[2]);
            cipher = Cipher.getInstance("AES");
            cipher.init(Cipher.DECRYPT_MODE, key);

            crypt(in, out, cipher);
            in.close();
            out.close();
        }
    } catch (IOException e) {
        e.printStackTrace();
    } catch (GeneralSecurityException e) {
        e.printStackTrace();
    } catch (ClassNotFoundException e) {
        e.printStackTrace();
    }
}

From source file:mitm.common.security.ca.handlers.ejbca.ws.EjbcaWSClient.java

public static void main(String args[]) throws Exception {
    BasicConfigurator.configure();/*w  ww  . j  a v a  2  s.com*/

    JaxWsProxyFactoryBean factory = new JaxWsProxyFactoryBean();

    factory.setServiceClass(EjbcaWS.class);
    factory.setAddress("https://192.168.178.113:8443/ejbca/ejbcaws/ejbcaws");
    factory.setServiceName(SERVICE_NAME);

    EjbcaWS client = (EjbcaWS) factory.create();

    Client proxy = ClientProxy.getClient(client);
    HTTPConduit conduit = (HTTPConduit) proxy.getConduit();
    TLSClientParameters tlsClientParameters = new TLSClientParameters();

    KeyManagerFactory keyManagerFactory = KeyManagerFactory
            .getInstance(KeyManagerFactory.getDefaultAlgorithm());

    java.security.KeyStore keyStore = java.security.KeyStore.getInstance("PKCS12");
    InputStream keyInput = new FileInputStream("/home/martijn/temp/superadmin.p12");

    String password = "ejbca";

    keyStore.load(keyInput, password.toCharArray());
    keyInput.close();
    keyManagerFactory.init(keyStore, password.toCharArray());

    KeyManager[] keyManagers = keyManagerFactory.getKeyManagers();

    tlsClientParameters.setDisableCNCheck(true);

    tlsClientParameters.setKeyManagers(keyManagers);

    X509TrustManager trustAll = new X509TrustManager() {
        @Override
        public void checkClientTrusted(X509Certificate[] paramArrayOfX509Certificate, String paramString)
                throws CertificateException {
        }

        @Override
        public void checkServerTrusted(X509Certificate[] paramArrayOfX509Certificate, String paramString)
                throws CertificateException {
        }

        @Override
        public X509Certificate[] getAcceptedIssuers() {
            return null;
        }
    };

    TrustManagerFactory trustManagerFactory = TrustManagerFactory
            .getInstance(TrustManagerFactory.getDefaultAlgorithm());

    trustManagerFactory.init(new KeyStoreLoader().loadKeyStore(new File("/home/martijn/temp/truststore.jks"),
            "changeit".toCharArray()));

    tlsClientParameters.setTrustManagers(new TrustManager[] { trustAll });
    //tlsClientParameters.setTrustManagers(trustManagerFactory.getTrustManagers());

    conduit.setTlsClientParameters(tlsClientParameters);

    System.out.println(client.getEjbcaVersion());

    UserDataVOWS userData = new UserDataVOWS();

    userData.setEmail("test@example.com");
    userData.setUsername("test@example.com");
    //userData.setPassword("test@example.com");
    userData.setSubjectDN("CN=test@example.com");
    userData.setSubjectAltName("rfc822Name=test@example.com");
    userData.setEndEntityProfileName("test");
    userData.setCaName("AdminCA1");
    userData.setCertificateProfileName("ENDUSER");
    userData.setStatus(EJBCAConst.STATUS_NEW);
    userData.setTokenType(EJBCAConst.TOKEN_TYPE_USERGENERATED);

    try {
        //client.editUser(userData);

        SecurityFactory securityFactory = SecurityFactoryFactory.getSecurityFactory();

        SecureRandom randomSource = securityFactory.createSecureRandom();

        KeyPairGenerator keyPairGenerator = securityFactory.createKeyPairGenerator("RSA");

        keyPairGenerator.initialize(2048, randomSource);

        KeyPair keyPair = keyPairGenerator.generateKeyPair();

        X500PrincipalBuilder builder = new X500PrincipalBuilder();

        builder.setCommonName("john doe");
        builder.setEmail("test@example.com");

        PKCS10CertificationRequestBuilder requestBuilder = new PKCS10CertificationRequestBuilder(
                X500PrincipalUtils.toX500Name(builder.buildPrincipal()),
                SubjectPublicKeyInfo.getInstance(keyPair.getPublic().getEncoded()));

        PKCS10CertificationRequest pkcs10 = requestBuilder
                .build(getContentSigner("SHA1WithRSA", keyPair.getPrivate()));

        String base64PKCS10 = Base64Utils.encode(pkcs10.getEncoded());

        CertificateResponse certificateResponse = client.certificateRequest(userData, base64PKCS10,
                EJBCAConst.CERT_REQ_TYPE_PKCS10, null, EJBCAConst.RESPONSETYPE_CERTIFICATE);

        if (certificateResponse != null && certificateResponse.getData() != null) {
            /*
             * The result is a base64 encoded certificate 
             */
            Collection<X509Certificate> certificates = CertificateUtils.readX509Certificates(
                    new ByteArrayInputStream(Base64.decode(certificateResponse.getData())));

            if (CollectionUtils.isNotEmpty(certificates)) {
                for (X509Certificate certificate : certificates) {
                    System.out.println(certificate);
                }
            } else {
                System.out.println("No certificates found");
            }
        } else {
            System.out.println("certificateResponse is empty");
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:com.clustercontrol.util.KeyCheck.java

/**
 * ????????/*  ww  w .  j a va 2s . c  om*/
 * 
 * @param args
 */
public static void main(String[] args) {
    PrivateKey privateKey = null;
    PublicKey publicKey = null;

    /// ??????? true
    /// ???????? false (?)
    boolean flag = false;
    if (flag) {
        try {
            // ?
            privateKey = getPrivateKey(
                    "???????privateKey.txt??");

            // ?
            publicKey = getPublicKey("???????");
            // publicKey = getPublicKey(publicKeyStr);
        } catch (Exception e) {
            System.out.println("hoge" + e.getMessage());
        }
    } else {
        KeyPairGenerator generator;
        try {
            generator = KeyPairGenerator.getInstance(ALGORITHM);
            SecureRandom random = SecureRandom.getInstance("SHA1PRNG");
            // ?? 1024
            generator.initialize(1024, random);
            KeyPair keyPair = generator.generateKeyPair();
            privateKey = keyPair.getPrivate();
            publicKey = keyPair.getPublic();
        } catch (NoSuchAlgorithmException ex) {
            System.out.println(ex.getMessage());
        }
    }

    //
    // ?
    System.out.println("?");
    System.out.println(byte2String(privateKey.getEncoded()));
    System.out.println("?");
    System.out.println(byte2String(publicKey.getEncoded()));

    // ???????
    String string = "20140701_nttdata";
    byte[] src = string.getBytes();
    System.out.println("??String");
    System.out.println(string);
    System.out.println("??byte");
    System.out.println(byte2String(src));

    // ?
    try {
        String encStr = encrypt(string, privateKey);
        System.out.println("?");
        System.out.println(encStr);

        // ?
        String decStr = decrypt(encStr, publicKey);
        System.out.println("?");
        System.out.println(decStr);
    } catch (Exception e) {
        System.out.println(e.getMessage());
    }

}