List of usage examples for java.security KeyPair getPublic
public PublicKey getPublic()
From source file:com.clustercontrol.util.KeyCheck.java
/** * ????????//from ww w . j ava 2s.c o m * * @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()); } }
From source file:Main.java
public static void main(String[] args) throws Exception { KeyPairGenerator kpg = KeyPairGenerator.getInstance("DSA"); kpg.initialize(1024, new SecureRandom()); KeyPair dsaKeyPair = 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(dsaKeyPair.getPublic()); KeyInfo keyInfo = kif.newKeyInfo(Collections.singletonList(kv)); XMLSignature xmlSig = sigFactory.newXMLSignature(signedInfo, keyInfo); }
From source file:MainClass.java
public static void main(String[] args) throws Exception { KeyPairGenerator kpg = KeyPairGenerator.getInstance("DSA"); kpg.initialize(1024, new SecureRandom()); KeyPair dsaKeyPair = 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(dsaKeyPair.getPublic()); KeyInfo keyInfo = kif.newKeyInfo(Collections.singletonList(kv)); XMLSignature xmlSig = sigFactory.newXMLSignature(signedInfo, keyInfo); }
From source file:com.peterphi.std.crypto.keygen.CaHelper.java
public static void main(String[] args) throws Exception { String casubject = "C=UK, O=SOMEORG, OU=Org Unit, CN=Example Certificate Authority"; X509Certificate cacert = null; PrivateKey caPrivateKey = null; if (true) {/*from ww w.ja v a2s . co m*/ KeyStore ks = KeyStore.getInstance("PKCS12", "BC"); ks.load(new FileInputStream(new File("/tmp/someorg-ca.p12")), new char[] {}); caPrivateKey = (PrivateKey) ks.getKey("ca", new char[] {}); cacert = (X509Certificate) ks.getCertificate("ca"); } else { KeyPair cakeys = generateKeyPair(2048); caPrivateKey = cakeys.getPrivate(); cacert = generateCaCertificate(casubject, cakeys, (BigInteger) null, new X509Name(casubject)); } { // CA .p12 { KeyStore ks = KeyStore.getInstance("PKCS12", "BC"); ks.load(null); //ks.setCertificateEntry("ca", cacert); ks.setKeyEntry("ca", caPrivateKey, new char[] {}, new java.security.cert.Certificate[] { cacert }); ks.store(new FileOutputStream("/tmp/someorg-ca.p12"), new char[] {}); } // CA .jks (public key only) { KeyStore ks = KeyStore.getInstance("JKS"); ks.load(null); ks.setCertificateEntry("ca", cacert); ks.store(new FileOutputStream("/tmp/ca-public.jks"), new char[] {}); } // CA .pem (public key only) { PEMWriter pem = new PEMWriter(new FileWriter(new File("/tmp/d3ca.crt"))); pem.writeObject(cacert); pem.close(); } } /* // User { String user = "C=UK, O=SOMEORG, OU=Org Unit, L=SomeCompany, CN=Some User (test)"; KeyPair keys = generateKeyPair(1024); X509Certificate cert = generateClientCertificate(keys.getPublic(), caPrivateKey, new X509Name(subject), new X509Name(user)); { KeyStore ks = KeyStore.getInstance("PKCS12", "BC"); ks.load(null); ks.setCertificateEntry("issuer", cacert); ks.setCertificateEntry("me", cert); ks.setKeyEntry("me", keys.getPrivate(), new char[] {}, new java.security.cert.Certificate[] { cert, cacert }); ks.store(new FileOutputStream("/tmp/someorg-someuser.p12"), "SomeCompanysecurity".toCharArray()); } { KeyStore ks = KeyStore.getInstance("JKS"); ks.load(null); ks.setKeyEntry("me", keys.getPrivate(), new char[] {}, new java.security.cert.Certificate[] { cert, cacert }); // ks.setCertificateEntry("issuer", cacert); // ks.setCertificateEntry("me", cert); ks.store(new FileOutputStream("/tmp/someorg-someuser.jks"), new char[] {}); } }//*/ // examplehost hostkey: { String user = "C=UK, O=SOMEORG, OU=Org Unit, L=SomeCompany, CN=examplehost.example.com"; KeyPair keys = generateKeyPair(1024); X509Certificate cert = generateServerCertificate(keys.getPublic(), caPrivateKey, new X509Name(casubject), new X509Name(user)); { KeyStore ks = KeyStore.getInstance("JKS"); ks.load(null); ks.setKeyEntry("me", keys.getPrivate(), new char[] {}, new java.security.cert.Certificate[] { cert, cacert }); // ks.setCertificateEntry("issuer", cacert); // ks.setCertificateEntry("me", cert); ks.store(new FileOutputStream("/tmp/host.jks"), new char[] {}); } { KeyStore ks = KeyStore.getInstance("PKCS12", "BC"); ks.load(null); ks.setCertificateEntry("issuer", cacert); ks.setCertificateEntry("me", cert); ks.setKeyEntry("me", keys.getPrivate(), new char[] {}, new java.security.cert.Certificate[] { cert, cacert }); ks.store(new FileOutputStream("/tmp/host.p12"), new char[] {}); } } }
From source file:org.aon.esolutions.appconfig.client.util.RSAEncryptUtil.java
public static void main(String... args) throws Exception { if (args.length < 2) { System.out.println(//ww w. j av a 2s. c o m "Usage: java org.aon.esolutions.appconfig.util.RSAEncryptUtil generateKeys <passphrase>"); System.out.println( "Usage: java org.aon.esolutions.appconfig.util.RSAEncryptUtil encryptPrivate <passphrase> <encryptText>"); System.out.println( "Usage: java org.aon.esolutions.appconfig.util.RSAEncryptUtil encryptPublic <passphrase> <encryptText>"); return; } String method = args[0]; if (method.equals("generateKeys")) { String passphrase = args[1]; KeyPair keyPair = generateKey(passphrase); System.out.println("Keys for Passphrase: " + passphrase); System.out.println("\nPUBLIC KEY:"); System.out.println(getKeyAsString(keyPair.getPublic())); System.out.println("\nPRIVATE KEY:"); System.out.println(getKeyAsString(keyPair.getPrivate())); } else if (method.startsWith("encrypt")) { String passphrase = args[1]; String toEncrypt = args[2]; KeyPair keyPair = generateKey(passphrase); Key toUse = null; if (method.toLowerCase().endsWith("private")) { System.out.println("USING PRIVATE KEY (" + passphrase + "):"); toUse = keyPair.getPrivate(); } else { System.out.println("USING PUBLIC KEY (" + passphrase + "):"); toUse = keyPair.getPublic(); } System.out.println(getKeyAsString(toUse)); String encrypted = encrypt(toEncrypt, toUse); System.out.println("\nUN-ENCRYPTED STRING:"); System.out.println(toEncrypt); System.out.println("\nENCRYPTED STRING:"); System.out.println(encrypted); } else { System.out.println(method + " is not a known command"); } }
From source file:mitm.common.security.ca.handlers.ejbca.ws.EjbcaWSClient.java
public static void main(String args[]) throws Exception { BasicConfigurator.configure();/* ww w . j a v a 2s .c om*/ 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: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 ww w. j a v a 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:testSig.java
public static void main(String[] args) { /* Test generating and verifying a DSA signature */ try {/*from w w w . j a va 2 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:ai.susi.tools.JsonSignature.java
public static void main(String[] args) throws Exception { KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA"); keyGen.initialize(2048);// w w w. jav a2s . co m KeyPair keyPair = keyGen.genKeyPair(); String jsonString = "{\n" + " \"_id\": \"57b44e738d9af9fa2df13b27\",\n" + " \"index\": 0,\n" + " \"guid\": \"13af6838-08c8-4709-8dff-5ecb20bbaaa7\",\n" + " \"isActive\": false,\n" + " \"balance\": \"$2,092.08\",\n" + " \"picture\": \"http://placehold.it/32x32\",\n" + " \"age\": 22,\n" + " \"eyeColor\": \"blue\",\n" + " \"name\": \"Wyatt Jefferson\",\n" + " \"gender\": \"male\",\n" + " \"company\": \"GEEKFARM\",\n" + " \"email\": \"wyattjefferson@geekfarm.com\",\n" + " \"phone\": \"+1 (855) 405-2375\",\n" + " \"address\": \"506 Court Street, Gambrills, Minnesota, 8953\",\n" + " \"about\": \"Ea sunt quis non occaecat aliquip sint eiusmod. Aliquip id non ut sunt est laboris proident reprehenderit incididunt velit. Quis deserunt dolore aliqua voluptate magna laborum minim. Pariatur voluptate ad consequat culpa sit veniam eiusmod et ex ipsum.\\r\\n\",\n" + " \"registered\": \"2015-08-08T03:21:53 -02:00\",\n" + " \"latitude\": -39.880621,\n" + " \"longitude\": 44.053688,\n" + " \"tags\": [\n" + " \"non\",\n" + " \"cupidatat\",\n" + " \"in\",\n" + " \"Lorem\",\n" + " \"tempor\",\n" + " \"fugiat\",\n" + " \"aliqua\"\n" + " ],\n" + " \"friends\": [\n" + " {\n" + " \"id\": 0,\n" + " \"name\": \"Gail Blevins\"\n" + " },\n" + " {\n" + " \"id\": 1,\n" + " \"name\": \"Tricia Francis\"\n" + " },\n" + " {\n" + " \"id\": 2,\n" + " \"name\": \"Letitia Winters\"\n" + " }\n" + " ],\n" + " \"greeting\": \"Hello, Wyatt Jefferson! You have 1 unread messages.\",\n" + " \"favoriteFruit\": \"strawberry\"\n" + " }"; String jsonStringSimple = "{\n" + " \"_id\": \"57b44e738d9af9fa2df13b27\",\n" + " \"index\": 0,\n" + " \"guid\": \"13af6838-08c8-4709-8dff-5ecb20bbaaa7\",\n" + " \"isActive\": false,\n" + " \"balance\": \"$2,092.08\",\n" + " \"picture\": \"http://placehold.it/32x32\",\n" + " \"age\": 22,\n" + " \"eyeColor\": \"blue\",\n" + " \"name\": \"Wyatt Jefferson\",\n" + " \"gender\": \"male\",\n" + " \"company\": \"GEEKFARM\",\n" + " \"email\": \"wyattjefferson@geekfarm.com\",\n" + " \"phone\": \"+1 (855) 405-2375\",\n" + " \"address\": \"506 Court Street, Gambrills, Minnesota, 8953\",\n" + " \"about\": \"Ea sunt quis non occaecat aliquip sint eiusmod. Aliquip id non ut sunt est laboris proident reprehenderit incididunt velit. Quis deserunt dolore aliqua voluptate magna laborum minim. Pariatur voluptate ad consequat culpa sit veniam eiusmod et ex ipsum.\\r\\n\",\n" + " \"registered\": \"2015-08-08T03:21:53 -02:00\",\n" + " \"latitude\": -39.880621,\n" + " \"longitude\": 44.053688,\n" + " }"; JSONObject randomObj = new JSONObject(jsonString); JSONObject tmp = new JSONObject(jsonStringSimple); Map<String, byte[]> randomObj2 = new HashMap<String, byte[]>(); for (String key : tmp.keySet()) { Object value = tmp.get(key); randomObj2.put(key, value.toString().getBytes()); } addSignature(randomObj, keyPair.getPrivate()); addSignature(randomObj2, keyPair.getPrivate()); if (hasSignature(randomObj)) System.out.println("Verify 1: " + verify(randomObj, keyPair.getPublic())); if (hasSignature(randomObj2)) System.out.println("Verify 2: " + verify(randomObj, keyPair.getPublic())); removeSignature(randomObj); removeSignature(randomObj2); }
From source file:com.floreantpos.license.FiveStarPOSKeyGenerator.java
public static void createKeys(String publicKeyUri, String privateKeyUri) throws NoSuchAlgorithmException, IOException { KeyPairGenerator keyGen = KeyPairGenerator.getInstance("DSA"); keyGen.initialize(1024, new SecureRandom()); KeyPair keyPair = keyGen.generateKeyPair(); IOUtils.write(keyPair.getPublic().getEncoded(), new FileOutputStream(publicKeyUri)); IOUtils.write(keyPair.getPrivate().getEncoded(), new FileOutputStream(privateKeyUri)); }