piątek, września 05, 2008

Znana witryna - http://today.java.net/pub/a/today/2006/11/21/xml-signature-with-jsr-105.html?page=1 - "XML Signature with JSR-105 in Java SE 5" Standard ten jest już przyjęty tutaj jest dokumentacja - http://jcp.org/aboutJava/communityprocess/final/jsr105/index.html

Celem podpisu cyfrowego jest zapewnienie integralności danych zgodnie z RFC 2828, dodatkowo chodzi o mocniejszy dowód - autentykację (message authentication).

<Signature ID?>
<SignedInfo>
<CanonicalizationMethod/>
<SignatureMethod/>
(<Reference URI? >
(<Transforms>)?
<DigestMethod>
<DigestValue>
</Reference>)+
</SignedInfo>
<SignatureValue>
(<KeyInfo>)?
(<Object ID?>)*
</Signature>

Znaczenie Reference - łącznik między danymi do podpisania a samym podpisem. Wewnątrz dla danych jest liczony skrót wiadomości (hash, digest, footprint, odcisk) w elemencie DigestValue algorytmami (tzw. one way hash) SHA-1, SHA -256, SHA-512. Elementem, który jest podpisywany jest SignedInfo wg algorytmów DSA-SHA1, RSA_SHA1.

Podpisywanie składa się z dwóch etapów:

  • Obliczenie wartości hash i wpisanie jej do Digest Value dla każdej wiadomości
  • Wygenerowanie podpisu cyfrowego (digital signature) dla całego elementu SignedInfo i wstawienie go do pola SignatureValue. Inaczej mówiąc zaszyfrowanie całego bloku SignedInfo. Do podpisu stosuje się klucz prywatny wysyłającego (podpisującego)

