Archive for the ‘Technical’ Category

How to obtain signer’s details from a JavaScript signed data

July 2, 2009

In a previous post I described how to sign data with only javascript. Now, this data should be used on the server side for something. Here is how a Java developer can extract the signature details, and verify whether the content received from a form is really what has been signed. The general scenario is – a user submits a form, the data from which he signs. Then on the server the submitted data should be verified against the signed (PKCS7) data.

One needs the Bouncycastle libraries and apache commons codec:

package com.materna.remedy.plugins;

import java.util.Collection;
import java.util.Iterator;
import java.util.Map;

import org.apache.commons.codec.binary.Base64;
import org.bouncycastle.cms.CMSProcessable;
import org.bouncycastle.cms.CMSProcessableByteArray;
import org.bouncycastle.cms.CMSSignedData;
import org.bouncycastle.cms.SignerInformation;
import org.bouncycastle.cms.SignerInformationStore;
import org.bouncycastle.jce.provider.BouncyCastleProvider;

public class CertificateDataExctractor {
	private Map<String, Object> extractInfos(String base64EncodedPKCS7,
			String contentString, boolean isIe) {
		try {
			byte[] data = Base64.decodeBase64(base64EncodedPKCS7.trim().getBytes());

			Security.addProvider(new BouncyCastleProvider());

			CMSSignedData signedData = new CMSSignedData(data);

			if (signedData.getSignedContent() == null) {
				byte[] contentBytes;
				if (!isIe) {
					contentBytes = contentString.getBytes();
				} else {
					contentBytes = contentString.getBytes("UnicodeLittleUnmarked");

				CMSProcessable cmsProcesableContent = new CMSProcessableByteArray(
				signedData = new CMSSignedData(cmsProcesableContent, data);

			CertStore certsStore = signedData.getCertificatesAndCRLs(
					"Collection", "BC");
			SignerInformationStore signersStores = signedData.getSignerInfos();

			boolean verified = true;
			boolean validCertificate = true;
			Map<String, Object> signerData = null;

			for (Iterator<SignerInformation> iter = signersStores.getSigners()
					.iterator(); iter.hasNext();) {
				SignerInformation signer =;
				// emulate(signer);

				Collection certCollection = certsStore.getCertificates(signer

				if (!certCollection.isEmpty()) {
					X509Certificate cert = (X509Certificate) certCollection

					try {
						if (!signer.verify(cert.getPublicKey(), "BC")) {
							verified = false;
					} catch (Exception ex) {
						// if this is an attempt to verify it assuming Firefox,
						// try assuming IE. If it is already IE - the
						// verification doesn't pass
						if (!isIe) {
							return extractInfos(base64EncodedPKCS7,
									contentString, true);
						verified = false;

					// If this is the last signer in the chain, obtain the data
					if (!iter.hasNext()) {
						signerData = extractSubjectInfos(cert);
			return signerData;
		} catch (Exception ex) {
			return null;


And of course, you provide your own implementation of getSubjectInfos method, putting whatever data you need from the certificate in the Map.


NoScript and AdBlock plus – two sides to every story

May 2, 2009

(If you don’t want to read too much here, check the links below)

Recently a lot of crap has been written at many places against NoScript (reddit, slashdot, the addon page on mozilla’s site, etc).
We can easily call it a flame war, but that’s not the point – the point is to have a good-working protective solution for any web-behaviour. I don’t use AdBlock plus, but a friend of mine does, and she is pretty happy with it. I’m pretty happy with NoScript, so every train has its passengers. Again – that is not the point. The point is that obviously AdBlock plus developer(s) trying to drive users away from NoScript. As you are reading this, you have probably read the blog-post in ABP site :

But of course, there is two sides to every story: saying:

Notice to AdBlock Plus users: after a targeted attack from EasyList which broke functionality like direct links to development builds on developer’s sites, NoScript and above configure a regular filterset whitelisting them. As any filterset, you can easily disable it with two clicks if you prefer.

And so, I saw a pile of users removing NoScript just for the reason someone has mocked it. How rational. Good luck to those in not getting infected.

“Who started the flame war” is an irrelevant question here – the question is why people are so not-quite-intelligent. I will continue using NoScript.

How to create a digital signing solution with only JavaScript

April 16, 2009

Look at the js-signer project on GitHub

Go to the new version of this blog post

It is sometimes required to have the user sign a text in order to certify that he is the one who has done the operation. For example, in an e-banking software, the user might have to sign a text describing the transaction (“Transfer 300 dollars to IBAN xxxxxxxxx”), or sign a request for a governmental eService. This could be achieved by a java-applet, but as JRE owners are not a majority, it is preferable to use other ways.

Of course, the preconditions are, that the user has a digital signature, issued by a CA, and has followed the CA’s manual for installing the certificate in a browser. If these steps are not completed successfully, the solution below wouldn’t work.

Also, note that this uses PKCS7 (java developers: use bouncy castle to verify it), instead of the XAdES standard. Internet Explorer has support for XAdES, but FireFox doesn’t.

Let’s see a simple HTML page that should sign a given text:

<script src="sign.js" type="text/javascript"></script>

<input id="text" type="text" />
<input onclick="signDigest(document.getElementById('text').value);" type="button" value="Sign" />

and then the JavaScript itself:

function signDigest(text)
window.event.cancelBubble = true;

var dest = sign(text); //TODO
return dest;

// CAPICOM constants
var CAPICOM_E_CANCELLED = -2138568446;

function IsCAPICOMInstalled()
if(typeof(oCAPICOM) == "object")
if( (oCAPICOM.object != null) )
// We found CAPICOM!
return true;

function FindCertificateByHash()

// instantiate the CAPICOM objects
var MyStore = new ActiveXObject("CAPICOM.Store");
// open the current users personal certificate store

// find all of the certificates that have the specified hash
var FilteredCertificates = MyStore.Certificates.Find(CAPICOM_CERTIFICATE_FIND_SHA1_HASH, strUserCertigicateThumbprint);

var Signer = new ActiveXObject("CAPICOM.Signer");
Signer.Certificate = FilteredCertificates.Item(1);
return Signer;

// Clean Up
MyStore = null;
FilteredCertificates = null;
catch (e)
if (e.number != CAPICOM_E_CANCELLED)
return new ActiveXObject("CAPICOM.Signer");

function sign(src)
if(window.crypto &amp;&amp; window.crypto.signText)
return sign_NS(src);

return sign_IE(src);

function sign_NS(src)
var s = crypto.signText(src, "ask" );
return s;

function sign_IE(src)
// instantiate the CAPICOM objects
var SignedData = new ActiveXObject("CAPICOM.SignedData");
var TimeAttribute = new ActiveXObject("CAPICOM.Attribute");

// Set the data that we want to sign
SignedData.Content = src;
var Signer = FindCertificateByHash();

// Set the time in which we are applying the signature
var Today = new Date();
TimeAttribute.Value = Today.getVarDate();
Today = null;

// Do the Sign operation
var szSignature = SignedData.Sign(Signer, true, CAPICOM_ENCODE_BASE64);
return szSignature;
catch (e)
if (e.number != CAPICOM_E_CANCELLED)
alert("An error occurred when attempting to sign the content, the errot was: " + e.description);
return "";

And that should do the stuff – the signed text can be sent to the server, where it can be verified (in case, of course, the server has the public part of the user’s certificate)

P.S. One important note when verifying afterward – Internet Explorer uses UnicodeLittleUnmarked (UTF-16LE) to encode the signed data, before signing it. So when verifying, use this encoding.

How to iterate over java.util.Set in JSF

March 3, 2009

Go to the new version of this blog post

I spent quite some time trying to find a solution for the following JSF issue: it is not possible to iterate over a java.util.Set.
– ui:repeat (facelets) doesn’t work
– a4j:repeat (richfaces) doesn’t work
– c:forEach works..only in case it does not rely on a variable defined by a parent component (rich:dataTable for instance)

All above are pretty logical phenomena, as UIData relies on ordered data, and generally a Set is not ordered.

In my case I had to use a Set defined in the Hibernate (JPA) object (PersistentSet).
An important note: you should use a set in case the view order is of no matter to you.

The pretty simple. And I’ll suggest it to be a part of facelets/richfaces for the next version, unless of course there is some valid specific reason for it not to be.

1. Define your own UI component extending an existing repeater component. I used a4j:repeat (HtmlAjaxRepeat)
2. Override the metohd getDataModel
3. Define your component in your faces-config
4. create a custom facelets tag definition
5. Define a context-variable in web.xml pointing to the facelet tag definition.

Note: for use with JSP instead of Facelets, you should define a .tld and a Tag handler, which is not an ojbect of this post.

Now let’s see the steps in detail:

1,2. Here some code:

package com.myproject.components;
import java.util.ArrayList;
import java.util.Set;

import javax.faces.model.DataModel;
import javax.faces.model.ListDataModel;

import org.ajax4jsf.component.html.HtmlAjaxRepeat;
import org.ajax4jsf.model.SequenceDataModel;

public class UIIterator extends HtmlAjaxRepeat {

   protected DataModel getDataModel() {
      Object current = getValue();
      if(current instanceof Set){
          return new SequenceDataModel(new ListDataModel(
                new ArrayList((Set) current)));
      return super.getDataModel();

So, as we don’t care about the order of the elements, we just create a new ArrayList out of the Set. And we can now easily return the appropirate DataModel.

3. Add this to your faces-config. (I copied it from the a4j definition)

		<description />


4. Here is the tag definition for facelets

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE facelet-taglib PUBLIC
"-//Sun Microsystems, Inc.//DTD Facelet Taglib 1.0//EN"
<facelet-taglib xmlns="">



Save this file as /WEB-INF/facelets/custom.taglib.xml

5. Add to your web.xml


6. It is now ready to use


<cust:repeat var=”myVar” value=”${aSet}”>


I think it is way neater than other workarounds, like defining a custom EL Resolver.

Why I might not want to use Flex

November 27, 2008

While waiting for my eclipse to shut down, because the Flex Builder plugin again made it crash, I decided to write a little about my Flex experience.

I’m now on the finish straight of a small-to-medium project which uses Flex as a front-end.

On first sight Flex is smooth and pleasant to work with. You draw a bunch of beautiful components, write three lines of actionscript, and here’s is our nice “advanced hello”. But whenever one gets more into the details, the immaturity of Flex (and ActionScript) is too visible, alas.

First, to start with the more general stuff:

  • exception handling. For a Java-guy like me, the exception handling ‘not perfect’. When an Error is caught, all you can know about it is .. the error code. Isn’t this too 1990? Stacktraces you can somehow acquire by calling “trace”, but it requires some configurations.
  • event handling. At first, it does not seem troublesome when you see the event handling mechanism. object.addEventListener(stringConstantEventType, handlerMethod). Ok, I don’t really mind the String constant (though I should), but the handler method accepts only an Event as an argument. (And when you write your method to have the wrong argument class it starts to feel strange). This makes it impossible to pass other arguments to the ‘listener’. Yes, you can use fields of the declaring class, but what if two asynchronous notifications happen? Actually, a brief look at the Ovserver (listener) pattern shows the right way to do this. I don’t know why it is so strange.
  • multithreading. Here I still don’t get things quite well – I read that Flex is single-threaded, and there is no way of manipulating threads. What a shame – especially if the flash player supports multithreading. In fact Flex maybe supports some kind of multithreading, with which it serves asynchronous requests, but are these mechanisms accessible for the developer? Actually, my recent experience hints towards the hypothesis that Flex has 2 threads – one for UI and one for the alleged asynchronous requests. So only one async request at a time. I might be wrong, of course.
  • dynamically typed AS3. Completely no problem with this, but something bothered me. When I referenced an objecet by its interface, the compiler did not know it is an Object, and so I couldn’t call its Object mehtods (toString()). So I need to cast it to Object (or whatever I want). And where did the dynamic typing go..?
  • event dispatching. This might well go to the section above, but here I don’t mean the machanisms, but some strange implementation details. I have exactly two examples – the Event.COMPLETE is dispatched by an Image before the Image object has marked itself as completed. And this caused problems. Also, the Click event is not dispatched if MouseDown is.
  • now on to some very specific things. Starting with the file upload. Something very basic and regularly needed. Prior to Flex 3.2 (and I’m using 3.1), there is not getBytes, or similar methods for a file. So the only option to send the file is via a Http request (instead of some remoting that I would prefer). But ok – I created a servlet which would parse the request, check the size, type, dimensions of the image, and return whether it is allowed to be uploaded or not. But much to my surprise, as far as I understand (please, anyone correct me if I’m wrong), there was no way of getting feedback from the server. So I had to think of a way. I thought of a solution, which I’m ashamed of – I used the HttpStatusError, and I mapped an arbitrary Http status code to a certain error (type not supported, size too big, etc.)
  • fonts cannot be loading dynamically – they must be precompiled. Which is my case made me write an java image creation servlet, but I suppose that in the common case it would be sufficient.
  • hibernate support – I only took a glimpse of the examples of a hibernate support, saw some re-definitions of collection mappings (<one-to-many ..), and ran away screaming.

So, from these points I dare to conclude that Flex is still immature. Version 5 might be really good. But not now, and not until some serious considerations and rafactoring.

That’s why I’m likely to propose GWT as a RIA solution for forthcoming projects.

Content Management Systems – a bad idea?

August 11, 2008

CMS – Content Management Systems are meant to…manage content. So if we need a generally static content, which should be editable by non-technical persons, it is probably a good idea to use them. Probably.

I’ve had some experience with a number of CMS (Joomla, DotNetNuke for example), and read/tried some more. What do all of them claim to offer – faster development, easier reusing of repeated tasks (registration, news feeds, etc). But let’s review some of the claims, and compare the use of CMS to making a site from scratch:

  • editing by non-technical persons made easy: Without a step-by-step guide a non-technical person would never make it through the complicated menus, buttons. And what most CMSs offer is some ugly javascript editor-enabled textarea, which generates bulky and incorrect (X)HTML. On the other hand, with a similar step-by-step guide, a non-technical person can easily use Dreamweaver to make his pages and link them to menu items.
    • easily reusing repeated tasks: let’s call the pieces of reusable code “modules” (they are often called that way). They should integrate well with both the CMS, and with existing modules. In practicse this is never the case. If at all any integration between modules is to be achieved, a bunch of inconvenient configurations are to be done.  And when at some point you find out that the existing module is not actually working as you want, it becomes a fight with the constraints of the cms. On the other hand, if you have already developed a number of sites, and have developed them well enough, you can reuse your own code (or even someone else’s independent code) knowing perfectly well what the outcomes will be.
    • creating new functionality: as mentioned in the previous point, lot’s of constraint and cms-specific rules are to be observed. They cannot be forced programatically, so you will be lucky if you have a whole list of these constraints and dependencies. Otherwise you should guess each time something doesn’t work. And these constraints and dependencies are not few at all in big CMSs. On the other hand, writing a custom functionality as just plain code, with no configurations, implicit and explicit dependencies seems easier. Of course, it should integrate with the existing system, but this integration is done transparently.

    In all the above point “learning curve” should’ve been included. It takes too much time to master a concrete CMS. And why, when, if you structure you work well, you can achieve even better speed and quality?

    So let’s introduce the term “prepared scratch” – that is, all general stuff like db connections, main configurations, etc, is already prepared, and you start writing your custom dynamic/static pages from that point. Believe me it will turn out to be a lot easier, and will save neurons.

    NetBeans 6.1 – not even 10% a useful IDE

    July 8, 2008

    I am forced to work with NetBeans (6.1) from time to time. We are creating a Desktop app, and hence NB’s Matisse is a good idea.
    But.. recently I started using only Matisse, and when I finish drawing, go back to Eclipse. Why? Well,

    • NetBeans is becoming rather slow, gets stuck randomly – on copy/paste, on autocomplete, on loading the projects, on pressing a shortcut. Note that my machine is Core2Duo 2.2, 2G of RAM, so not a weak one.
    • indexing of files is obviously not working as it should – when trying to Open Type (CTRL + SHIFT + T, from eclipse shortcuts) half of the classes are just not there. And I have to manully locate them in the project explorer. Furthermore, the suggestions are rather stupid. Classes that appear on the first lines are completely unrealated to the project. (See Eclipse for the better implementation)
    • some stupid caching. I updated a project (we are using 4 separate projects, in order to separate functionality), and then it wouldn’t run. It turned out a jar has been removed by one of my colleages. He added it, and committed. I updated, the project properties file WAS updated, but when I rightclick>properties, the jar isn’t there.
    • refreshing errors – the red dots here and there in the project explorer are not where they should be. They are updated only when one opens the file, and sees that – hey, there are no errors here. Also, today I removed a class, that was reduntant (merely extending some jdk interface). There were places, where the red dots appeared, and I corrected the usages. However, when I tried to run, not much to my surprise actually, the compiler comlained about 2-3 other places, where red dots do not exist. The cool thing is that I’ve been running with such hidden compilation errors for 2 days – obviously they have been cached in the build as well.
    • missing key features. Like on commit, selecting which files to commit and which not. Such basic stuff should not be missing from production-stable IDE. Another thing is that, to my knowledge, they don’t have call and class hierarchies.

    So, in short – NetBeans can NOT be used in production, unless one slowly goes around with the mouse, and uses only 2-3 options.
    No matter how much extras and plug-ins they create, if the base, and most used functionality is working so bad, I doubt NB will soon become a useful IDE.

    I have always wondered why there are developers that seem to like NB very much — are they searching for classes by unfolding packages in the project explorer, or copying using the mouse, or running “Clean” on every base class modification or removal of class?

    Why Windows Live Hotmail is not competitive?

    July 8, 2008

    Today I had to check an e-mail in my old hotmail account. First of all, a 404 message in the two left frames – I didn’t mind it – the login frame was there.
    I needed to check the header information of the e-mail. And much to my surprise – I did not see an option “show headers”, “show original” or “save original message”.
    I switched to the new, full-featured Live Hotmail version.
    Well, this feature seems not important for Microsoft developers. Note that Gmail, Yahoo, and every competitive email system has such an option.
    Another complaint – the vertical e-mail preview, where the screen it split in two. 1/3 of my FireFox, google-toolbarred+stumble toolbarred screen is taken by the logo and the banner above. I feel like having claustrophobia.

    I just don’t want to know what more ‘good surprises’ will Hotmail present to me.
    In conclusion, MS seems to underestimate ergonomic and functionality. How come they want to have users? If this is based only on the “wide-spreadness” of Windows, their days are counted. Imho.

    First look at Google Android – a bit of disappointment?

    July 8, 2008

    As every hyped product, Google’s Android attracts developers attention. So did it with me, I downloaded the SDK, and starting coding some simple things.
    Let me summarize:

    • I felt a bit strange when all constructors of UI components required a Context parameter (“this” in most cases). I’m pretty sure there should be some reason for that, and it is not a big problem, I suppose
    • Lots of XML. Everything (yes, even UI components) is declared in xml files. Which I, and I suppose many more, hate. You see – no one tells you about typos in the xml config, which is pain in.. Yes, the UI components might be done the _normal_ way – programatically – but you need to declare every screen, and every screen transition in the xml file. I’m sure there is a reason for this, too, but it surely does not warm my feelings
    • The Emulator is buggy. Just go the Google Groups to see all the complaints about it

    And not to be all pessimistic, Android seems to offer a very wide scope of functionality and application interoperability (that’s why it is a platform, after all). Each application can use common resources, communicate with other applications, etc. Maybe here’s why we have to write all those XMLs, but having already tweaked the VM, can’t they spare us the xml-part?

    Despite some major public concerns that Android can “fracture Java”, I think this is just a framework. Yes, it has it’s own VM, but the Java code you write is the same – it just runs only if the framework is supported by the device. And for mobile devices, we all know, “write once, run everywhere” is a myth.

    In conclusion, Android may turn to have some big flaws, and not be comfortable for developers. We will see when the hype is over.

    Feed readers’ view-styles

    July 8, 2008

    Today we have a new version of Google Reader, and here’s why I decided to comment on the ways feeds can be presented.

    The new version of Google Reader is, of course, better than the previous, where I felt trapped in the tiny boxes. Still, however, I feel uncomfortable with it – I have to click here and there if I have to see what is new.
    The same issue (I’d not call it a problem) lies in most feed readers – the tree-like organization of feeds.
    On the other hand, many of you may know about Netvibes – a Web 2.0, ajax-based application that might look as a complete mess at first sight – all headlines listed in boxes all over the screen. But what we have to keep in mind is, that the human brain is not organized tree-like. And so the use of such chaotic interface is much a comfort. Maybe If I hadn’t used netvibes I wouldn’t feel uncomfortable with other feed readers, who knows.