@Test public void createSimpleContainer() throws Exception { URL trdm090Resource = CreateContainerTest.class.getClassLoader().getResource(TRDM090_SUBMIT_TENDER_SAMPLE_XML); assertNotNull( trdm090Resource, "Unable to locate " + TRDM090_SUBMIT_TENDER_SAMPLE_XML + " in class path"); File trdm090SampleFile = new File(trdm090Resource.toURI()); URL keystoreUrl = CreateContainerTest.class.getClassLoader().getResource(VEFA_INNLEVERING_JKS); assertNotNull(keystoreUrl, "Unable to locate the keystore " + VEFA_INNLEVERING_JKS); File keyStoreFile = new File(keystoreUrl.toURI()); assertTrue(keyStoreFile.canRead(), "Keystore " + VEFA_INNLEVERING_JKS + " not readable"); File archiveOutputFile = new File(System.getProperty("java.io.tmpdir"), "vefa-sample.asice"); AsicWriterFactory asicWriterFactory = AsicWriterFactory.newFactory(); asicWriterFactory .newContainer(archiveOutputFile) .add(trdm090SampleFile) .setRootEntryName(trdm090SampleFile.getName()) .sign( keyStoreFile, KeyStoreUtil.getKeyStorePassword(), KeyStoreUtil.getPrivateKeyPassord()); log.debug("Created ASiC archive in " + archiveOutputFile); }
public void testRandomString() throws Exception { SecureRandom rng = MiscTestUtil.getSecureRandom(); String r10 = KeyStoreUtil.randomString(10, rng); String r1024 = KeyStoreUtil.randomString(1024, rng); assertEquals(10, r10.length()); assertEquals(1024, r1024.length()); assertCharsBetween(32, 126, r10); assertCharsBetween(32, 126, r1024); assertNotEquals(r1024, KeyStoreUtil.randomString(1024, rng)); }
public void testSendingSameStreamDefinitions() throws MalformedURLException, AuthenticationException, TransportException, AgentException, UndefinedEventTypeException, DifferentStreamDefinitionAlreadyDefinedException, InterruptedException, DataBridgeException, MalformedStreamDefinitionException, StreamDefinitionException { TestServer testServer = new TestServer(); testServer.start(7614); KeyStoreUtil.setTrustStoreParams(); Thread.sleep(2000); // according to the convention the authentication port will be 7611+100= 7711 and its host will // be the same DataPublisher dataPublisher = new DataPublisher("tcp://localhost:7614", "admin", "admin"); String id1 = dataPublisher.defineStream( "{" + " 'name':'org.wso2.esb.MediatorStatistics'," + " 'version':'2.3.0'," + " 'nickName': 'Stock Quote Information'," + " 'description': 'Some Desc'," + " 'tags':['foo', 'bar']," + " 'metaData':[" + " {'name':'ipAdd','type':'STRING'}" + " ]," + " 'payloadData':[" + " {'name':'symbol','type':'STRING'}," + " {'name':'price','type':'DOUBLE'}," + " {'name':'volume','type':'INT'}," + " {'name':'max','type':'DOUBLE'}," + " {'name':'min','type':'Double'}" + " ]" + "}"); String id2 = dataPublisher.defineStream( "{" + " 'name':'org.wso2.esb.MediatorStatistics'," + " 'version':'2.3.0'," + " 'nickName': 'Stock Quote Information'," + " 'description': 'Some Desc'," + " 'tags':['foo', 'bar']," + " 'metaData':[" + " {'name':'ipAdd','type':'STRING'}" + " ]," + " 'payloadData':[" + " {'name':'symbol','type':'STRING'}," + " {'name':'price','type':'DOUBLE'}," + " {'name':'volume','type':'INT'}," + " {'name':'max','type':'DOUBLE'}," + " {'name':'min','type':'Double'}" + " ]" + "}"); Assert.assertEquals(id1, id2); // In this case correlation data is null dataPublisher.publish( id1, new Object[] {"127.0.0.1"}, null, new Object[] {"IBM", 96.8, 300, 120.6, 70.4}); dataPublisher.stop(); testServer.stop(); }
public void testSendingTwoDifferentStreamDefinitionsWithSameStreamId() throws MalformedURLException, AuthenticationException, TransportException, AgentException, UndefinedEventTypeException, InterruptedException, DataBridgeException, MalformedStreamDefinitionException, StreamDefinitionException, DifferentStreamDefinitionAlreadyDefinedException { TestServer testServer = new TestServer(); testServer.start(7617); KeyStoreUtil.setTrustStoreParams(); Thread.sleep(2000); // according to the convention the authentication port will be 7611+100= 7711 and its host will // be the same DataPublisher dataPublisher = new DataPublisher("tcp://localhost:7617", "admin", "admin"); dataPublisher.defineStream( "{" + " 'name':'org.wso2.esb.MediatorStatistics3'," + " 'version':'2.3.0'," + " 'nickName': 'Stock Quote Information'," + " 'description': 'Some Desc'," + " 'tags':['foo', 'bar']," + " 'metaData':[" + " {'name':'ipAdd','type':'STRING'}" + " ]," + " 'payloadData':[" + " {'name':'symbol','type':'STRING'}," + " {'name':'price','type':'DOUBLE'}," + " {'name':'volume','type':'INT'}," + " {'name':'max','type':'DOUBLE'}," + " {'name':'min','type':'Double'}" + " ]" + "}"); Boolean exceptionOccurred = false; try { dataPublisher.defineStream( "{" + " 'name':'org.wso2.esb.MediatorStatistics3'," + " 'version':'2.3.0'," + " 'nickName': 'Stock Quote Information'," + " 'description': 'Some Desc'," + " 'tags':['foo', 'bar']," + " 'metaData':[" + " {'name':'ipAdd','type':'STRING'}" + " ]," + " 'payloadData':[" + " {'name':'symbol','type':'STRING'}," + " {'name':'price','type':'DOUBLE'}," + " {'name':'volume','type':'INT'}," + " {'name':'min','type':'Double'}" + " ]" + "}"); } catch (DifferentStreamDefinitionAlreadyDefinedException e) { exceptionOccurred = true; } Assert.assertTrue(exceptionOccurred); dataPublisher.stop(); testServer.stop(); }
public void testDefaults() throws Exception { Properties p = initProps(); KeyStore ks = KeyStoreUtil.createKeyStore(p); List aliases = ListUtil.fromIterator(new EnumerationIterator(ks.aliases())); assertIsomorphic(SetUtil.set("mykey", "mycert"), SetUtil.theSet(aliases)); assertNotNull(ks.getCertificate("mycert")); assertNull(ks.getCertificate("foocert")); assertEquals("JCEKS", ks.getType()); }
@Test public void testBoth() throws CertificateException, NoSuchAlgorithmException, KeyStoreException, IOException, InvalidKeySpecException, InvalidKeyException, NoSuchProviderException, SignatureException { File caPem = getTempFile("ca/cert.pem"); File serverPem = getTempFile("server/cert.pem"); File keyPem = getTempFile("server/key.pem"); KeyStore keystore = createKeyStore(); KeyStoreUtil.updateWithCaPem(keystore, caPem); KeyStoreUtil.updateWithServerPems(keystore, serverPem, keyPem, "RSA", new char[0]); X509Certificate caCert = (X509Certificate) keystore.getCertificate(CA_ALIAS); X509Certificate serverCert = (X509Certificate) keystore.getCertificate(SERVER_ALIAS); // Check that server cert is signed by ca serverCert.verify(caCert.getPublicKey()); }
public void testCreateSharedPLNKeyStores() throws Exception { List<String> hosts = ListUtil.list("host1", "host2.foo.bar", "host3"); List<String> hosts2 = ListUtil.list("host3", "host4"); File dir = getTempDir(); File pub = new File(dir, "pub.ks"); KeyStoreUtil.createSharedPLNKeyStores( dir, hosts, pub, "pubpass", MiscTestUtil.getSecureRandom()); assertPubKs(pub, "pubpass", hosts); for (String host : hosts) { assertPrivateKs( new File(dir, host + ".jceks"), StringUtil.fromFile(new File(dir, host + ".pass")), host); } KeyStore pubks1 = loadKeyStore("jceks", new File(dir, "pub.ks"), "pubpass"); Certificate host1cert1 = pubks1.getCertificate("host1.crt"); Certificate host3cert1 = pubks1.getCertificate("host3.crt"); String host1priv1 = StringUtil.fromFile(new File(dir, "host1.jceks")); String host3priv1 = StringUtil.fromFile(new File(dir, "host3.jceks")); // Now add host4 and generate a new key for host3 KeyStoreUtil.createSharedPLNKeyStores( dir, hosts2, pub, "pubpass", MiscTestUtil.getSecureRandom()); List<String> both = ListUtils.sum(hosts, hosts2); assertPubKs(pub, "pubpass", both); for (String host : both) { assertPrivateKs( new File(dir, host + ".jceks"), StringUtil.fromFile(new File(dir, host + ".pass")), host); } KeyStore pubks2 = loadKeyStore("jceks", new File(dir, "pub.ks"), "pubpass"); // host1 should have the same cert, host3 not Certificate host1cert2 = pubks2.getCertificate("host1.crt"); Certificate host3cert2 = pubks2.getCertificate("host3.crt"); assertEquals(host1cert1, host1cert2); assertNotEquals(host3cert1, host3cert2); // host1's private key file should be the same, host3's not String host1priv2 = StringUtil.fromFile(new File(dir, "host1.jceks")); String host3priv2 = StringUtil.fromFile(new File(dir, "host3.jceks")); assertEquals(host1priv1, host1priv2); assertNotEquals(host3priv1, host3priv2); }
public void start(int receiverPort) throws DataBridgeException { KeyStoreUtil.setKeyStoreParams(); DataBridge databridge = new DataBridge( new AuthenticationHandler() { @Override public boolean authenticate(String userName, String password) { return true; // allays authenticate to true } @Override public String getTenantDomain(String userName) { return "admin"; } }, new InMemoryStreamDefinitionStore()); thriftDataReceiver = new ThriftDataReceiver(receiverPort, databridge); databridge.subscribe( new AgentCallback() { int totalSize = 0; public void definedStream(StreamDefinition streamDefinition, Credentials credentials) { log.info("Added StreamDefinition " + streamDefinition); } @Override public void removeStream(StreamDefinition streamDefinition, Credentials credentials) { log.info("Removed StreamDefinition " + streamDefinition); } @Override public void receive(List<Event> eventList, Credentials credentials) { log.info( "eventListSize=" + eventList.size() + " eventList " + eventList + " for username " + credentials.getUsername()); eventReceived = true; stop(); } }); try { String address = HostAddressFinder.findAddress("localhost"); log.info("Test Server starting on " + address); thriftDataReceiver.start(address); log.info("Test Server Started"); } catch (SocketException e) { log.error("Test Server not started !", e); } }
@Test public void testSelfSignedCertificate() throws Exception { KeyStore keystore = createKeyStore(); KeyStoreUtil.updateWithSelfSignedServerCertificate(keystore); X509Certificate cert = (X509Certificate) keystore.getCertificate("jolokia-agent"); assertNotNull(cert); assertEquals( cert.getSubjectDN().getName(), "CN=Jolokia Agent " + Version.getAgentVersion() + ", OU=JVM, O=jolokia.org, L=Pegnitz, ST=Franconia, C=DE"); assertEquals(cert.getSubjectDN(), cert.getIssuerDN()); }
@Test public void testInvalid() throws IOException, CertificateException, NoSuchAlgorithmException, KeyStoreException, InvalidKeySpecException { for (String file : new String[] {"invalid/base64.pem", "invalid/begin.pem", "invalid/end.pem"}) { File invalidPem = getTempFile(file); KeyStore keystore = createKeyStore(); try { KeyStoreUtil.updateWithCaPem(keystore, invalidPem); fail(); } catch (Exception exp) { } try { KeyStoreUtil.updateWithServerPems( keystore, getTempFile("server/cert.pem"), invalidPem, "RSA", new char[0]); fail(); } catch (Exception exp) { } } }
public void testCreateIllProv() throws Exception { File dir = getTempDir(); File file = new File(dir, "test.ks"); Properties p = initProps(); p.put(KeyStoreUtil.PROP_KEYSTORE_FILE, file.toString()); p.put(KeyStoreUtil.PROP_KEYSTORE_TYPE, "JKS"); p.put(KeyStoreUtil.PROP_KEYSTORE_PROVIDER, "not_a_provider"); assertFalse(file.exists()); try { KeyStoreUtil.createKeyStore(p); fail("Illegal keystore type should throw"); } catch (NoSuchProviderException e) { } assertFalse(file.exists()); }
public void testStore() throws Exception { File dir = getTempDir(); File file = new File(dir, "test.ks"); Properties p = initProps(); p.put(KeyStoreUtil.PROP_KEYSTORE_FILE, file.toString()); assertFalse(file.exists()); KeyStore ks = KeyStoreUtil.createKeyStore(p); assertTrue(file.exists()); KeyStore ks2 = loadKeyStore(ks.getType(), file, PASSWD); List aliases = ListUtil.fromIterator(new EnumerationIterator(ks2.aliases())); assertIsomorphic(SetUtil.set("mykey", "mycert"), SetUtil.theSet(aliases)); assertNotNull(ks2.getCertificate("mycert")); assertNull(ks2.getCertificate("foocert")); assertEquals("JCEKS", ks2.getType()); }
@Test public void testTrustStore() throws KeyStoreException, CertificateException, NoSuchAlgorithmException, IOException { File caPem = getTempFile("ca/cert.pem"); KeyStore keystore = createKeyStore(); KeyStoreUtil.updateWithCaPem(keystore, caPem); Enumeration<String> aliases = keystore.aliases(); String alias = aliases.nextElement(); assertFalse(aliases.hasMoreElements()); assertTrue(alias.contains("ca.test.jolokia.org")); X509Certificate cert = (X509Certificate) keystore.getCertificate(alias); cert.checkValidity(); assertTrue(cert.getSubjectDN().getName().contains(CA_CERT_SUBJECT_DN_CN)); RSAPublicKey key = (RSAPublicKey) cert.getPublicKey(); assertEquals(key.getAlgorithm(), "RSA"); }
public static void main(String[] args) throws KeyStoreException, NoSuchAlgorithmException, CertificateException, IOException, NoSuchPaddingException, IllegalBlockSizeException, BadPaddingException, InvalidKeyException, UnrecoverableKeyException, NoSuchProviderException, SignatureException { /** At the client side */ KeyStoreUtil keyStoreUtil = new KeyStoreUtil(); // Generate Symmetric key byte[] symmetrickey = keyStoreUtil.generateSessionKey(); // Encrypt data by symmetric key String data = "ABC"; System.out.println("Data : " + data); String encryptedData = keyStoreUtil.encryptWithAESKey(data, symmetrickey); System.out.println("encryptedData : " + encryptedData); // Encrypt symmetric key using trustore String encryptedKey = keyStoreUtil.encryptKey(symmetrickey, "mykey"); System.out.println("encryptedKey : " + encryptedKey); // Generate the signature of symmetric key byte[] signedEncryptedKey = keyStoreUtil.signData(Base64.decodeBase64(encryptedKey)); String signatureOfKey = Base64.encodeBase64String(signedEncryptedKey); System.out.println("Signed Ecrypted Key : " + signatureOfKey); /** At the receiver */ // Verify signature keyStoreUtil.verifySignature(Base64.decodeBase64(encryptedKey), signedEncryptedKey); // Decrypt symmteric key using keystore String decryptedKey = keyStoreUtil.decryptKey(encryptedKey, "mykey"); System.out.println("decryptedKey : " + decryptedKey); // Decrypt data using decrypted symetric key System.out.println( "Decrypted Data : " + keyStoreUtil.decryptWithAESKey(encryptedData, decryptedKey)); }
@Test public void testKeyStore() throws IOException, CertificateException, NoSuchAlgorithmException, KeyStoreException, InvalidKeySpecException, UnrecoverableKeyException { File serverPem = getTempFile("server/cert.pem"); File keyPem = getTempFile("server/key.pem"); KeyStore keystore = createKeyStore(); KeyStoreUtil.updateWithServerPems(keystore, serverPem, keyPem, "RSA", new char[0]); Enumeration<String> aliases = keystore.aliases(); String alias = aliases.nextElement(); assertFalse(aliases.hasMoreElements()); assertTrue(alias.contains("server")); X509Certificate cert = (X509Certificate) keystore.getCertificate(alias); cert.checkValidity(); assertEquals(cert.getSubjectDN().getName(), SERVER_CERT_SUBJECT_DN); RSAPrivateCrtKey key = (RSAPrivateCrtKey) keystore.getKey(alias, new char[0]); assertEquals("RSA", key.getAlgorithm()); RSAPublicKey pubKey = (RSAPublicKey) cert.getPublicKey(); assertEquals("RSA", pubKey.getAlgorithm()); }
public static void main(String[] args) throws AgentException, MalformedStreamDefinitionException, StreamDefinitionException, DifferentStreamDefinitionAlreadyDefinedException, MalformedURLException, AuthenticationException, NoStreamDefinitionExistException, TransportException, SocketException, org.wso2.carbon.databridge.commons.exception.AuthenticationException { System.out.println("Starting Activity Monitoring Sample"); KeyStoreUtil.setTrustStoreParams(); String host = args[0]; String port = args[1]; String username = args[2]; String password = args[3]; int events = Integer.parseInt(args[4]); // create data publisher DataPublisher dataPublisher = new DataPublisher("tcp://" + host + ":" + port, username, password); String streamId = null; try { streamId = dataPublisher.findStream(ACTIVITY_MONITORING_STREAM, VERSION); System.out.println("Stream already defined"); } catch (NoStreamDefinitionExistException e) { streamId = dataPublisher.defineStream( "{" + " 'name':'" + ACTIVITY_MONITORING_STREAM + "'," + " 'version':'" + VERSION + "'," + " 'nickName': 'Activity_Monitoring'," + " 'description': 'A sample for Activity Monitoring'," + " 'metaData':[" + " {'name':'character_set_encoding','type':'STRING'}," + " {'name':'host','type':'STRING'}," + " {'name':'http_method','type':'STRING'}," + " {'name':'message_type','type':'STRING'}," + " {'name':'remote_address','type':'STRING'}," + " {'name':'remote_host','type':'STRING'}," + " {'name':'service_prefix','type':'STRING'}," + " {'name':'tenant_id','type':'INT'}," + " {'name':'transport_in_url','type':'STRING'}" + " ]," + " 'correlationData':[" + " {'name':'bam_activity_id','type':'STRING'}" + " ]," + " 'payloadData':[" + " {'name':'soap_body','type':'STRING'}," + " {'name':'soap_header','type':'STRING'}," + " {'name':'message_direction','type':'STRING'}," + " {'name':'message_id','type':'STRING'}," + " {'name':'operation_name','type':'STRING'}," + " {'name':'service_name','type':'STRING'}," + " {'name':'timestamp','type':'LONG'}" + " ]" + "}"); // //Define event stream } // Publish event for a valid stream if (!streamId.isEmpty()) { System.out.println("Stream ID: " + streamId); for (int i = 0; i < events; i++) { publishEvents(dataPublisher, streamId, i); System.out.println("Events published : " + (i + 1)); } try { Thread.sleep(2000); } catch (InterruptedException e) { } dataPublisher.stop(); } }