Walidacja podstawowa składa się również z 2 etapów: (http://java.sun.com/developer/technicalArticles/xml/dig_signatures/fig8.gif):

  • Reference validation - czy każdy element Reference jest poprawny tzn. oblicza się hash otrzymanego wiadomości i sprawdza z DigestValue
  • Signature validation - polega na sprawdzeniu przy pomocy klucz publicznego podpisującego (?) - odszyfrowanie bloku SignedInfo posługując się kluczem publicznym i porównanie tej wartości z wartością hash elementu SignedInfo otrzymanej wiadomości
  • Potwierdzenie tego jest na stronach Sun-a - http://java.sun.com/developer/technicalArticles/xml/dig_signatures/
  • Inne potwierdzenie "Performing a digital signature involves two steps. In the first step, the data is run through a hashing algorithm. A typical hashing algorithm scans through the data and generates a number of some size -- this is typically called a "digest." If the same data is run through the hashing algorithm again, the same digest should be generated. Good hashing algorithms vary the digest unpredictably if the slightest change is made in the data. This makes it impossible to reverse engineer the original data, given the digest.

The second step in producing a digital signature is to encrypt the digest using the private key of the author. If you're not familiar with the terms public key or private key, then you've probably never heard of public key cryptography. The basic concepts of public key cryptography are simple: anything that is encrypted using an individual's private key, can only be decrypted using the same individual's public key. The reverse is also true: anything encrypted using an individual's public key, can only be decrypted using the same individual's private key. The two keys are mathematically linked. After encrypting the digest with the user's private key, the resulting scrambled data is then appended to the original document data.

Because public keys can be shared with anyone, and private keys should be known only to the signing author, verifying a digital signature is simple. The steps are:

  1. Rehash the document data that was received.
  2. Decrypt the encrypted digest with the author's public key that is typically appended to the document.
  3. Compare the two digests. If they are equal, the signature is valid.

If the two digests are not equal, then either the document has been altered, or the author of the document is not the same as the individual that signed it. However this information does not indicate which of those two faults (or both) have occurred. Wklejono z <http://www.java-tips.org/java-ee-tips/xml-digital-signature-api/using-the-java-xml-digital-signatur-2.html>"

Znaczenie Object -rekomenduje się aby tam umieścić dane które będą podpisywane (w przypadku wersji podpisu enveloping). KeyInfo z kolei może zawierać informacje o kluczu publicznym potrzebnym przy weryfikacji.

Pomocne narzędzia w Javie to keytool - http://java.sun.com/j2se/1.4.2/docs/tooldocs/windows/keytool.html

Lista dyskusyjna:

Podpis cyfrowy w Java przy pomocy biblioteki Apache XML Security (DigiSig) - http://www.linux.com/feature/39427

Bardzo ciekawy artykuł "JAVA XML Digital Signature" pokazuje architekturę JCA (Java Cryptographic Architecture) jako rozszerzalną platformę:

Niezbędne biblioteki:

  • javax.xml.crypto
  • javax.xml.crypto.dsig
  • javax.xml.crypto.dsig.keyinfo
  • javax.xml.crypto.dsig.spec
  • javax.xml.crypto.dom
  • javax.xml.crypto.dsig.dom

W celu przyśpieszenia operacji kryptograficznych (zajmują one do 30% CPU) proponuje SUN wykorzystanie rozszerzenia PKCS#11 (Crypto.Token Interface Standard) w celu przeniesienia ciężąru obliczeń na akceleratory sprzętowe lub karty inteligentne.

Na powyższym rysunku Sun PKCS#11 Provider stanowi pomost między warstwami wyższymi a konkretną implementacją obliczeń kryptograficznych. Statycznie określenie rodzaju dostawcy polega na edycji pliku konfiguracyjnego sunpkcs11 umieszczonego w ../jre/lib/scurity/java.security Oto fragment mojego pliku:

#

# List of providers and their preference orders (see above):

#

security.provider.1=sun.security.provider.Sun

security.provider.2=sun.security.rsa.SunRsaSign

security.provider.3=com.sun.net.ssl.internal.ssl.Provider

security.provider.4=com.sun.crypto.provider.SunJCE

security.provider.5=sun.security.jgss.SunProvider

security.provider.6=com.sun.security.sasl.Provider

security.provider.7=org.jcp.xml.dsig.internal.dom.XMLDSigRI

security.provider.8=sun.security.smartcardio.SunPCSC

security.provider.9=sun.security.mscapi.SunMSCAPI

Jak widać jest nawet obsługa MS CAPI (poprzez wpis 9).

Fundamentalne łącza:

Przykład diagramu:


czwartek, września 04, 2008

Zasoby z Toshiby:
30.08.2008
==========
Zasoby: Kruger, DaniWeb, Zen Habit, Ajaxian
1. http://www.ajaxtoolbox.com/request/examples.php
2. http://www.mattkruse.com/
27.08.2008
==========
1. jsc - sourceforge, chyba to jest to - http://docs.google.com/View?docid=dfmc8fvr_208fmcjqmhm
2. Obsługa JDOM -http://www.informit.com/guides/content.aspx?g=java&seqNum=432&ns=15275, biblioteka - http://jdom.org/
3. Triki optymalizacyjne w JS wykorzystujace najnowsze osiagnięcia optymalizacji - http://arstechnica.com/news.ars/post/20080822-firefox-to-get-massive-javascript-performance-boost.html
4. Nowa gra "Battelfield Heros" z EA - http://arstechnica.com/news.ars/post/20080826-first-look-battlefield-heroes-is-good-free-pc-gaming-fun.html, podobna gra Team Fortress 2
5. Mini Ajax -pomysły na ajaxa - http://miniajax.com/
6. Miętowy Ajax - http://mintajax.pl/
7. JS corral -http://www.crays.com/jsc/index.htm
8. Ściągnij najnowszy MS SQL Server - http://www.microsoft.com/express/sql/default.aspx
9. Zasoby JS na MOzilli - http://www.mozilla.org/js/scripting/
10. Wykorzystanie FireBug-a - http://www.webmonkey.com/tutorial/Build_Better_Pages_With_Firebug#FirePHP_equivalents_for_other_languages
11. UI JWuery - http://docs.jquery.com/UI/Tabs
12. Jak zacząć GWT - http://code.google.com/webtoolkit/
13. Nauka programowania Java - http://java.sun.com/developer/technicalArticles/wombat_basics/
==================================================
24.08.2008
Linki -
1. http://zenhabits.net/2008/08/minimalist-fitness-how-to-get-in-lean-shape-with-little-or-no-equipment/
2. http://nettuts.com/javascript-ajax/submit-a-form-without-page-refresh-using-jquery/
3. http://effectize.com/jquery-developer-guide
4. http://developer.yahoo.com/
5. http://www.qsor.pl/artykuly/skrypty_wsh/transformacja_xml_xsl/
6. http://msdn.microsoft.com/en-us/library/ms229745.aspx
7. Bouncy Castle
===================================================
sly =
parchment -
he jumped bail =
torrid =
technocrati zbiera linki autoró, delicious linki odwiedzających
http://www.informit.com/articles/article.aspx?p=1232366&seqNum=1
was wringing its hands back in - załamał
--------
Izolacja od IE:
===============
<!--[if IE]>
<link rel="stylesheet" type="text/css" href="/ie-fix.css />
<![endif]-->
--------
<!--[if IE6]> : allows you target a specific browser version
<!--[if gt IE 5]> : allows you to target all versions after the one you specify
<!--[if lt IE 5]> : allows you to target all versions before the one you specify
<!--[if gte IE7]> : allows you target all versions after and including the one that you specify
<!--[if lte IE6]> : allows you target all versions before and including the one that you specify
--------
.NET for Visual FoxPro
--------
+48601100123 - iPlus
--------
02.08.2008
======================
http://java.about.com/
-
Pożyteczne łącza:
1. Strony z wyszukiwarkami kodu dla programistów. Np (csourcesearch.net, QuickRef.org, Koders, ByteMyCode, Planet Code, and O'Reilly Search, Krugle)
2. Pokaż dane z bazy jako transformowalna strona w kontrolce przeglądarki - codeguru
3. Biblioteka jibu do wsparcia wielowątkowosci
4. Zapis treści dokumentu z MS Word do BLOBa
5. XADes - zawiera również aspekty elementu znacznika czasu -tzn. formaty XAdES-T, XAdES-X oraz XAdES-A
-
http://weblog.infoworld.com/securityadviser/archives/2008/08/user_access_con.html?source=NLC-DAILY&cgd=2008-08-01
http://snippets.dzone.com/posts/show/2439
http://www.hscripts.com/tutorials/index.php
http://bytes.com/forum/thread85596.html
http://thejavamonkey.blogspot.com/2008/07/digital-signatures-in-java-public-key.html
http://forums.sun.com/thread.jspa?threadID=5126495&tstart=0
http://swing-fx.blogspot.com/2008/05/swing-search-engine.html
http://forums.sun.com/thread.jspa?threadID=5317720
http://dotnetslackers.com/XML/re-21255_XAdES_Interop_with_XML_DSIG_as_implemented_by_the_NET_Framework.aspx
http://forums.microsoft.com/MSDN/ShowPost.aspx?PostID=3440889&SiteID=1
http://www.secnewsgroups.net/group/microsoft.public.dotnet.security/topic14281.aspx
http://groups.google.com/group/microsoft.public.dotnet.security/msg/d10a83484f4c19eb
http://groups.google.com/group/microsoft.public.dotnet.security/browse_thread/thread/4bbcbf65a23a5afb/d10a83484f4c19eb
http://forums.microsoft.com/MSDN/ShowPost.aspx?PostID=3173985&SiteID=1
http://www.softwaremaker.net/blog/xadesinteropwithxmldsigasimplementedbythenetframework.aspx
http://snippets.dzone.com/posts/show/2439


Zasoby Javy:

  1. Bezpieczeństwo appletu i podpisywanie:
    1. "Java security evolution and concepts" - http://www.javaworld.com/javaworld/jw-12-2001/jw-1221-jdk4security.html
  1. Podpis cyfrowy w Java:
    1. http://www.openxades.org/
    2. http://docs.oasis-open.org/dss/oasis-dss-1.0-profiles-XAdES-spec-cd-01.pdf
    3. http://xml.coverpages.org/xmlSig.html
    4. http://world.std.com/~dtd/sign_encrypt/sign_encrypt7.html
    5. http://xmlbeans.googlepages.com/
    6. http://sourceforge.net/projects/gdigidoc
    7. http://sourceforge.net/project/showfiles.php?group_id=99569
    8. Koncepcja wykorzystania appletów w zespół z servletem do prezentowania danych pochodzących z wartswy biznesowej (na serwerze) - http://www.javaworld.com/javaworld/jw-05-2002/jw-0524-j2ee.html?page=2
    9. Jak wysyłać dane POST w Javie - http://www.javaworld.com/javatips/jw-javatip34.html?page=2
    10. W tym samym stylu pobieranie zasobu plikowego z internetu - http://www.javaworld.com/javatips/jw-javatip19.html
    11. Forum javaworld na temat bezpieczeństwa - http://www.javaworld.com/javaforums/postlist.php?Cat=2&Board=JavaSecurity
    12. Do przejrzenia:
      1. http://java.sun.com/j2se/1.4.2/docs/tooldocs/windows/keytool.html
      2. http://forums.sun.com/thread.jspa?threadID=660634&messageID=3879820
      3. http://www.linux.com/feature/39427
      4. http://java.sun.com/developer/technicalArticles/xml/dig_signatures/
      5. http://osdir.com/ml/encryption.bouncy-castle.devel/2004-09/msg00046.html
      6. http://forums.java.net/jive/thread.jspa?messageID=247428
      7. http://forums.java.net/jive/thread.jspa?messageID=255470
      8. http://www.java-tips.org/java-ee-tips/xml-digital-signature-api/using-the-java-xml-digital-signatur-2.html
      9. http://java.sun.com/javase/6/docs/technotes/guides/security/xmldsig/XMLDigitalSignature.html
      10. http://www.java2s.com/Code/Jar/wsit/xmldsig.jar.htm
      11. http://coding.derkeiler.com/Archive/Java/comp.lang.java/2004-03/0527.html
      12. http://www.koders.com/java/fidCEFECC0B536138DCFE919C5324844F8D1A0AC068.aspx
      13. http://geekswithblogs.net/DavidBarrett/archive/2008/04/21/121459.aspx
      14. http://www.java2s.com/Code/Jar/wsit/Downloadxmldsigjar.htm
      15. http://www.javaworld.com/javaworld/jw-12-2002/jw-1220-xmlsecurity.html
      16. http://www.javaworld.com/javaworld/jw-10-2002/jw-1011-securexml.html
      17. http://www.javaworld.com/javaworld/jw-06-2005/jw-0627-plugin.html
      18. http://www.javaworld.com/javaworld/jw-03-2003/jw-0321-wssecurity.html
      19. http://www.javaworld.com/javaworld/jw-01-2001/jw-0112-howto.html
      20. http://www.javaworld.com/javaworld/jw-07-2001/jw-0706-webstart.html
      21. http://today.java.net/pub/a/today/2006/11/21/xml-signature-with-jsr-105.html?page=1
  1. Podpis cyfrowy w MS:
    1. http://msdn.microsoft.com/en-us/library/ms229745.aspx
    2. http://msdn.microsoft.com/en-us/library/ms229749.aspx
  1. Podpis cyfrowy w IBM:
    1. http://www.ibm.com/developerworks/java/library/s-digsig.html
    2. http://www.ibm.com/developerworks/library/ws-soa-verifyxml/index.html
    3. http://www.ibm.com/developerworks/edu/ws-dw-ws-understand-web-services4.html?S_TACT=105AGX04&S_CMP=ART
  1. Pobieranie danych z Internetu:
    1. http://www.computing.net/answers/programming/http-post-in-c-/12267.html
    2. http://www.codeproject.com/KB/cs/ScriptBuilder.aspx
    3. http://www.codeproject.com/KB/aspnet/SoftArch5.aspx
    4. http://hdtv.com.pl/


Podstawy podpisu 1
Na podstawie (http://www.javaworld.com/javaworld/jw-12-1998/jw-12-howto.html?page=4)
  1. Key - klucz - informacja służąca do szyfrowania i deszyfrowania danych. Mamy dwa typy kryptografii: 
    1. bazująca na kluczu niejawnych (secret) zwana symetryczną - stosuje jeden typ klucza zarówno do szyfrowania jak i odszyfrowania. Klucz jest wspólny dla odbiorcy i wysyłającego.
    2. bazująca na kluczach publicznych zwana asymetryczną - ma dwa klucze (jeden klucz służy do szyfrowania, drugi do odszyfrowania:
      1. publiczny - (public key)stosowany do potwierdzenia autentyczności (informacja zaszyfrowana kluczem prywatnym danej osoby może być odszyfrowana TYLKO JEJ kluczem publicznym i żadnym innym)
      2. prywatny - (private key) powinnien być znany tylko właścicielowy
  2. Message digest - skrót wiadomości (obrazowo cyfrowy odcisk - digital footprint) - krótki ciąg informacji unikalny dla niej.
  3. Digital signature - podpis cyfrowy. Wyliczony na podstawie Message digest i private key ciąg informacji (zazwyczaj ciąg ten jest znacznie krótszy od orginalnej wiadomości, możnaby podpisać cyfrowo całą wiadomość orginalną ale wymagałoby to znacznej mocy obliczeniowej i czasu). Stanowi potwierdzenie, że dana wiadomość została podpisana przez osobę posiadającą w/w klucz prywatny.
  4. Z uwagi na istniejące i historycznie zaszłe ograniczenia na publikację algorytmów kryptograficznych, twórcy architektury do obsługi w javie kryptografii (JCA - Java Cryptography Architecture) zdecydowali się na zbudowanie jej na koncepcji dostawców usług (providers). JCA jest dostarczana z domyślnymi dostawcami, inne firmy mogą podpiąć własnych dostawców usług kryptograficznych. Dostawca jest pośrednikiem między istniejącą implementacją np. algorytmu MessageDigest a aplikacją.
  5. Kod wygląda mniej więcej tak:
  6.    // The getInstance() method is a static method of the    //  Signature class.  It returns an instance of the    //  installed class that implements the SHA/DSA    //  digital signature algorithm.    Signature signature = Signature.getInstance("SHA/DSA");


Nowości:
  1. o nowego w przeglądarkach nowej generacji. Pojawiły się nowe wersje przeglądarek internetowych (wszystkie w wersji beta). Porównanie wypada słabo. IE 8 - jest to ciężka przeglądarka, ciągnąca w swym balaście wszystkie dobre i złe cechy poprzednich wersji w ramach zgodności wstecznej (aby nie naruszyć istniejących stron napisanych pod konkretną wersję IE). Jest dla starych użytkowników IE i poszerza o nowe możliwości. Chrome jest lekka, ma spartańskie interfejs.Podobne jest podejście do izolacji stron, w obu przeglądarkach każda zakładka to odrębny, niezależny proces. "Like Chrome, IE 8 uses multiple, discrete processes to isolate and protect each tab's contents. However, while Chrome takes a purist approach and literally launches a new process with each opened tab, IE 8 uses more of a hybrid model: It creates multiple instances of the iexplore.exe process but doesn't specifically assign each tab to its own instance. Thus a look at Task Manager under Windows will show an equal or greater number of Chrome instances than running tabs, whereas IE 8 will generate a fewer number of instances -- for example, six copies of iexplore.exe to support 10 discrete tabs -- and share them among the running tabs." Wklejono z <http://www.computerworld.com.au/index.php?id=1560002236&eid=-44>
  2. Powoduje to olbrzymie obciążenie systemu i znaczne zużycie pamięci operacyjnej.
  3. Język F# czyli programowanie funkcjonalne - http://www.computerworld.com.au/index.php?id=1826342097&eid=-301
  4. Jak wystartować z Gears - http://gears.google.com/

  5. Jak pogodzić życie osobiste z zawodowym - http://www.cio.com.au/index.php?id=1361025773&eid=-153



Nie pomijać znaczenia JavaScript
  1. Jak zauważyła Forrest Group jest to pożyteczny język ale ma etykietkę do tworzenia stron internetowych po stronie klienta, czyli nie jest tak popularny.

    Trzeba pamiętać, że aplikacje internetowe to są dwie nogi: strona serwerowa (języki Java, .NET, skryptowe jak Python, PHP, Ruby) i kliencka (JS). Proporcje między nimi decydują o rodzaju i charakterystyka użytkowo-funkcjonalnej aplikacji webowych oraz szybkości działania. Jeżeli przeważa część serwerowa to mamy mocne obciążenie łącza oraz serwera (gro przetwarzania odbywa się na serwerze). Jeżeli przewagę ma część kliencka to serwer działa jako dostawca danych rozpakowywanych i prezentowanych u klienta. Tutaj większą część przetwarzania bierze na siebie komputer klienta odciążając serwer. Do tego dochodzi jakość interpretowania JS (teraz w projektach Mozilli FF 3.1 mówi się o kompilatorze języka TraceMonkey, opartego na badaniach uniwersyteckich, obiecującego radykalne przyśpieszenie działania) oraz sprawność motoru przeglądarki. Ponieważ tak czy inaczej strona internetowa wytworzona na serwerze trafia do punktu docelowego jakim jest przeglądarka to tak naprawdę to ona określa efekt końcowy odbierany przez użytkownika. A jeżeli coś się dzieje w przeglądarce (a powinno, choćby renderowanie strony lub wykonywanie jakieś logiki na strukturze DOM tej strony) to jest ona inteligentna tzn. bierze na siebie wykonywanie pewnych operacji w języku JS. Wniosek - dużo zależy do szybkości pracy motoru przeglądarki i jakości i szybkości interpretowania JS. W tym świetle cieszy pogodzenie tendencji ewolucyjnych z rewolucyjnymi w komitecie zajmującym się pracami nad rozwojem i standaryzacją ECMAScript (JS) - ECMA International Commitee . Wygrała frakcja wersji 3 nad wersją 4, tzn. prostszy język i szybsze wykonywanie się w przeglądarce i urządzeniach mobilnych. Zaowocowało to w nowej wersji 3.1 która nosi nazwę Harmony. Duże znaczenie miała opinia twórców rusztowań Dojo, Scriptaculous i innych.

    W związku z tym zachodzi nowy trend - przetwarzania aplikacji w kontenerze klienckim (np. przeglądarka) natomiast dostęp do zasobów znajdujących się w Internecie poprzez protokół HTTP i jego wyższe warstwy wykorzystujące technologię AJAX. Wszyscy liczący się gracze na rynku aplikacji web2 mają coś w zanadrzu:

    • Adobe - technologię AIR (połączenie odmiany JS - ActionScript i Flasha) - super to wygląda graficzne, wykorzystuje wszystkie dostępne możliwości Windows
    • Google - technologię Gears oraz nową przeglądarkę Chrome, która łączy funkcje tradycyjnej przeglądarki (oczywiście wzbogacając ją o prostotę użycia, integrację z Google Apps, wyszukiwarką, szybkością działania dzięki nowoczesnej maszynie wirtualnej JavaScript korzystającej z innowacji Apple -WebKit i Mozilli-Firefox) z uniwersalnym kontenerem umożliwiającym uruchamianie aplikacji klienckich charakteryzujących się możliwością pracy offline (synchronizacja opóżniona), zapamiętaniem stanu aplikacji u klienta (to już nie jest HTTP bezstanowy) w bazie SQL, wykorzystaniem technologii Gears oraz brakiem paska adresu internetowego. Dodatkowo ma specjalne okno tzw. Application window stwarza to iluzję korzystania jak z aplikacji desktopowej. Uwaga: Chrome używa ciągle starej wersji WebKit, która ma wiele znanych przez hackerów dziur.
    • Mozilla - prace nad technologią Prism (podobnie jak Google)
    • Opera/Yahoo - stosowania widgetów (wihajstrów) pracujących w środowisku maszyny wirtualnej, którą sobie trzeba ściągnąć na początku pracy (potem ewentualne aktualizacje)
    • Microsoft - technologia Silverlight o jej możliwościach przekonuje NBC w przekazach z olimpiady w Pekinie. Kawał potężnej technologii zintergrowanej z platformą .NET i przenaszalnej na inne środowiska oprócz Windows dzięki technologii Mono



wtorek, września 02, 2008

Pomoc o OpenSSL

The Most Common OpenSSL Commands

One of the most versatile SSL tools is OpenSSL which is an open source implementation of the SSL protocol. There are versions of OpenSSL for nearly every platform, including Windows, Linux, and Mac OS X. OpenSSL is commonly used to create the CSR and private key for many different platforms, including Apache. However, it also has hundreds of different functions that allow you to view the details of a CSR or certificate, compare an MD5 hash of the certificate and private key (to make sure they match), verify that a certificate is installed properly on any website, and convert the certificate to a different format. A compiled version of OpenSSL for Windows can be found here.

Below, we have listed the most common OpenSSL commands and their usage:

General OpenSSL Commands

These commands allow you to generate CSRs, Certificates, Private Keys and do other miscellaneous tasks.

  • Generate a new private key and Certificate Signing Request

    openssl req -out CSR.csr -pubkey -new -keyout privateKey.key

  • Generate a certificate signing request (CSR) for an existing private key

    openssl req -out CSR.csr -key privateKey.key -new

  • Generate a certificate signing request based on an existing certificate

    openssl x509 -x509toreq -in MYCRT.crt -out CSR.csr -signkey privateKey.key

  • Generate a self-signed certificate

    openssl req -x509 -nodes -days 365 -newkey rsa:1024 -keyout privateKey.key -out certificate.crt

  • Remove a passphrase from a private key

    openssl rsa -in privateKey.pem -out newPrivateKey.pem

Checking Using OpenSSL

If you need to check the information within a Certificate, CSR or Private Key, use these commands.

  • Check a Certificate Signing Request (CSR)

    openssl req -text -noout -verify -in CSR.csr

  • Check a private key

    openssl rsa -in privateKey.key -check

  • Check a certificate

    openssl x509 -in certificate.crt -text -noout

  • Check a PKCS#12 file (.pfx or .p12)

    openssl pkcs12 -info -in keyStore.p12

Debugging Using OpenSSL

If you are receiving an error that the private doesn't match the certificate or that a certificate that you installed to a site is not trusted, try one of these commands.

  • Check an MD5 hash of the public key to ensure that it matches with what is in a CSR or private key

    openssl x509 -noout -modulus -in certificate.crt | openssl md5
    openssl rsa -noout -modulus -in privateKey.key | openssl md5
    openssl req -noout -modulus -in CSR.csr | openssl md5

  • Check an SSL connection. All the certificates (including Intermediates) should be displayed

    openssl s_client -connect https://www.paypal.com:443

Converting Using OpenSSL

These commands allow you to convert certificates and keys to different formats to make them compatible with specific types of servers or software. For example, you can convert a normal PEM file that would work with Apache to a PFX (PKCS#12) file and use it with Tomcat or IIS.

  • Convert a DER file (.crt .cer .der) to PEM

    openssl x509 -inform der -in certificate.cer -out certificate.pem

  • Convert a PEM file to DER

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

  • Convert a PKCS#12 file (.pfx .p12) containing a private key and certificates to PEM

    openssl pkcs12 -in keyStore.pfx -out keyStore.pem -nodes

    You can add -nocerts to only output the private key or add -nokeys to only output the certificates.

  • Convert a PEM certificate file and a private key to PKCS#12 (.pfx .p12)

    openssl pkcs12 -export -out certificate.pfx -inkey privateKey.txt -in certificate.crt -certfile CACert.crt


Technologie ... co wybrać?

Technologie w JAVA

The Right Java Tool for the Right Job

By Michael Bardash, Gerhard Bayer, Max Dolgicer

Earlier this summer in these columns, we took a high-level view of the Java side in the e-business middleware clash between Microsoft's .NET and Java 2 Extended Edition from Sun Microsystems Inc. and its partners. This month, we look more closely at the relationship between Java servlets and Enterprise JavaBeans (EJBs), and at how the two technologies can be best used separately in some cases and as complements in others.

In the earlier ''Servlets and EJBs: Friends or foes?'' article, we offered some thoughts on the evolution of the middleware platform so far. We also concluded that the phrase ''less is more'' is certainly applicable when it comes to the development of new, component-based e-business applications now that there are just two middleware platforms to choose from -- J2EE and .NET.

In that article, we noted in passing a question that we have been asked repeatedly during the past few years: Should Java servlets or EJBs be used as a foundation for e-business applications?

This is an important question, since the servlet model offers more simplicity than EJBs. The servlet model is also easier for IT developers and managers to comprehend as they get started with the technology. Our opinion is clear. If an application is presentation-centric and does not require support for high-end middleware services -- distributed transactions, persistence, application-level load balancing, state management and asynchronous messaging, among others -- then opting for heavy EJB usage is overkill. However, if an application requires at least a partial list of such high-end middleware services, then EJBs become the only game in town, assuming of course that the customer has selected or is about to select a J2EE-based application server.

Scalability

Both servlets and EJBs scale well. A number of features -- such as server clustering, DB connection pooling and location transparency -- can facilitate scalability.

Each technology -- or rather the products that implement the technologies -- has been built to support each of these concepts. However, servlet scalability is based mostly on proprietary, vendor-created implementations of servlet pools and load-balancing mechanisms, which are not stipulated by the servlet API. On the other hand, the EJB architecture was designed from the beginning with a vision of addressing scalability.

The essential point of distinction here is that while servlets can scale at the server level, EJBs can scale at the architecture level. Server-level scalability depends on specific product features (which, no doubt, are almost universally supported nowadays by best-of-breed products, and are thus sufficiently mature and comprehensive). Reliance on product characteristics rather than on a robust, scalable architecture is a gamble because, in some cases, loads can quickly outgrow product capacity and require emergency re-architecting, which is a very expensive necessity.

Load balancing

Both EJB servers and servlet engines can provide mechanisms for load balancing that include resource pooling, default dispatch mechanisms and entity clustering. While benchmarking results of servlet engines vs. EJB application servers show more or less compatible performance curves under heavy loads, a load-balanced EJB-based application has a better guarantee of operational integrity.

There is no enforcement on an individual servlet design to mandate its guaranteed incorporation into the distributed environment. As a result, load balancing has to be accounted for at design time and thus becomes a condition to proper architecture design and mature vision.

If load balancing is not taken into account, later attempts to introduce new resources create the potential for resource sharing conflicts, breach of transactional guarantees, or for sub-optimal performance caused by custom dispatch decisions or resource locking. On the other hand, EJBs can supply an infrastructure with rich component management capabilities that allow for the plug-and-play-style introduction of new resources.

Business logic hosting

Because servlets have no impositions on their internal structure and therefore have to manage all aspects of their existence explicitly, they attain only a mediocre level of separation between business functionality and cooperation management (such as database connection management calls, for example).

Business logic becomes intermingled with service calls to databases, name servers or other infrastructure services. EJBs, by design, attain a good level of business separation. Another limitation imposed on servlets' capability to host business logic is their responsiveness obligations. Because they operate within an HTTP session, a lengthy calculation -- which may be necessitated by the business functionality -- could time out the user session.

Business agility

EJBs and servlets do not preclude design-level atomization of business services, so application components can be replaced with other components transparently to the overall architecture. However, because of its more flexible cooperation model, an EJB provides a better vehicle to handle paradigm shifts.

For example, if a browser client must be replaced for some reason with a programmatic agent (such as in the case of business process automation), servlets would not be able to handle the change, while an EJB-based solution would require only modest and well-confined modifications.

Integrity

An EJB application is homomorphic throughout: The same component model is utilized for the component hierarchy, and all components are guaranteed to function under the single umbrella of transactional and security services.

In contrast, a servlet-based application is free to agglomerate any technology without restrictions, with the unavoidable risk of creating points of tension, and the consequent need to account for technology blending at the analysis and architecture stages.

High availability

Both EJB application server and servlet engine products are designed to provide high availability of services on the front end. This is achieved through clustering and failover mechanisms that, though differing between implementations, still pursue the same goal with more or less compatible effectiveness.

However, on the back end -- at the level of business logic implementation -- EJBs use advanced component distribution techniques, such as object factories and smart proxies, that are not available to servlets.

Failover

In the case of EJB, a failover mechanism is a prescribed key functionality and is readily available without any additional analysis or design effort. EJB failover is facilitated by automatic persistence guarantees and by automatic failure detection. Servlets have no equivalent mechanisms unless they are coded explicitly.

Deployment

Deployment is not a priority issue for servlets, but in the EJB worldview, deployment is considered to be one of the key elements of application delivery.

For this purpose, EJBs define a whole methodology for defining deployment characteristics that is supported by extensive APIs dealing with environment, deployment descriptors and object properties. As a rule, deployment description is declarative in nature, and the container is capable of adjusting runtime characteristics (such as transaction guarantees) automatically.

Portability

Both servlets and EJBs are published standards that are backed up by reference implementations and product compliance certification programs.

Despite that, vendors choose to introduce non-standard elements that, in their opinion, enhance product functionality. Because of the huge difference in the breadth of coverage and depth of penetration between servlets and EJBs, EJBs more easily fall victim to such enhancements; so, applications developed over different EJB products carry a greater risk of not being completely portable.

Management and administration

Runtime management and administration is a high priority for both EJBs and servlets, and most products supply facilities for component start and stop, configuring operational parameters, event logging and health monitoring.

EJBs supply a runtime environment that enables easier component monitoring and management. Integrating a component into a management infrastructure is a seamless activity with EJBs, whereas with servlets, if it is feasible at all, it requires the use of product-specific APIs.

Development ergonomics

Servlets is a relatively simple standard that requires basic knowledge of Java and HTML, at the most. EJBs, on the other hand, are complex and multifaceted, and require an understanding of the J2EE platform, as well as proficiency with essential computer science fundamentals (such as threading, transacting, object technologies and so on).

It is probably clear at this point to the development world that Enterprise JavaBeans are better suited for enterprise application platforms than pure servlets are. We say ''pure'' servlets to underscore the fact that a complete (though, as explained, not necessarily adequate for certain uses) architecture can be built exclusively upon servlets supplemented with a mix of other Java technologies. In reality, however, there are shades of gray between pure EJB and pure servlet solutions.

First, many servlet engines are embedded into app servers and share a common implementation architecture with EJB servers. This allows vendors to merge the servlet execution environment with the EJB server and thus bring servlet execution under the same failover and load balance guarantees as EJBs.

Second, EJBs by definition declare compatibility with the other J2EE standards, including Java Server Pages (JSP), a technology that aims for the same goals as servlets (though admittedly in a different way). Moreover, JSP uses servlets as an implementation vehicle, as JSPs are compiled and cached as servlets.

If we return to our initial assertion -- that servlets are a narrowly specialized technology that is excellent for delivering dynamic HTML content, and that EJBs are a wide, generalized specification designed to componentize business functionality -- it becomes apparent that the class of enterprise-strength applications dealing with browser-based clients can benefit from both servlet and EJB technologies simultaneously and without inherent conflict.

The browser client initiates an HTTP request that is served by a servlet. Rather than implementing complex business logic, the servlet simply redirects the call, along with parameters and perhaps some identification information, to a session bean. The session bean implements the top-level process flow associated with the call, but delegates specific activities to the specialized entity beans. These serve later as proxies to various resources both inside and outside the application server. Developers should notice that all of the business logic is under EJB container management and that it benefits fully from the rich infrastructure services and container-side management.

It should be noted that this architecture has the inherent flexibility to support not only browser-based clients, but also richer clients (in an intranet scenario). In addition, it can be easily extended to make business functionality available through new interface mechanisms -- for example, Web services or whatever the next great idea might be.

In conclusion, it is easy to see that because servlets are good at exposing Java interfaces to the Web, and EJB is the tool to enable good Java interfaces, there seems to be a perfect match in using a lightweight servlet as a Web-exposing front end to EJB-encapsulated business functionality.

Wklejono z <http://www.adtmag.com/article.aspx?id=6670&amp;page=>


Servlets and EJBs: Friends or foes?

7/1/2002

By Michael Bardash, Gerhard Bayer, Max Dolgicer


Our return to the columns of ADT after a two-year absence comes after a period of intense change -- the demise of the dot.com phenomenon (which almost overnight became the dot.bomb experience), the introduction of too many buzzwords and standards, a plethora of new products that implement -- or just claim to implement -- the latest buzzwords and standards, and much, much more. As always in this business, vendor marketing dollars moved quickly from yesterday's ''du jour'' technologies a couple of years ago and are now promoting J2EE, .NET and, of course, Web services.


However, though the ever-increasing number of buzzwords does create a degree of confusion, one can oftentimes easily follow the common thread and common sense of what we call ''the buzzword evolution.''


A couple of years ago one of our engineers jokingly declared: ''after the invention of the state machine everything in computing is a hack.'' While this is far from reality, many industry veterans would concur that while the buzzwords and standards do change all the time, the basic principles of distributed computing and middleware remain the same. Just follow the trail of ''buzzword evolution'' in the common vocabulary of magazines. IDL (Interface Definition Language) ''got replaced'' by WSDL (Web Services Definition Language); SII (Static Invocation Interface), DII (Dynamic Invocation Interface) and RMI (Remote Method Invocation) ''were taken over'' by SOAP (Simple Object Access Protocol); and finally, Service Oriented Architecture replaced ''Whatever Oriented Architecture'' was in vogue.


Yes, there are more standards now than ever before (skeptics are referred to the list of XML standards governed by the World Wide Web Consortium, or W3C). But at the end of the day, only a few standards matter to developers.


The ''buzzwords and standards'' evolution begs the question of whether middleware choices are more confusing for IT executives and development managers now than they were two years ago. As a consulting company always trying to stay at the front of the middleware revolution (and evolution), taking advantage of many opportunities to implement important projects using a multitude of middleware technologies, we can report that unfortunately, the answer to the question is not a binary yes or no. The good news is that there are some middleware choices that are becoming close to binary. And at least when it comes to the development of brand-new component-based e-business applications there are really only two middleware platforms to choose from -- J2EE and .NET.


However, the reality is that most companies have long focused less on developing new applications than on integrating existing applications. That reality is even more true today as IT budgets undergo more scrutiny than ever before. According to recent monthly CIO surveys conducted by investment firm Morgan Stanley, application integration was cited consistently as a top priority for 2002 and beyond. The bad news is that no single middleware solution has emerged from the pack to become an obvious choice for projects that are focused on application integration. So the technologies and products that enterprises can evaluate today remain very complex and are even more confusing than they were in earlier years. Today, viable integration technologies include Message Oriented Middleware (MOM), Message Brokers, CORBA, J2EE-based application servers and Microsoft's .NET.


As middleware consultants, important questions we hear regularly include: Are the J2EE-based application servers ready to undertake complex EAI projects? And what are the long-term risks associated with the use of proprietary Message Brokers?


In this and future articles we'll try to answer some of the most asked technical questions, including: What are the differences and similarities between J2EE and .NET frameworks? Are J2EE-based application servers ready to become the technology of choice for EAI projects? And what are the key challenges in the development and deployment of J2EE applications?


In this article we tackle a question that we have been asked repeatedly during the past few years. As J2EE-based application servers like BEA's WebLogic Server and IBM's WebSphere gain more widespread acceptance, should Java servlets or Enterprise JavaBeans (EJBs) be used as a foundation for e-business applications? Most of the early Web-based J2EE applications have been developed using servlets as a base for two main reasons. First, the servlet model offers more simplicity than EJBs and is easier for IT developers and managers to comprehend as they get started with the technology. And second, the majority of the early projects are focused on the so-called ''low-hanging fruit,'' or new e-business applications that focus on presentation-centric applications and do not have high developer demands in terms of complexity, scalability, availability, reliability and extensibility.


Meanwhile, the vendors state that the purpose of J2EE application servers is to support high-end enterprise applications and to serve as the new, strategic middleware platform for all application development and deployment. It is therefore important to understand the difference in capabilities of servlets vs. EJBs so that the suitability of one approach over the other can be determined given the requirements of a particular project, the readiness of IT personnel, budgets and realistic time-to-market.


Popular technologies

Both Java servlets and Enterprise JavaBeans are popular technologies, and both can play a prominent role in enterprise architectures. Frequently, suppliers and users view these technologies as competitive, especially for Web-centric applications. Indeed, on the surface, servlets and EJBs can both be used to allow thin clients, such as browsers, PDAs and the like, to access enterprise data. Two variations on a classical architecture -- a thin client (such as a browser) accessing a servlet that is in turn connected to a back-end system or database; and a second variation that shows a client accessing an EJB through a presentation gateway, such as an HTML servlet -- illustrate this contention.


Indeed, from the browser client perspective, there is not much difference between the two technologies -- both bridge between presentation and back-end functionality. And, in many cases, servlets are considered to be a better choice because their coding and deployment requires simpler skills and shorter times than those required for using EJBs, which deal with a whole spectrum of complex issues, including many additional APIs and rules. Of course, when an enterprise-strength architecture is in question, neither the browser client perspective nor the simplification of the development process is a good enough justification for the choice of technology.


The fundamental difference between servlets and EJBs becomes apparent when such essential design objectives as architectural robustness and business agility are brought into focus. Then, issues like scalability, state management, flexibility of entity relationships and richness of the cooperation metaphor start to play a prominent role in the technology selection process. We intend to show why EJB-based architectures can handle such concerns better than servlets-based technologies, and why a clear understanding and recognition of this conclusion is required when new, complex applications are being developed.


We may be giving readers the impression that we are biased toward EJBs as the preferred vehicle for enterprise architectures. However, our view is that EJBs and servlets are orthogonal technologies that, rather than competing directly, are mostly complementary. To compare EJBs and servlets is not like comparing apples to apples. It is not even like comparing apples to oranges -- it is more like comparing apples and oranges to the crates and barrels that are used to store and transport them. This becomes obvious when the essential differences in intent, focus and, if you like, domain philosophy of the two standards are investigated.


Servlets cater primarily to the delivery of dynamic content to browser-based clients. They are narrowly focused on facilitating presentation, such as programmatic translation and preparation of HTML, and on relief from handling lower-level details of HTTP. This is the extent of the role servlets play in the framework of the J2EE standard.


On the other hand, the EJB standard was devised with the vision of a common pattern for component architectures in mind. It deals principally with enabling the development and deployment of a business application as a collection of components into a framework of powerful and comprehensive infrastructure services (which can include Java Database Connectivity (JDBC), Java Transactional Service (JTS)/ Java Transaction API (JTA), Java Messaging Service (JMS) and the like). Rather than prescribing any specific role (such as HTML rendering or HTTP encapsulation), the Enterprise JavaBean component model is a mold for generic business components whose exact specialization is left to the application designer to establish. In other words, the servlets specification is a somewhat narrow standard specialized on the presentation layer of applications, while the EJB standard is a broad enabling technology.


This distinction becomes more apparent when directly comparing the characteristics of EJBs and servlets to evaluate their respective applicability to enterprise architectures.


* A servlet is a faceless Java object. Beyond some features mandated by its base class, it is amorphous and can have arbitrary internal composition. On the other hand, by contract, an EJB is obliged to implement specific interfaces (such as the home interface, activation and deactivation interfaces) and mandatory properties (such as primary key, for example) that promptly tie it into the cooperation environment (the container).


* A servlet has to implement a rigid set of methods with predefined signatures just as Enterprise JavaBeans need to implement a set of methods imposed by the EJB specification to fulfill the contract with the container. However, the EJB can also define arbitrary methods that best suit its business semantics.


* Servlets have very thin support from the environment they are deployed into, which is mostly limited to HTTP-related matters; EJBs enjoy a wide range of powerful and comprehensive infrastructure services that are provided by the container. Examples include the generation and handling of remote interfaces, component factory services, component instance identification, distributed transactions, automatic persistence for Entity Beans and declarative security.


* Basically, servlets are focused on one task: reacting to HTTP requests with HTML responses in a stateless manner (in fact, state may be maintained via an HttpSession object, but it is not comprehensive and requires explicit client cooperation via session cookies). EJB behavior is defined at a higher level of abstraction: EJB method invocation does not stipulate any syntax or semantics to the invocation arguments or to the maintained state.


* By design, the aim of EJB is to segregate business functionality from infrastructure services (such as life cycle management, transaction and security contexts and persistence). Because servlets are not integrated with the J2EE infrastructure services, they encourage application developers to deal with lower-level J2EE APIs directly, and entangle business functionality with logic related to infrastructure services.


* The servlets specification does not address enterprise concerns such as load balancing and failover. On the contrary, inherent scalability and high availability of services is a declared responsibility of the EJB container. (It should be noted that some servlet engines do support clustering and load balancing. Curiously enough, these are the engines that are embedded into EJB application servers such as WebSphere and WebLogic).


In other words, servlets do one thing and do it well -- they provide a shell for the presentation layer of a Web-based application; EJB is a complex framework for implementing widely dissimilar business functionality in a coherent and comprehensive fashion.


Servlets expose; EJBs encapsulate

The other point of distinction between servlets and EJBs is that, in our experience, in the majority of cases, servlets are used to expose business data, whereas EJBs are used to encapsulate business functionality.


A classic use of a servlet would be to parse an HTTP request, access a database for inquiry or update, and to compose an outgoing HTML reply. (A less common use of a servlet would involve passing a serialized Java object between itself and a browser-side applet. This scenario will be discussed later.) For example, a browser may submit a request for an airline schedule, and the servlet will fetch the data from the database and format the reply as an HTML table. Also, the browser may submit a filled form whose elements will be stored by the servlet in a database table. In either case, it is the data, not the behavior, the client is interested in.


Arguably, HTML data-level cooperation achieves a great level of independence between the presentation at a client (in this case the browser) and the processing at the server (the servlet). The interface between the client and the server is primarily concerned with passing data; there is no API specific to any particular business function. The browser client displays HTML returns unconditionally (subject to its validity, of course). Thus, if the servlet implementation is changed to render richer replies (such as embedding sound clips, for example), the client will benefit from this extended business functionality automatically and transparently. However, if the servlet is changed to display, for example, the latest cricket results instead of stock quotes, all the same data will be unconditionally rendered by the client, much to the user's dismay.


In other words, the client's horizon extends all the way to the data and the servlet acts merely as a rendering agent that enables the client to access the database.


Separating the presentation by the browser client and the processing in servlets achieves a higher degree of independence compared to an EJB-based architecture because it does not rely on the strong coupling that the interface of an EJB with rigid business semantics imposes. However, this comes at the cost of compromising business process integrity. This might not be a cause for concern for simple Web browsing interactions, but from an enterprise-strength B2B/B2C perspective, cohesiveness of the end-to-end business process flow must be protected. This objective is best achieved by encapsulating business behavior in services, and service granulation and exposition is precisely the domain of the EJB.


With a typical EJB implementation, a client gains access to business functionality through a presentation gateway, whereby the latter provides a rendering agent for business functionality as opposed to data. Thus, a typical use of an EJB would be for the client to remotely invoke the server-side service, which may or may not result in any data being returned to the client, but which would definitely result in some meaningful processing having taken place at the server side.


Two-tier vs. three-plus tier

Another way to contrast servlets and EJBs is to assert that servlets by intent serve to accommodate a classical two-tier application (where the presentation and data access/business logic tiers are commingled within the servlet and the data store). On the other hand, EJBs tend to three-tier or multitier complex cooperative environments.


Apparently, the flexibility of interpretation built into the servlets standard permits us to break this data-only paradigm easily. Nothing prevents a servlet from being engineered in such a way that it encapsulates a business service. Practically, this can be achieved in a number of ways. For example, instead of only accessing a database, a servlet implementation may invoke back-end functionality that has been written in Java via an RMI call, or a servlet may exchange serialized Java objects with a browser-resident applet. These and other design patterns that turn servlets into business logic capsules are well known and quite popular.


In practice, it has become a common architecture approach to allow servlets to benefit from their amorphous ''anything goes'' internal structure -- or, better yet, their lack of any internal structure. Nothing prevents servlet implementations from internally integrating with a variety of technologies like RMI/CORBA, JNDI, JMS, JTS/JTA and so on; just as no out-of-the-box transparency exists for JDBC -- a main vehicle to access databases from within a servlet -- the constructs within a servlet for all of the above technologies have to be manually coded on a case-by-case basis. Nevertheless, the ability to embed the whole spectrum of Java platform solutions on the client's behalf turns servlets into a powerful middleware mechanism that extends the Java APIs to the Web.


It seems that both the servlets and the EJB technology are suitable platforms for an enterprise application. Furthermore, they both seem suitable for presentation-centric applications that do not require support for ''hard-core'' distributed services such as transactions, load balancing, persistence, state management and message queuing, among others. The use of servlets might be even more appropriate and certainly more straightforward. However, even though it is possible to use servlets for truly distributed applications, such use would be sub-optimal. The reason for this far-reaching statement will be clarified in Part II of this article, in which we will compare these two technologies in more detail. Stay tuned.

Wklejono z <http://www.adtmag.com/print.aspx?id=6465>

Comparing servlets and EJBs

By Michael Bardash, Gerhard Bayer, Max Dolgicer

This table compares and contrasts the servlets and EJBs, and provides a more detailed insight into how they stack up against each other using a set of objective parameters.

APPLICATION TOPOLOGY

Servlets

Web-centric model (client connects via Web server only)

EJBs

* Web-centric model (via presentation gateway, e.g., HTML servlet)

* LAN-based model (clients access services over LAN or WAN via remote method invocations without any intermediary)

* Local (several tiers of services collocated within a single host, either in intra- or inter-process fashion)

Comments

EJB permits for much more flexible deployment topographies. Web server is not a prerequisite.

CLIENT ACCESS

Servlets

HTTP only

EJBs

HTTP

* RMI and/or CORBA

* IIOP HTTP tunneling

* Value-added proprietary protocols such as t3

Comments

HTTP is a stateless protocol optimized for request-reply style text transfer. An attempt to engage it for generic use, such as may be required by common cooperation metaphors like stateful session, involves significant overhead and is not trivial to implement. On the other hand, technologies like RMI and CORBA are specifically optimized for distributed computing and easily account for a variety of cooperation metaphors. HTTP tunneling allows circumventing a firewall in cases when direct client access is precluded.

TRANSACTIONAL SUPPORT

Servlets

* Transactions must be coordinated manually through integration with JTS.

* A client cannot easily pass transaction context to a servlet.

* Attempt to allow a single transaction to spawn multiple servlet invocations is at least non-trivial.

EJBs

* All transaction functions are performed by the container implicitly on behalf of an EJB, including context propagation and transaction demarcation. However, the bean is not precluded from taking full control over transaction management.

* Transaction rules are declarative in nature and can be changed at deployment time.

Comments

Though a servlet can ultimately be made as transactional as an EJB, this attempt will involve significant effort, both at design and development times. EJB strongly relieves these concerns.

SECURITY

Servlets

There is no security mechanism readily available to servlets. Rudimentary access security is managed by the servlet engine in a superficial manner (in most cases, limited to differentiating between trusted and untrusted modes).

EJBs

Comprehensive security mechanism is managed by the server. EJBs are instantiated into security context and service invocations are authorized against access control lists. Security definition is declarative and defined at deployment time.

Comments

In a Web-centric environment, both standards benefit from technologies like SSL and digital certificates. But implementation of these features is not mandated by either standard and is left to the discretion of specific products. Most app servers and servlet engines (especially those embedded in app servers) support an end-to-end Web security model.

PERSISTENCE

Servlets

No specific mechanism exists to provide for servlet persistence, though of course nothing prevents a servlet from implementing persistence on its own by explicitly integrating with JDBC.

EJBs

EJB allows persisting objects automatically. Support for this comes from two angles. Introspecting the bean can automatically generate database schemas. Container-provided life-cycle management automatically passivates and activates objects as needed and provides for synchronization of EJB state with the database.

OBJECT IDENTIFICATION AND CONTEXT ASSOCIATION

Servlets

To identify a Servlet into context (such as in the case of a session context, for example) requires explicit cooperation between the client and the engine. Client-side cookies are needed, and additional coding is required on the server side for session tracking. Integration with a naming service is not possible at the client side, and has to be manually coded at the server side.

EJBs

EJB differentiates between stateless and stateful objects. While the former are created on demand and do not outlive single invocation, the latter are uniquely identified by a primary key, which permits unambiguous context identification.

Comments

EJB benefits from its implicit integration with persistence and naming services. Moreover, while servlets leave the topic to the user's discretion, EJB supplies ground rules and a comprehensive framework for identification of EJBs.

ENVIRONMENT ACCESS

Servlets

Servlets have no access to the runtime environment other than regular Java mechanisms.

EJBs

The EJB container manages environment properties on behalf of individual EJBs. These can be defined at deployment time, allowing for greater deployment flexibility.

Comments

EJB provides better ergonomics of the runtime environment management, an essential part of system administration.

NAMING AND DIRECTORY SERVICES

Servlets

No integration with JNDI except when manually coded. No client-side access to directory services.

EJBs

JNDI is fully integrated into the server and the namespace is managed transparently. EJB provides naming context and automates object registration.

Comments

The servlet client's inability to discriminate its server object is a limiting factor for component-based architectures.

LIFE-CYCLE MANAGEMENT

Servlets

Servlets are bound into the end-user context only for the duration of a single request. Servlet instances are managed by the server only to assure that the configured number of instances of a certain kind has been pooled.

EJBs

EJB instance life span can vary from per-request instantiation to the duration of a session, to the persistence over many user sessions. The persistence mechanism allows bean-based implementations to survive catastrophic session failures and container shutdowns.

STATE MANAGEMENT

Servlets

Servlets do not have any prescribed state management policies.

EJBs

The container cooperates with the EJB to maintain the state. In contrast to servlets, stateful EJBs are required to implement activation/passivation methods to enable the container to invoke them automatically to persist the EJB's state at well-defined points.

Comments

EJBs must comply with the state management contract, which in some scenarios may be perceived as an unnecessary burden. However, a well-articulated and standardized state persistence policy is a definite advantage to application designers.

RESOURCE BINDING

Servlets

The association of a servlet with back-end resources must be hard-coded.

EJBs

Back-end resource access is encapsulated in entity beans that act like resource proxies to the session-level objects.

Comments

To achieve the same level of indirection and encapsulation as available with EJB, servlets have to manually provide for resource management. This may be prohibitively complex, especially when resource management needs to be integrated with transactional and security management.

RESOURCE SHARING

Servlets

Resource locking must be manually implemented and coordinated across servlet instances. It is easy to break resource sharing, as there is no centralized enforcement authority.

EJBs

Resource sharing is managed at the level of entity beans. The container manages access to the entity beans and synchronizes access to them according to the defined sharing policy.

Comments

An EJB resource-sharing mechanism creates an essential foundation for resource load balancing.

RELATIONSHIP MULTIPLICITY

Servlets

The relationship between the client and the servlet is one-to-one only, for the duration of single request.

EJBs

The multiplicity of relationships between client and server-side objects is not defined. The client may reference many entity and/or session beans simultaneously.

Comments

The relationship between client and servlet is inherently damaged by the limitations of the HTTP protocol. However, a number of work-around techniques may be suggested, like having a single servlet to multiplex all types of client requests. The drawbacks of such a scheme are obvious.

DATABASE INTEGRATION

Servlets

Servlets rely on JDBC facilities to pool database connections. This pooling is managed explicitly. SQL statements have to be prepared manually.

EJBs

The database connection pool is managed by the server, according to the deployment time policy. The container manages object persistence. SQL statements can be generated automatically.

INVOCATION ARGUMENTS

Servlets

Servlets require manual marshalling of call arguments from their HTML representation. Analogously, return values have to be embedded in HTML. The Servlet API defines a number of programmatic facilities that assist in this task.

EJBs

EJB invocations do not have fixed signatures, and arguments can be represented as a structure of arbitrary complexity, including, but not limited to HTML strings.

Comments

Direct HTML rendering provided by servlets is a strong advantage for a browser-based client.

THREADING MODEL

Servlets

Servlets do not have any inherent threading or synchronization model. Threading safety is left to the discretion of the developer. A single threading model is devised specifically to ensure that all calls are single-threaded.

EJBs

Bean invocations run in dedicated threads. The container manages thread synchronization. Thread pooling is available for performance optimization.

METAPHOR

Servlets

Servlets essentially support a single metaphor: request-reply. It is possible to identify requests into a client session, but this requires additional design and, because of API limitations, is not a comprehensive solution.

EJBs

EJBs support a wide spectrum of metaphors, including request/reply in both stateless and stateful manner, asynchronous communication through message-driven beans, as well as session and persistent session.

CHAINING

Servlets

Servlets can be chained to each other to process client requests in a sequential manner.

EJBs

An EJB that receives the client request can fan out consequent service invocations.

Please see the related story 'The right Java tool for the right job.'