As we had a look at the Event Broker just recently, I was wondering which types of events were published at all. So I wrote a little plug-in to keep track of them:
Hover over an event to see the event properties (as far as .toString() handles them).
By default it subscribes to all events, but you may narrow it down by providing a Filter string.
Try it out for yourself and grab it from my update site:
http://codeandme.googlecode.com/svn/trunk/tools/com.codeandme.tools.releng.p2/update/
Wednesday, August 21, 2013
Event Broker Spy plug-in
Monday, August 5, 2013
Using the Event Broker without DI
The new EventBroker in e4 is a very handy tool to send events globally without the need to allow listeners to register. Listeners may subscribe to events on the event bus instead of finding an instance that supports addEventListener().
If you are running an E4 application you may directly inject the IEventBroker. If DI is not available you may consume the IEventBroker as a service, which works nicely for "old school" plug-ins that run within an e4 application.
Source code for this tutorial is available on googlecode as a single zip archive, as a Team Project Set or you can checkout the SVN projects directly.
Step 1: Creating an event publisher
Lets start with a fresh Plug-in Project named com.example.eventbroker. Then continue by creating a PublisherJob implementation:
To resolve IEventBroker you need to add a dependency to org.eclipse.e4.core.services. For the rest we additionally need org.eclipse.core.runtime and org.eclipse.ui.workbench.
The Job in the example will publish 2 events each second.
Step 2: Creating a subscriber
Create the Subscriber class:
e.getPropertyNames() may be used to retrieve the keys of the event data.
You need to add an additional dependency to org.eclipse.osgi.services to resolve EventHandler.
Step 3: Autostart our sample code
To run our little example we have to add an Activator:
Register the Activator in your plugin.xml and set Auto-Start to true for com.example.eventbroker in your launch configuration.
If you are running an E4 application you may directly inject the IEventBroker. If DI is not available you may consume the IEventBroker as a service, which works nicely for "old school" plug-ins that run within an e4 application.
Source code for this tutorial is available on googlecode as a single zip archive, as a Team Project Set or you can checkout the SVN projects directly.
Step 1: Creating an event publisher
Lets start with a fresh Plug-in Project named com.example.eventbroker. Then continue by creating a PublisherJob implementation:
package com.example.eventbroker;
import java.util.HashMap;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Status;
import org.eclipse.core.runtime.jobs.Job;
import org.eclipse.e4.core.services.events.IEventBroker;
import org.eclipse.ui.PlatformUI;
public class PublisherJob extends Job {
private static int mCounter = 0;
public PublisherJob() {
super("Publisher");
schedule();
}
@Override
protected IStatus run(IProgressMonitor monitor) {
Object service = PlatformUI.getWorkbench().getService(IEventBroker.class);
if (service instanceof IEventBroker) {
((IEventBroker) service).post("com/example/eventbroker/basic", new Object());
HashMap<String, Object> data = new HashMap<String, Object>();
data.put("Event origin", "unknown");
data.put("Event number", mCounter++);
((IEventBroker) service).post("com/example/eventbroker/advanced", data);
schedule(1000);
return Status.OK_STATUS;
}
return Status.OK_STATUS;
}
}
Each posted event contains a topic and optional event data. Topics use hierarchies separated by slashes. If the data parameter is a Map it will be directly used for the event. If it is something else it will be wrapped inside a Map. So if you want to transport more than a single object use a Map<String, Object> to encapsulate your data. To resolve IEventBroker you need to add a dependency to org.eclipse.e4.core.services. For the rest we additionally need org.eclipse.core.runtime and org.eclipse.ui.workbench.
The Job in the example will publish 2 events each second.
Step 2: Creating a subscriber
Create the Subscriber class:
package com.example.eventbroker;
import org.eclipse.e4.core.services.events.IEventBroker;
import org.eclipse.ui.PlatformUI;
import org.osgi.service.event.Event;
import org.osgi.service.event.EventHandler;
public class Subscriber implements EventHandler {
public Subscriber() {
Object service = PlatformUI.getWorkbench().getService(IEventBroker.class);
if (service instanceof IEventBroker)
((IEventBroker) service).subscribe("com/example/eventbroker/*", this);
}
@Override
public void handleEvent(Event e) {
System.out.println("-------------------------------------------");
System.out.println(e.getTopic());
for (String name: e.getPropertyNames())
System.out.println("\t" + name + ": " + e.getProperty(name));
}
}
The subscriber subscribes to dedicated topics. Wildcards (*) may be used to subscribe to event groups. Subscribing to "*" will create notifications on any event.e.getPropertyNames() may be used to retrieve the keys of the event data.
You need to add an additional dependency to org.eclipse.osgi.services to resolve EventHandler.
Step 3: Autostart our sample code
To run our little example we have to add an Activator:
package com.example.eventbroker;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Status;
import org.eclipse.core.runtime.jobs.Job;
import org.eclipse.e4.core.services.events.IEventBroker;
import org.eclipse.ui.PlatformUI;
import org.osgi.framework.BundleActivator;
import org.osgi.framework.BundleContext;
public class Activator implements BundleActivator {
public void start(BundleContext bundleContext) throws Exception {
Job job = new Job("Starting Publisher/Subscriber") {
@Override
protected IStatus run(IProgressMonitor monitor) {
if (PlatformUI.isWorkbenchRunning()) {
Object service = PlatformUI.getWorkbench().getService(IEventBroker.class);
if (service instanceof IEventBroker) {
// broker available, create publisher
new PublisherJob();
new Subscriber();
}
} else
// workbench not running yet, try again in 1 second
schedule(1000);
return Status.OK_STATUS;
}
};
job.schedule();
}
public void stop(BundleContext bundleContext) throws Exception {
}
}
Basically a job runs continuously until the workbench is up and running. Afterwards we look for the Broker and create publisher and listener.Register the Activator in your plugin.xml and set Auto-Start to true for com.example.eventbroker in your launch configuration.
Wednesday, July 31, 2013
Introducing EScript - scripting for your IDE
During the last years I was playing around with a scripting engine supporting JavaScript that is directly integrated in Eclipse. This engine is used as a basis for my RCPs to allow users to create their own workflow.
I thought this might come in handy for others too, so I raised bug 365133. In the meantime I was able to extend the framework and added other interpreters as well. Currently Rhino, JRuby and Jython are supported (some better, some worse).
Hoping to get feedback from the community (you!) I release this project into the wild. Check out the project homepage, or dive directly into the source at github.
"What can I do with such an engine?", you may ask.
At my company we use it to automate test equipment, create test patterns and accumulate test results. Therefore we need to commuinicate with lots of lab equipment like oscilloscopes, RFID readers and so on. As our work flows are very dynamic, we provide a script environment along with command sets to easily access these devices. Our users may then create their dedicated tests by implementing their own scripts.
By creating libraries (which are independent of the used interpreter!) you may extend the script languages with your own functionality. Find an example at the EScript homepage.
You may also access any class available in your IDE and directly call methods on it.
All source is available under EPL terms. Drop me a line if you find it useful or need some support.
Please be aware that despite the Rhino implementation is available for quite some time, other interpreters were added just recently. So be prepared for some surprises :)
I thought this might come in handy for others too, so I raised bug 365133. In the meantime I was able to extend the framework and added other interpreters as well. Currently Rhino, JRuby and Jython are supported (some better, some worse).
Hoping to get feedback from the community (you!) I release this project into the wild. Check out the project homepage, or dive directly into the source at github.
"What can I do with such an engine?", you may ask.
At my company we use it to automate test equipment, create test patterns and accumulate test results. Therefore we need to commuinicate with lots of lab equipment like oscilloscopes, RFID readers and so on. As our work flows are very dynamic, we provide a script environment along with command sets to easily access these devices. Our users may then create their dedicated tests by implementing their own scripts.
By creating libraries (which are independent of the used interpreter!) you may extend the script languages with your own functionality. Find an example at the EScript homepage.
You may also access any class available in your IDE and directly call methods on it.
All source is available under EPL terms. Drop me a line if you find it useful or need some support.
Please be aware that despite the Rhino implementation is available for quite some time, other interpreters were added just recently. So be prepared for some surprises :)
Posted by
Christian Pontesegger
at
12:56 PM
1 comments
Labels:
Eclipse,
JavaScript,
RCP,
Rhino,
Scripting
Wednesday, July 17, 2013
Tycho 10: Signing plugins and executables
Eclipse supports signed plugins and displays this information in its Installation Details. On Mac and Windows you might further want to sign your executable to get rid of potential warnings when launching your application. All this can be done automatically with tycho. To get a general overview how to build a product with tycho, see my previous tutorials on this topic:
Tycho Tutorials
For a list of all tycho related tutorials see Tycho Tutorials Overview
Source code for this tutorial is available on github as a single zip archive, as a Team Project Set or you can browse the files online.
Before we start signing stuff, we need a certificate. In our example, we will use a self-signed certificate, you will probably want to go for one from a certification authority.
Step 1: Creating a self signed certificate
There exist lots of tutorials out there, how to sign jar files with a self-signed certificate. I suggest you pick one and try to sign a jar file for test purposes. Here are the two commands needed to create the certificate, which can be executed in a shell:
The email address field seems to be necessary (thanks for the comment), see this message on stackoverflow
Step 2: Signing jar files with tycho
Signing will be done by the maven-jarsigner-plugin. Open the master pom located in com.codeandme.tycho.releng (see previous tutorials) and add following plugin section to it.
Step 3: Create a code signing certificate for windows
Creating a self-signed certificate for your windows executable is not very useful unless you add your CA (we will create this in a second) to the trusted root certificates on the target machines. So this might be valid for a setup in a closed environment but not when your software is downloaded from the internet. In the latter case you need to buy a certificate from one of the big CAs (see this thread for some cheap ones).
Nevertheless for our test purposes such a certificate will do, so lets create one following this description on stackoverflow. We need to install Windows SDK, so download and run the installer. On the Install Options page select Windows Native Code Development/Tools, we do not need anything else for signing. After the installer is done you should find signtool.exe in C:\Program Files\Microsoft SDKs\Windows\v7.1\Bin.
To create a code signing certificate, startup a command shell:
To verify that signing worked you can open the Properties dialog of your executable and examine Digital Signatures.
For signing our executable we need to run the external signtool.exe by using the exec-maven-plugin. Open com.example.tycho.releng.product/pom.xml and add a new plugin section with following content:
For MacOS this should work similar. To my knowledge you would just have to use another signing application.
Tycho Tutorials
For a list of all tycho related tutorials see Tycho Tutorials Overview
Source code for this tutorial is available on github as a single zip archive, as a Team Project Set or you can browse the files online.
Before we start signing stuff, we need a certificate. In our example, we will use a self-signed certificate, you will probably want to go for one from a certification authority.
Step 1: Creating a self signed certificate
There exist lots of tutorials out there, how to sign jar files with a self-signed certificate. I suggest you pick one and try to sign a jar file for test purposes. Here are the two commands needed to create the certificate, which can be executed in a shell:
$JAVA_HOME/bin/keytool -genkey -keyalg RSA -sigalg SHA1withRSA -keystore C:\userdata\workspaces\blog\com.codeandme.tycho.releng\sample.keystore -alias eve -dname "CN=Eve, OU=none, O=example, L=somewhere, ST=earth, C=ea, EMAILADDRESS=eve@example.com"
Enter keystore password: verystrong
Re-enter new password: verystrong
Enter key password for <eve>
(RETURN if same as keystore password): secret
Re-enter new password: secret
$JAVA_HOME/bin/keytool -selfcert -keystore C:\userdata\workspaces\blog\com.codeandme.tycho.releng\sample.keystore -alias eve
(I always preferred Eve over Alice and Bob...)The email address field seems to be necessary (thanks for the comment), see this message on stackoverflow
Step 2: Signing jar files with tycho
Signing will be done by the maven-jarsigner-plugin. Open the master pom located in com.codeandme.tycho.releng (see previous tutorials) and add following plugin section to it.
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-jarsigner-plugin</artifactId>
<version>1.2</version>
<configuration>
<keystore>${basedir}/../com.codeandme.tycho.releng/blog.keystore</keystore>
<storepass>verystrong</storepass>
<alias>eve</alias>
<keypass>secret</keypass>
</configuration>
<executions>
<execution>
<id>sign</id>
<goals>
<goal>sign</goal>
</goals>
</execution>
</executions>
</plugin>
Set your passwords and the path to your keystore and run your maven build. Congratulations, you have signed your jars successfully. Step 3: Create a code signing certificate for windows
Creating a self-signed certificate for your windows executable is not very useful unless you add your CA (we will create this in a second) to the trusted root certificates on the target machines. So this might be valid for a setup in a closed environment but not when your software is downloaded from the internet. In the latter case you need to buy a certificate from one of the big CAs (see this thread for some cheap ones).
Nevertheless for our test purposes such a certificate will do, so lets create one following this description on stackoverflow. We need to install Windows SDK, so download and run the installer. On the Install Options page select Windows Native Code Development/Tools, we do not need anything else for signing. After the installer is done you should find signtool.exe in C:\Program Files\Microsoft SDKs\Windows\v7.1\Bin.
To create a code signing certificate, startup a command shell:
"C:\Program Files\Microsoft SDKs\Windows\v7.1\Bin\makecert.exe" -r -pe -n "CN=Eve" -ss CA -sr CurrentUser -a sha256 -cy authority -sky signature -sv SampleCA.pvk SampleCA.cer "C:\Program Files\Microsoft SDKs\Windows\v7.1\Bin\makecert.exe" -pe -n "CN=Eve" -a sha256 -cy end -sky signature -ic SampleCA.cer -iv SampleCA.pvk -sv SampleSPC.pvk SampleSPC.cer "C:\Program Files\Microsoft SDKs\Windows\v7.1\Bin\pvk2pfx.exe" -pvk SampleCA.pvk -spc SampleCA.cer -pfx SampleCA.pfx "C:\Program Files\Microsoft SDKs\Windows\v7.1\Bin\signtool.exe" sign /v /f SampleCA.pfx /t http://timestamp.verisign.com/scripts/timstamp.dll Application.exe
- Line 1 creates a root CA. You will be asked for a Subject Key twice. This is the key for your CA. Lets use "verystrong".
- Line 2 creates a signing certificate using the root CA. The Subject Key is now the key for our signing certificate. So use a different one to that before (eg. "secret"). You will also be asked for an Issuer Signature, which refers to the Subject Key of step 1 ("verystrong").
- Line 3 converts our certificate into pfx format. Again you need the Subject Key of step 1 ("verystrong").
- Line 4 signs a fictional file Application.exe with our key.
To verify that signing worked you can open the Properties dialog of your executable and examine Digital Signatures.
For signing our executable we need to run the external signtool.exe by using the exec-maven-plugin. Open com.example.tycho.releng.product/pom.xml and add a new plugin section with following content:
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>exec-maven-plugin</artifactId>
<version>1.2.1</version>
<executions>
<execution>
<id>exec</id>
<phase>package</phase>
<goals>
<goal>exec</goal>
</goals>
</execution>
</executions>
<configuration>
<executable>C:\Program Files\Microsoft SDKs\Windows\v7.1\Bin\signtool.exe</executable>
<arguments>
<argument>sign</argument>
<argument>/v</argument>
<argument>/f</argument>
<argument>C:\UserData\Workspaces\Blog\om.codeandme.tycho.releng\SampleCA.pfx</argument>
<argument>/t</argument>
<argument>http://timestamp.verisign.com/scripts/timstamp.dll</argument>
<argument>${project.build.directory}\products\tycho.product\win32\win32\x86\eclipse.exe</argument>
</arguments>
</configuration>
</plugin>
Make sure you have no line breaks in your xml nodes! For MacOS this should work similar. To my knowledge you would just have to use another signing application.
Tuesday, July 2, 2013
Writing your own JCA extensions - a full cipher
So you have managed to create your own cipher. Great! Now lets go for the real thing and implement a cipher.
Basically ciphers are implemented similar to digests. But while digests can be used without any security restrictions, ciphers need to be signed when used with JCA. In more detail your cipher implementation must reside in a signed jar file. To sign you need a code signing certificate from Oracle. Application for such a certificate is free of charge, but will take approximately 2 weeks to be processed. You will not get it for fun either as you have to provide your use case.
For the exact procedure follow Oracles step by step guide. To follow the tutorial below I expect you to have your certificate ready. Otherwise you might do the coding but will not be able to use your provider afterwards.
Source code for this tutorial is available on googlecode as a single zip archive, as a Team Project Set or you can checkout the SVN projects directly.
Step 1: Create key classes
We wil create a Caesar cipher implementation. You could also do ROT13 with it. As ciphers are about encryption/decryption we need some keys. Our key class will be very simple as we just need to store an offset for shifting our letters later on.
Start by creating a new Java Project named com.example.jce.cipher. Then implement the key class com.example.jce.provider.CaesarKey:
Ciphers are implemented extending CipherSpi (as all JCA extensions extend a WhateverSpi class). Implement com.example.jce.cipher.CaesarCipher as follows:
Step 3: Create a JCE provider
As for the digest, we need to usa a provider to register our digest in the JRE. Create a new class com.example.jce.cipher.CaesarProvider:
For all the others: export the project as a JAR file and sign it using jarsigner along with your certificate. The commandline looks something like this:
Step 4: Using our provider
Create a new Java project com.example.jce.cipher.consumer. Create a subfolder libs and store your signed JAR file there. Then add this JAR to the Java Build Path.
Now everything is in place to use our cipher:
Further reading
If you intend to implement your own stuff you should have a look at these links:
Basically ciphers are implemented similar to digests. But while digests can be used without any security restrictions, ciphers need to be signed when used with JCA. In more detail your cipher implementation must reside in a signed jar file. To sign you need a code signing certificate from Oracle. Application for such a certificate is free of charge, but will take approximately 2 weeks to be processed. You will not get it for fun either as you have to provide your use case.
For the exact procedure follow Oracles step by step guide. To follow the tutorial below I expect you to have your certificate ready. Otherwise you might do the coding but will not be able to use your provider afterwards.
Source code for this tutorial is available on googlecode as a single zip archive, as a Team Project Set or you can checkout the SVN projects directly.
Step 1: Create key classes
We wil create a Caesar cipher implementation. You could also do ROT13 with it. As ciphers are about encryption/decryption we need some keys. Our key class will be very simple as we just need to store an offset for shifting our letters later on.
Start by creating a new Java Project named com.example.jce.cipher. Then implement the key class com.example.jce.provider.CaesarKey:
package com.example.jce.cipher;
import javax.crypto.SecretKey;
public class CaesarKey implements SecretKey {
private static final long serialVersionUID = -542084808194990775L;
private byte mValue;
public CaesarKey(byte value) {
// converts any value to [0, 26), even negative ones
mValue = (byte) (((value % 26) + 26) % 26);
}
@Override
public String getAlgorithm() {
return "Caesar";
}
@Override
public String getFormat() {
return getAlgorithm() + " format";
}
@Override
public byte[] getEncoded() {
return new byte[] { mValue };
}
}
You may also implement a key generator that creates random keys on demand. This is not mandatory for our example but may be useful sometimes. The generator is implemented in com.example.jce.cipher.CaesarkeyGenerator:package com.example.jce.cipher;
import java.security.InvalidAlgorithmParameterException;
import java.security.SecureRandom;
import java.security.spec.AlgorithmParameterSpec;
import javax.crypto.KeyGeneratorSpi;
import javax.crypto.SecretKey;
public class CaesarKeyGenerator extends KeyGeneratorSpi {
SecureRandom mRandomSource;
public void engineInit(SecureRandom sr) {
mRandomSource = sr;
}
public void engineInit(AlgorithmParameterSpec ap, SecureRandom sr) throws InvalidAlgorithmParameterException {
throw new InvalidAlgorithmParameterException("No parameters supported in this class");
}
public SecretKey engineGenerateKey() {
if (mRandomSource == null)
mRandomSource = new SecureRandom();
return new CaesarKey((byte) Math.abs(mRandomSource.nextInt()));
}
@Override
protected void engineInit(int arg0, SecureRandom sr) {
engineInit(sr);
}
}
Step 2: Implement the cipherCiphers are implemented extending CipherSpi (as all JCA extensions extend a WhateverSpi class). Implement com.example.jce.cipher.CaesarCipher as follows:
package com.example.jce.cipher;
import java.security.AlgorithmParameters;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.Key;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.spec.AlgorithmParameterSpec;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.CipherSpi;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.ShortBufferException;
public class CaesarCipher extends CipherSpi {
private Key mKey;
private int mOPMode;
@Override
protected byte[] engineDoFinal(byte[] input, int inputOffset, int inputLen) throws IllegalBlockSizeException, BadPaddingException {
return engineUpdate(input, inputOffset, inputLen);
}
@Override
protected int engineDoFinal(byte[] input, int inputOffset, int inputLen, byte[] output, int outputOffset) throws ShortBufferException,
IllegalBlockSizeException, BadPaddingException {
return engineUpdate(input, inputOffset, inputLen, output, outputOffset);
}
@Override
protected int engineGetBlockSize() {
return 1;
}
@Override
protected byte[] engineGetIV() {
return null;
}
@Override
protected int engineGetOutputSize(int inputLen) {
return 0;
}
@Override
protected AlgorithmParameters engineGetParameters() {
return null;
}
@Override
protected void engineInit(int opmode, Key key, SecureRandom random) throws InvalidKeyException {
mOPMode = opmode;
if (key instanceof CaesarKey)
mKey = key;
else
throw new InvalidKeyException("Caesar cipher needs a Caesar key");
}
@Override
protected void engineInit(int opmode, Key key, AlgorithmParameterSpec params, SecureRandom random) throws InvalidKeyException,
InvalidAlgorithmParameterException {
engineInit(opmode, key, random);
}
@Override
protected void engineInit(int opmode, Key key, AlgorithmParameters params, SecureRandom random) throws InvalidKeyException,
InvalidAlgorithmParameterException {
engineInit(opmode, key, random);
}
@Override
protected void engineSetMode(String mode) throws NoSuchAlgorithmException {
throw new NoSuchAlgorithmException();
}
@Override
protected void engineSetPadding(String pading) throws NoSuchPaddingException {
throw new NoSuchPaddingException();
}
@Override
protected byte[] engineUpdate(byte[] input, int inputOffset, int inputLen) {
byte[] output = new byte[inputLen];
try {
engineUpdate(input, inputOffset, inputLen, output, 0);
} catch (ShortBufferException e) {
// output buffer is always big enough
}
return output;
}
@Override
protected int engineUpdate(byte[] input, int inputOffset, int inputLen, byte[] output, int outputOffset) throws ShortBufferException {
if (output.length - outputOffset < inputLen)
throw new ShortBufferException("Buffer too short to hold encrypted data");
for (int index = inputOffset; index < inputOffset + inputLen; index++)
output[outputOffset + index - inputOffset] = twistCharacter(input[index], getKey());
return inputLen;
}
private byte getKey() {
// calculate key depending on encryption/decryption
if (mOPMode == Cipher.ENCRYPT_MODE)
return mKey.getEncoded()[0];
// decode using inverse key
return (byte) (26 - mKey.getEncoded()[0]);
}
private byte twistCharacter(byte data, byte key) {
if (Character.isLetter(data)) {
// only operate on characters, leave everything else as-is
if (Character.isLowerCase(data))
return (byte) (((data - 'a' + key) % 26) + 'a');
else
return (byte) (((data - 'A' + key) % 26) + 'A');
}
return data;
}
@Override
protected int engineGetKeySize(Key key) throws InvalidKeyException {
if (key instanceof CaesarKey)
return 1;
throw new InvalidKeyException("Caesar cipher needs a Caesar key");
}
}
This is a straight forward implementation that will encode characters only. Everything else like digits or punctuation will remain unchanged.
Step 3: Create a JCE provider
As for the digest, we need to usa a provider to register our digest in the JRE. Create a new class com.example.jce.cipher.CaesarProvider:
package com.example.jce.cipher;
import java.security.Provider;
public class CaesarProvider extends Provider {
private static final long serialVersionUID = -67123468605911408L;
public CaesarProvider() {
super("Caesar Cipher", 1.0, "Caesar cipher v1.0");
put("KeyGenerator.Caesar", CaesarKeyGenerator.class.getName());
put("Cipher.Caesar", CaesarCipher.class.getName());
}
}
At this point we need the certificate requested from Oracle, because a cipher class needs to be nested in a signed jar file. If you do not have such a certificate your quest ends here...For all the others: export the project as a JAR file and sign it using jarsigner along with your certificate. The commandline looks something like this:
jarsigner -keystore <store location> -storepass <store master password> <JAR file> <keystore alias>
Step 4: Using our provider
Create a new Java project com.example.jce.cipher.consumer. Create a subfolder libs and store your signed JAR file there. Then add this JAR to the Java Build Path.
Now everything is in place to use our cipher:
public static void main(String[] args) {
// adding provider dynamically
Security.addProvider(new CaesarProvider());
try {
String message = "Hello World";
Cipher c = Cipher.getInstance("Caesar");
SecretKey key = new CaesarKey((byte) 2);
System.out.println("Message: " + message);
c.init(Cipher.ENCRYPT_MODE, key);
byte[] encrypted = c.doFinal(message.getBytes());
System.out.println("Encrypted: " + new String(encrypted));
c.init(Cipher.DECRYPT_MODE, key);
byte[] decrypted = c.doFinal(encrypted);
System.out.println("Decrypted: " + new String(decrypted));
} catch (Exception e) {
e.printStackTrace();
}
}
Further reading
If you intend to implement your own stuff you should have a look at these links:
- Java Cryptography Architecture
Overview of the JCA framework (Oracle) - How to implement a provider
Detailed step by step guide how to implement your own provider (Oracle) - Java security
Detailed description of the JCA framework with examples (O' Reilly)
Wednesday, June 26, 2013
Writing your own JCA extensions - a simple digest
When dealing with cryptographic algorithms in Java you should use the Java Cryptography Architecture (JCA). It is part of Java SE and provides support for several different algorithms like DES or AES. Even more algorithms are supported by BouncyCastle.
But what if you need to implement your own digest or cipher? JCE allows to add your own cryptographic provider to the framework, which is what we will do in this tutorial.
Source code for this tutorial is available on googlecode as a single zip archive, as a Team Project Set or you can checkout the SVN projects directly.
Step 1: Create a digest implementation
We will implement a simple digest that will XOR all bytes of a message and therefore return a 1 byte checksum.
Start by creating a new Java Project named com.example.jce.provider. To implement a digest we need to extend MessageDigestSpi. Implement com.example.jce.provider.XORDigest as follows:
To register our digest in the JRE we need to use a provider. This provider is used by the JCE as an entry point to locate our Digest class. Create a new class com.example.jce.provider.CryptoProvider:
Step 3: Using our provider
Lets see our provider in action:
But what if you need to implement your own digest or cipher? JCE allows to add your own cryptographic provider to the framework, which is what we will do in this tutorial.
Source code for this tutorial is available on googlecode as a single zip archive, as a Team Project Set or you can checkout the SVN projects directly.
Step 1: Create a digest implementation
We will implement a simple digest that will XOR all bytes of a message and therefore return a 1 byte checksum.
Start by creating a new Java Project named com.example.jce.provider. To implement a digest we need to extend MessageDigestSpi. Implement com.example.jce.provider.XORDigest as follows:
package com.example.jce.provider;
import java.security.MessageDigestSpi;
public class XORDigest extends MessageDigestSpi {
private byte mChecksum = 0;
public XORDigest() {
}
@Override
protected void engineUpdate(byte input) {
mChecksum ^= input;
}
@Override
protected void engineUpdate(byte[] input, int offset, int len) {
for (int index = offset; index < offset + len; index++)
engineUpdate(input[index]);
}
@Override
protected byte[] engineDigest() {
return new byte[] { mChecksum };
}
@Override
protected void engineReset() {
mChecksum = 0;
}
}
Step 2: Create a JCE providerTo register our digest in the JRE we need to use a provider. This provider is used by the JCE as an entry point to locate our Digest class. Create a new class com.example.jce.provider.CryptoProvider:
package com.example.jce.provider;
import java.security.Provider;
public class CryptoProvider extends Provider {
private static final long serialVersionUID = -67123468605911408L;
public CryptoProvider() {
super("SimpleCrypto", 1.0, "XOR digest v1.0");
put("MessageDigest.XOR", XORDigest.class.getName());
}
}
Finally we need to register this provider in our runtime. There are several ways to do this, here we will use the dynamic approach as we do not want to alter our JRE install folder. Registration is handled by the Security class:
Security.addProvider(new CryptoProvider());
Step 3: Using our provider
Lets see our provider in action:
public static void main(String[] args) {
Security.addProvider(new CryptoProvider());
try {
MessageDigest digest = MessageDigest.getInstance("XOR");
byte[] checksum = digest.digest(new byte[] { 0x01, 0x23, 0x45 });
System.out.println("Checksum: 0x" + Integer.toHexString(checksum[0]));
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
}
First we are registering our provider as explained in step 2. Afterwards we create a new digest and feed some data to it. The checksum you get should be 0x67.
Thursday, June 13, 2013
Using ANTLR in your RCP
ANTLR is a parser generator widely used to create DSLs and all kinds of parsers for special purposes. In this tutorial I will show how to create a simple parser and how to implement it into an RCP.
Source code for this tutorial is available on googlecode as a single zip archive, as a Team Project Set or you can checkout the SVN projects directly.
Prerequisites
We need some stuff from the ANTLR download page. Get Complete ANTLR 4.0 Java binaries jar and ANTLR 4.0 Java runtime binaries jar from there. The full package includes the build tool for grammars, the runtime binaries are needed to execute a parser in our RCP later on.
Step 1: Create a simple grammar
As this tutorial is not about ANTLR itself, but its integration into an RCP, we will use a very simple grammar to parse CSV files (actually just a single line of separated integers).
Currently there seems to be no eclipse support for ANTLRv4. To write grammars you could use ANTLRWorks 2 or write it directly in an editor of your choice.
Create a new Plug-in Project named com.example.antlr.parser. Afterwards create a grammar file CSV.g4 in the project root and add following content:
To compile our grammar file we need the Complete ANTLR package we downloaded earlier and a simple script. As there is no native eclipse builder available, we will use an external build script.
Create a new folder build and copy antlr-4.0-complete.jar to it. Afterwards create a new file build.bat with following content:
You may launch this batch file from the External Tools located in the Run menu. The launcher is available in the source repository in the build folder.
Step 3: Add ANTLR runtime
The created files show lots of error markers because we have no runtime available yet. Create a new Plug-in from Existing JAR Archives and add antlr-runtime-4.0.jar to it. Name the project org.antlr.v4.runtime and add it as a dependency to com.example.antlr.parser. All the error markers should be gone by now.
ANTLR comes with a BSD like license so you have to check if this fits to your application needs. According to this wiki entry it seems that it fits to EPL.
Step 4: Implement the parser
To run the parser we need 2 more classes. Lets start with com.example.antlr.CSVVisitor
Source code for this tutorial is available on googlecode as a single zip archive, as a Team Project Set or you can checkout the SVN projects directly.
Prerequisites
We need some stuff from the ANTLR download page. Get Complete ANTLR 4.0 Java binaries jar and ANTLR 4.0 Java runtime binaries jar from there. The full package includes the build tool for grammars, the runtime binaries are needed to execute a parser in our RCP later on.
Step 1: Create a simple grammar
As this tutorial is not about ANTLR itself, but its integration into an RCP, we will use a very simple grammar to parse CSV files (actually just a single line of separated integers).
Currently there seems to be no eclipse support for ANTLRv4. To write grammars you could use ANTLRWorks 2 or write it directly in an editor of your choice.
Create a new Plug-in Project named com.example.antlr.parser. Afterwards create a grammar file CSV.g4 in the project root and add following content:
grammar CSV; csv: NUMBER (DELIMITER NUMBER)*; DELIMITER: ','; NUMBER: DIGIT+; fragment DIGIT: [0-9];Step 2: Compile grammar
To compile our grammar file we need the Complete ANTLR package we downloaded earlier and a simple script. As there is no native eclipse builder available, we will use an external build script.
Create a new folder build and copy antlr-4.0-complete.jar to it. Afterwards create a new file build.bat with following content:
"C:\Program Files\Java\jdk1.7.0_04\bin\java.exe" -cp antlr-4.0-complete.jar org.antlr.v4.Tool -visitor -package com.example.antlr.gen -o ..\src\com\example\antlr\gen\foo ..\CSV.g4Extend this to your needs, port it to ANT or integrate it in a maven build (there seems to exist a maven target for ANTLRv4). It seems that the -o parameter needs some dummy folder name at the end. At least for me the very last path entry was skipped by the build tool.
You may launch this batch file from the External Tools located in the Run menu. The launcher is available in the source repository in the build folder.
Step 3: Add ANTLR runtime
The created files show lots of error markers because we have no runtime available yet. Create a new Plug-in from Existing JAR Archives and add antlr-runtime-4.0.jar to it. Name the project org.antlr.v4.runtime and add it as a dependency to com.example.antlr.parser. All the error markers should be gone by now.
ANTLR comes with a BSD like license so you have to check if this fits to your application needs. According to this wiki entry it seems that it fits to EPL.
Step 4: Implement the parser
To run the parser we need 2 more classes. Lets start with com.example.antlr.CSVVisitor
package com.example.antlr;
import java.util.Arrays;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
import org.antlr.v4.runtime.tree.RuleNode;
import org.antlr.v4.runtime.tree.TerminalNode;
import com.example.antlr.gen.CSVBaseVisitor;
import com.example.antlr.gen.CSVLexer;
public class CSVVisitor extends CSVBaseVisitor<List<Integer>> {
@Override
public List<Integer> visitChildren(RuleNode ctx) {
List<Integer> numbers = new LinkedList<Integer>();
for (int index = 0; index < ctx.getChildCount(); index++)
numbers.addAll(visit(ctx.getChild(index)));
return numbers;
}
@Override
public List<Integer> visitTerminal(TerminalNode node) {
if (node.getSymbol().getType() == CSVLexer.NUMBER) {
int number = Integer.parseInt(node.getText());
return Arrays.asList(number);
}
return Collections.emptyList();
}
}
Now we can finally call the parser from com.example.antlr.CSVProcessorpackage com.example.antlr;
import java.util.List;
import org.antlr.v4.runtime.ANTLRInputStream;
import org.antlr.v4.runtime.CommonTokenStream;
import com.example.antlr.gen.CSVLexer;
import com.example.antlr.gen.CSVParser;
public class CSVProcessor {
public static List<Integer> parseCSV(final String data) {
CSVLexer lexer = new CSVLexer(new ANTLRInputStream(data));
CSVParser parser = new CSVParser(new CommonTokenStream(lexer));
return parser.csv().accept(new CSVVisitor());
}
public static void main(String[] args) {
List<Integer> numbers = parseCSV("2,45,66,123,24,6,7,7,8");
System.out.println(numbers);
}
}
If you need support on ANTLRv4 check out the webpage or - even better - support the project and buy the book.
Subscribe to:
Posts (Atom)



