martes, 24 de junio de 2014

SSL, keystores, truststores and 2-way-SSL

Con esta entrada pretendo aclarar estos conceptos y mostrar algún comando de interés.

SSL: capa de conexión segura, nos permite intercambiar información de forma cifrada a través de la red, dicho de otra forma, no visible para el resto.

El Java KeyStore (JKS) es un repositorio de certificados de confianza (con sus claves privadas). El propósito final es proveer las credenciales.

El TrustStore (JKS) es un repositorio de certificados de confianza (con sus claves publicas). Este sirve, por ejemplo, para negociar la conexión SSL entre el cliente y el servidor. El propósito final es validar las credenciales.

Two-Way SSL: es un método de autenticación donde la aplicación cliente verifica la identidad de la aplicación servidora y luego la servidora verifica la identidad del cliente.

Si hablamos de certificados, debemos aclarar el termino CA que se corresponde con una entidad certificadora (emite y revoca los certificados). Lo primero es confiar en la propia CA para lo que se suele recurrir a la instalación (añadir al truststore) del certificado autofirmado de la CA.


Comandos

Los principales comandos para el manejo de certificados los ofrece el kit keytool de Java.
  • listar certificados en el keystore
    • keytool -list -v -keystore $keystore.jks
  • obtener los certificados del servidor
    • openssl s_client -connect $ip:$port -prexit -showcerts
  • Caducidad de un certificado .pem
    • openssl x509 -in $cert -noout -enddate
  • Información del certificado
    • openssl pkcs12 -in $cert.p12 -info
  • Generar un certificado .pem desde un p.12
    • openssl pkcs12 -in $cert.p12 -out $finalCert.pem
  • Importar un certificado de una CA en un keystore
    • keytool -import -trustcacerts -alias root -file $cacert.crt -keystore $keystore.jks
  • Generar un keystore con un certificado auto-firmado (para pruebas)
    • keytool -genkey -keyalg RSA -alias $selfsignedAlias -keystore $keystore.jks -storepass $password -validity $numberDays -keysize 2048
    • (otra opción) openssl req -new -x509 -sha256 -newkey rsa:2048 -days 365 -nodes -out /path/cert.pem -keyout /path/cert.key



____________________________________________


This blog post I'll try to explain several concepts and show the main commands about SSL.

SSL: Secure Sockets Layer, it makes encryption communication, so our information will not be visible to another person or system.

A Java KeyStore (JKS) is a repository of security certificates (with private keys). The final purpose is to provide the credentials.

A TrustStore (JKS) is a repository of security certificates (with public keys). This is useful for establish a SSL connection between a client and a server. The final purpose is to validate the credentials.

Two-way SSL: is a authentication method where client application verify the identity of the server application and, after that, server verify the identity of the client.

When we speak about certificates, we must considerer the CA, Certificate Authority (who releases and revokes the certificates). The first step is to trust in the CA so you must to install (add to truststore) the CA self-signed certificate.

Commands

The main commands to managament of certificates are offers by the keytool kit of Java.
  • Listing of certificates in the keystore
    • keytool -list -v -keystore $keystore.jks
  • Getting all certificates from the server
    • openssl s_client -connect $ip:$port -prexit -showcerts
  • Getting informatión about the certificate
    • openssl pkcs12 -in $cert.p12 -info
  • Expiration date of a certificate (.pem format)
    • openssl x509 -in $cert -noout -enddate
  • Generating a certificate with format .pem from format p.12
    • openssl pkcs12 -in $cert.p12 -out $finalCert.pem
  • Import a root or intermediate CA certificate to an existing Java keystore
    • keytool -import -trustcacerts -alias root -file $cacert.crt -keystore $keystore.jks
  • Generate a keystore and self-signed certificate (for testing purposes)
    • keytool -genkey -keyalg RSA -alias $selfsignedAlias -keystore $keystore.jks -storepass $password -validity $numberDays -keysize 2048
    • (another option) openssl req -new -x509 -sha256 -newkey rsa:2048 -days 365 -nodes -out /path/cert.pem -keyout /path/cert.key

jueves, 12 de junio de 2014

Mejores ofertas / The best discounts

Hola,

He participado, junto con un compañero, en la creación de una web que permite obtener las mejores ofertas en Rakuten, el nuevo marketplace que viene pegando fuerte. Poco a poco iremos completando la funcionalidad ofrecida y, quizás en un futuro próximo, permitiendo comprar precios de distintos sitios para encontrar el producto mas interesante o que mas haya bajado de precio.

