Monday, December 21, 2009

Installing X.509 certificates on Nokia S60 3rd edition device

Sometimes you need to install your own X.509 certificate on the phone in order to authorize some web site, Exchange server, or installed software, or in general to use TLS (SSL) connection. According to the guide, provided on Nokia forums – it a piece of cake! However, sometimes problems may arise, and you start wondering about what can go wrong. The next thing you do is try to find the answer somewhere on the Internet. Well, you'll get a whole bunch of different posts about positive or negative experience, you'll find different solutions that are sometimes weird, sometimes don't work, and sometimes work but not on your phone. In general, most solutions are correct, you just need to pay attention to one nobody-ever-mentioned thing.

At first, a small amount of theory, so you'll know what I am talking about. X.509 certificate files have several extensions. Here is the description from Wikipedia for the most common:

  • .pem - Base64 encoded DER certificate, enclosed between "-----BEGIN CERTIFICATE-----" and "-----END CERTIFICATE-----"
  • .cer, .crt, .der - usually in binary DER form, but Base64-encoded certificates are common too
  • .p12 - PKCS#12, may contain certificate(s) (public) and private keys (password protected)
  • .pfx - PFX, predecessor of PKCS#12 (but most of the time the actual data is PKCS#12, only the extension is kept)

If you are not into technical very much, you just need to know that .pem files are text files. So you can open them in any text editor (like GEdit or Notepad) and see bunch of letters and numbers after the first line, which says “-----BEGIN CERTIFICATE-----”. Those letters and numbers is actually a specially encoded binary certificate. Now, the files with extensions .cer, .crt, .der are usually (but not always!) binary files. That means that you cannot view their contents with usual text editor. But pay attention to what is being said at the end for this kind of files: “... but Base64-encoded certificates are common too”! That means, that you can have a certificate file with, for example, .cer extension, but it will be a text file actually encoded as .pem file! And, what's the difference, you ask, why should I care?

Well, here we came to the most interesting part. Nokia phones on S60 3rd edition platform cannot import .pem certificates! They cannot import certificates that are represented as text files. You need a binary DER encoded file. And what's really exciting – you can have a .cer, .crt, or even .der file, but it will be a text file that was renamed from .pem! Well, your computer web browser will cope with it just fine. You computer mailing program will cope with it just fine, too. But not your Nokia phone!

If you are still wondering on “how do I know what kind of certificate file I have?”, then try to do a simple thing. Open the file with any text editor and see: if it opens correctly and has the first line as “-----BEGIN CERTIFICATE-----”, then this is a text .pem file. If it doesn't open correctly or has something really crazy inside – then it is probably a binary .der file.

If you have a binary certificate file, then just transfer it to the phone and open with phone's File Manager. It will ask you to import the certificate. Just like the mentioned tutorial says. What if you have a text certificate file? Then you should convert it to binary representation. There is an open source and free program that can do it for you, called OpenSSL. A compiled version of OpenSSL for Windows can be found here. Ubuntu users just type in terminal: sudo apt-get install openssl.

So, you've got the program! Next thing you do is type in terminal the following command:

openssl x509 -outform der -in certificate.pem -out certificate.der

In place of 'certificate.pem' you should put your text certificate file (it can have extensions .pem, .cer, .crt, .der but it should be text file) and in place of 'certificate.der' you just put any name you want. After executing this command (pressing Enter in terminal after typing it there) you should get in your directory a file named 'certificate.der' (or whatever you've put there), which will be a binary DER encoded certificate file. After that you do the same thing that I wrote before – transfer file to the phone and open it with File Manager. And you're done!

Now, lets mention the .p12 files. As I said before that are the binary files containing public certificate and password-protected private key. According to the already beloved Nokia guide this kind of files should be supported for installing on the phone. Well, not necessarily. In fact, unfortunately my Nokia N73 phone with the latest firmware does not import .p12 certificate files. I don't know why. Nokia support does not know either. I didn't dig it deeper into the problem, because I actually didn't need to install the certificate with private key – I probably will not decrypt any content with my phone that was signed or encrypted with public certificate (that is why you actually need a private key). But if you still need to import just the certificate from the .p12 file, you need to extract it first. The following command can be used:

openssl pkcs12 -in keyStore.p12 -out certificate.pem -nodes -nokeys

In place of 'keyStore.p12' you put the name of your .p12 file and in place of 'certificate.pem' you put any name. After executing this command you will get a text certificate file. Please, pay attention – it will be a text certificate file. You will need to convert it to binary format with the command mentioned before.

Well, that's about it! Now you should have no problems with installing your own X.509 certificate files on the Nokia phone. I didn't test the other versions of Symbian OS for the support of text certificate files, because I do not have many Nokia phones, except my own N73 :) But I think that S60 4th and 5th editions do not support then either.


Tuesday, December 8, 2009

Видео лекция по AspectJ