Querría compartirlo con vosotros, por si la página os pudiera ser útil. El sitio se llama:
http://locosporlasrebajas.com/

Cualquier comentario sobre la misma será bien recibido.

_______________________________________________

Hello,

I have participated, with a friend, in the development of a new site with the best discounts of Rakuten, the new marketplace which arrives strong. As soon as posible, we will try to add new functionality and, probably, to compare prices from differents marketplaces so you could find a product with the better price.

I want to share this site with you, perhaps it is useful for somebody. The website is:
http://locosporlasrebajas.com/

Every comment about the website will be thankful.

viernes, 21 de febrero de 2014

Nueva web / New site


Hola a todos, sé que este tema no está relacionado directamente con el desarrollo y la programación, pero a nivel personal he estado trabajando en un nuevo proyecto y me gustaría comentarlo.

Se trata del desarrollo de una página web:
http://articulosparaelcazador.com/

Cualquier comentario sobre la misma será bien recibido.

_______________________________________________

Hello, this article is not directly related with development and programming, but I am involved in a personal proyect and I would like to tell to everyone.

It is about a new website (now there is only Spanish version, sorry for inconveniences):
http://articulosparaelcazador.com/

Every comment about the website will be thankful.

martes, 4 de febrero de 2014

Principales diferencias entre las distintas versiones de Java / Main differences between Java versions


 1.4 

  • assert keyword
    x = 1;
    assert (x != 0);

  • Regular expressions
        Pattern p = Pattern.compile("fish");
    Matcher m = p.matcher("one fish, two fish, red fish, blue fish");
    while (m.find()) {
  /*...*/
    }
 
  • IPv6 support
Se modificaron clases para soportar IPv6, como por ejemplo InetAddress, MulticastSocket, etc.

  • Logging
Properties file with all configuration for logs
  • XML parser and XSLT processor (JAXP)
Transformer xmlTransformer = TransformerFactory.newInstance().newTransformer(
         new StreamSource(new StringReader(xsltResource))
      );
_______________________________________
Document doc = parseFile(xmlFileName);
  Node root = doc.getDocumentElement();
 
  • Integrated security and cryptography extensions (JCE, JSSE, JAAS)
SSLServerSocketFactory sslSrvFact = (SSLServerSocketFactory)                  SSLServerSocketFactory.getDefault();
    s =(SSLServerSocket)sslSrvFact.createServerSocket(port);
    SSLSocket c = (SSLSocket)s.accept();
    OutputStream out = c.getOutputStream();
    InputStream in = c.getInputStream();

  • Preferences API
    Preferences myPreferences = Preferences.systemRoot();
  String value = (String) myPreferences.get(key, defaultValue);

 5 (1.5) 

  • Generics 
List<String> l = new ArrayList<String>();
    l.add("string");
  • Metadada (annotations)
@Override
    @MethodInfo(author = 'Pankaj', comments = 'Main method', date = 'Nov 17 2012', revision = 1)
    public String toString() {
        return 'Overriden toString method';
    }
  • Enhanced for loop
for (String s: stringList) {
        System.out.println(s);
    }

  • Enumerations
public enum Currency {PENNY, NICKLE, DIME, QUARTER};
  • Varargs
void printReport(String header, int... numbers) {
for (int num : numbers) {
System.out.println(num);
}
}
  • Concurrency utilities
Classes like: Semaphore, Executors, SynchronousQueue<E>, ... in java.util.concurrent.

 6 

  • Scripting Language Support 
  • Improved Web Service support through JAX-WS
package javax.xml.ws. It's commonly used by axis2 and cxf.
  • [performance improvements]
  • Upgrade of JAXB to version 2.0
  • Support for pluggable annotations 


     7 

    • String in switch
    • Allowing underscores in numeric literals
    • Catching multiple exception types and rethrowing exceptions with improved type checking
    • Lambda (anonymous function)
        Runnable r2 = () -> System.out.println("Hello world two!");
    • Concurrency utilities

        static final int AVAILABLE_PROCESSORS =   Runtime.getRuntime().availableProcessors();
        final ForkJoinPool pool = new ForkJoinPool(AVAILABLE_PROCESSORS);

     8 

    • Lambda expressions
    printPersonsWithPredicate(
        roster,
        p -> p.getGender() == Person.Sex.MALE
            && p.getAge() >= 18
            && p.getAge() <= 25
    );
    • Allows developers to embed JavaScript code (Project Nashorn)
    • Annotations on Java Types
    List<@NonNull Object>
     
    • Date and Time API
         Package java.time