Аспектно-ориентированное программирование (АОП) — парадигма программирования, основанная на идее разделения функциональности для улучшения разбиения программы на модули. Основная идея сводится к выделению сквозной функциональности, разбросанной между существующими модулями программы (классами, функциями), в отдельные аспекты, которые потом можно повторно использовать. Многие контейнеры, среди которых и Spring Framework, содержат в своем ядре АОП и используют его, а некоторые даже предоставляют свою реализацию (Spring AOP, JBoss AOP).

АОП мне понравилось своим нестандартным подходом. Всем известная единица модульности в ООП — это класс. Некий набор классов, где каждый выполняет совсем разные функции, может содержать определенную сквозную функциональность, не имеющую отношение к логике самих классов. Это может быть управление транзакциями, кеширование данных, ведение логов, уведомление пользователя и т. д. Как сделать так, чтобы функциональность не дублировалась? Можно воспользоваться самим ООП, применить наследование или агрегацию, но тогда классы все равно будут зависеть от других. Можно применить различные шаблоны проектированиявнедрение зависимостей, например, но тогда приложение становится зависимым от сторонней библиотеки, применение которой не всегда может быть оправдано. Шаблоны проектирования помогают решить большинство проблем, связанных с проектированием приложения, но что, если сам шаблон содержит, либо приводит к появлению, сквозной функциональности (например, шаблон Наблюдатель, где дублируется логика управления наблюдателями)?

Решением описанных проблем может быть, и на самом деле есть, применение АОП. Сквозная функциональность выносится в отдельный модуль, называемый аспектом (aspect). В нем также определяется с помощью точек соединения (joint-points), где, в каких местах, и при каких условиях будет применяться данная функциональность, называемая советом (advice). Советы могут привязываться к точкам соединения либо во время компилирования программы, либо во время загрузки программы, либо даже во время работы программы. Разные библиотеки реализации АОП предоставляют разные возможности.

АОП реализовано во многих языках программирования. Для Java одной из успешных реализаций является AspectJ. Для работы с ней в среде Eclipse отлично подойдет плагин AJDT. Документации по AspectJ и вообще по АОП можно найти много, но мне больше всего нравятся два источника. Первый — это AspectJ 5 Developer's Notebook. Он же содержится сразу в помощи (F1) к плагину AJDT. Второй источник — это цикл статей AOP@Work от IBM. После того, как познакомитесь с АОП, рекомендую прочитать статью AOP@Work: Мифы и реальности АОП, где развенчиваются некоторые мифы, связанные с использованием АОП, и где содержатся дополнительные ссылки для изучения АОП.

Идея рассказать студентам про АОП у меня возникла тогда, когда я решил к курсовому проекту по предмету «Технологии проектирования программных систем» добавить контейнер Spring Framework, чтобы он создавал все необходимые сервисы, связывал их между собой, а также управлял транзакциями и работой с базой данных. Управление транзакциями происходит декларативно с помощью Java аннотаций над методами или классами. А вот непосредственно код, связанный с транзакциями, находится в аспектах, которые подключаются к проекту. На лекции я старался объяснить, что нам дает использование АОП, а также показать основные способы применения AspectJ.

Update: Ниже выкладываю слайды лекции, чтобы Вы их смогли скачать и использовать в своей практике. Для этого нажмите меню в правом нижнем углу, потом нажмите на название презентации слева почти снизу. В новом окне откроется презентация, где ее можно будет скачать.


Friday, December 4, 2009

Java Swing application to access Blogger

This small and very simple application allows you to connect to the Blogger server, see all you blogs, read posts, create new posts and edit them. The use of Java language was determined by the need of running this application on different operating systems. Swing was used for GUI programming because of its simplicity (and one more reason, described below). The name of the application is JDesktopBlogger.

After I started to use Blogger I searched for some desktop application to use with it. I've tried to use different open sources projects but none of them fit my needs. Then I thought: why not writing something on your own? Interesting enough, but some big changes came to my life at that time - I've switch my job and moved to another city. At the new job because of some reasons I couldn't start working at the project right away. I had couple of weeks to... do some self education :) I found out that the new project will be dealing with Swing. So I thought - why not create a blogging application? I've incited my friend to help me. We both were waiting for a project to start and while waiting we created this blogging application.

The application is very simple. The used technologies are limited to Swing for GUI, JAXB for saving account's file, Google's Gdata BloggerService for accessing Blogger.

At the time of writing this post the application is at pre-beta state. :) The features are not very rich, but include the following:
  • managing of several blogger accounts (includes creating, editing, deleting);
  • getting list of all blogs within account;
  • managing list of all posts within blog (includes creating, editing or deleting posts);
  • ability to create draft post. 
That's about it :) Not much, but we had to start with something. However, I do have some plans for this application and if time permits we'll add the following:
  • simple formatting options for post (right now only plain text is supported); 
  • caching of posts and blogs;
  • saving drafts on local machine; 
  • support of other blogging services by adding plug-in functionality. 

And now the main revelation: This post was written from the created application! :) It's like a proof of its work. Well, yes, the formatting of links and lists was later edited in the web, but that is the primary to-do for me :)