This site is the archived OWASP Foundation Wiki and is no longer accepting Account Requests.
To view the new OWASP Foundation website, please visit https://owasp.org

Difference between revisions of "Implementacion De Firmas Digitales en Java"

From OWASP
Jump to: navigation, search
(Version Inicial)
 
(References)
 
(13 intermediate revisions by 2 users not shown)
Line 1: Line 1:
== ADVERTENCIA ==
+
== WARNING ==
  
Recientemente Jim Manico trajo a mi atención esta página wiki, el mismo que me pidió que revisara con exactitud. Al hacerlo, me di cuenta de varios errores y áreas de weakness. Últimamente, tengo la intención de revisar esta página (espero que con la ayuda de uno de los propietarios originales), pero no dispongo de tiempo para hacer una revisión completa en este momento. Por lo tanto, resumiré la problemática que observe de esta página y dejándole a usted la decisión de utilizar o no, con estas advertencias.<br>  
+
Jim Manico recently brought to my attention this wiki page, the same who asked me to check exactly. In doing so, I noticed several errors and areas of weakness. Lately, I have the intention to revisit this page (hopefully with the help of one of the original owners), but I do not have time to do a full review at this time. Therefore, I will summarize the problems observed on this page and leaving you the decision to use or not, with these warnings.
 +
<br />
 +
#First, this page does not describe "digital signatures". Rather, it describes a concept known as "digital envelopes", which is a scheme used with objects such as S / MIME. Digital signatures not only encrypt the actual message text, only encrypts the hash of the message text.
 +
#UTF-8 should be used to convert between Java byte strings and arrays to ensure adequate portability across different operating systems.
 +
#The certificate chain must always be validated. In this example, the certificate is self-signed, so this is not relevant and will not be true in the normal case. Furthermore, it should be noted that the self-signed, but acceptable for demonstration purposes certificates is considered a dubious practice for production, as it opens the door to spoofing attacks.
 +
#[http://www.nist.gov/ NIST] now recommends using key size 2048 bits for RSA or DSA keys.
 +
#There is a consistent use of weak algorithms. Here are some suggested replacements:
 +
## Use "RSA/ECB/OAEPWithSHA1AndMGF1Padding" instead of "RSA/ECB/PKCS1Padding".
 +
## Use SHA1 (or better SHA256, SHA1 but at least) instead of MD5 for message digest.
 +
## Use "SHA1withRSA" for the signature algorithm instead of "MD5withRSA".
 +
## When creating a symmetric encryption system to encrypt the message text, use "AES / CBC / PKCS5Padding" and choose an IV random for each text message instead of simply using "AES", ending with "AES / ECB / PKCS5Padding ". ECB mode is extremely weak for a regular plain text. (OK for random bit encryption, however, is well used with RSA.) However, the use CBC and PKCS5Padding could make it vulnerable to "Padding Oracle" attacks, so caution is advised. You can use Encryptor 2.0 ESAPI 's to avoid it. (Note also, this part is the concept of "on digital". If this page was really limited by "digital signatures" would not apply because it would be irrelevant.)
 +
<br />
 +
I hope to get soonest, before cleaning this wiki page. Meanwhile, email me your questions.
 +
<br />
 +
-Kevin Wall
  
#En primer lugar, esta página no describe "firmas digitales". Más bien, describe un concepto conocido como "sobres digitales", que es un esquema utilizado con objetos como S / MIME. Las firmas digitales no sólo cifra el texto real del mensaje, sólo cifra el hash del texto del mensaje.
+
== Overview ==
#Codificación UTF-8, debe utilizarse para realizar conversiones entre cadenas y matrices Java byte para asegurar la portabilidad adecuada a través de diferentes sistemas operativos.
+
 
#La cadena de certificados siempre deben ser validados. En este ejemplo, el certificado es auto firmado, por lo que este no es relevante y no será verdadero en el caso normal. Además, debe tenerse en cuenta que los certificados auto firmados, aunque aceptables para fines de demostración se considera una práctica dudosa para la producción, ya que abre la puerta a ataques de suplantación.
+
This article presents a brief overview of the concepts involved with digital signatures and provides code examples for the application of digital signatures in Java using the [http://docs.oracle.com/javase/6/docs/technotes/guides/security/crypto/CryptoSpec.html Java Cryptography Architecture (JCA)].
#NIST ahora recomienda el uso de 2048 tamaño de la clave de bits para claves RSA o DSA.
 
#Hay un consistente uso de algoritmos débiles. Aquí están algunos reemplazos sugeridos:
 
  
*Utilice "RSA/ECB/OAEPWithSHA1AndMGF1Padding" en lugar de "RSA/ECB/PKCS1Padding".
+
=== What is a digital signature?  ===
*Utilice SHA1 (o mejor SHA256, SHA1 pero por lo menos) en lugar de MD5 para la síntesis del mensaje.
 
*Utilice "SHA1withRSA" para el algoritmo de la firma en lugar de "MD5withRSA".
 
*Al crear un sistema de cifrado simétrico para cifrar el mensaje de texto, utilice "AES/CBC/PKCS5Padding" y elija un IV aleatorio para cada mensaje de texto en lugar de utilizar simplemente "AES", que termina con "AES/ECB/PKCS5Padding". Modo ECB es extremadamente débil para un texto plano regular. (Está bien para el cifrado de bits aleatorios, sin embargo, está bien usar con RSA.) Sin embargo, el uso CBC y PKCS5Padding podría hacer vulnerable a "Padding Oracle" ataques, así que se recomienda tener cuidado. Puede utilizar Encryptor ESAPI 2.0 's para evitarlo. (Tenga en cuenta también, esta parte es del concepto de "sobre digital". Si esta página fuera limitada verdaderamente por "firmas digitales", no se aplicaría, ya que sería irrelevante.)
 
  
Espero sacar tiempo lo más pronto, antes de limpiar esta página wiki. Mientras tanto, envíeme por correo electrónico sus preguntas.
+
A digital signature is a concept that helps to get the non-repudiation of origin (ie, the integrity of Origin) data. By digitally signing the document, the person signing, says he is the author of the document or the signed message.
  
-kevin wall
+
=== Need for Digital Signature  ===
  
== Visión de conjunto ==
+
During the "E" revolution was a need for authentication of critical transactions especially in the financial world. If Alice agreed to transfer $ x to Bob, then there had to be a way for Bob to ensure that:
  
Este artículo presenta un breve resumen de los conceptos involucrados con firmas digitales y proporciona ejemplos de código para la aplicación de firmas digitales en Java utilizando la Arquitectura de Java Cryptography.
+
*It was Alice who performed the transaction and not someone else impersonating Alice (Authentication).
 +
*The amount agreed by Alice is $ x (Integrity).
 +
*Alice could not discuss his statement transaction $ x a Bob (Non-repudiation of origin).
  
=== ¿Qué es una firma digital?  ===
+
These concerns were treated with a solution known as digital signatures. More background information on digital signatures can be found [http://en.wikipedia.org/wiki/Digital_signature here]
  
Una firma digital es un concepto que ayuda a obtener el no repudio de origen (es decir, la Integridad del Origen) de datos. Al firmar digitalmente el documento, la persona que firma, asegura que él es el autor del documento o el mensaje firmado.
+
== Digital signatures in Java using JCA  ==
  
=== Necesidad de Firma Digital  ===
+
Java Cryptography Architecture is a framework for accessing and developing cryptographic functionality for the Java platform. JCA provider implements cryptographic functionality such as digital signatures and message digests. The default JCA provider is SUN JDK 1.4.2.
  
Durante la "E" revolución, fue una necesidad para la autenticación de críticas transacciones sobre todo en el mundo financiero. Si Alice se comprometió a transferir $ x para Bob, entonces tenía que haber una manera para que Bob se asegure de que:
+
=== Security considerations when implementing digital signature ===
  
*Fue Alice quien realizó la transacción y no otra persona suplantando Alice (Autenticación).
+
Two major safety considerations that must be taken into account when applying digital signatures are:
*El monto acordado por Alice es $x (Integridad).
 
*Alicia no pudo discutir su declaración de transacción $x a Bob (No repudio de origen).
 
  
Estas preocupaciones fueron tratadas con una solución conocida como firmas digitales. Más información de fondo sobre las firmas digitales se puede encontrar en [http://en.wikipedia.org/wiki/Digital_signature Wikipedia article]
+
#Sign the message and then encrypt the signed message.
 +
#Sign the hash of the message instead of the entire message.  
  
== Firmas digitales en Java utilizando JCA  ==
+
=== Performance considerations when implementing digital signature ===
  
La Arquitectura de Java Cryptography es un marco para el acceso y el desarrollo de la funcionalidad criptográfica para la plataforma Java. Un proveedor de JCA implementa las funcionalidades criptográficas como firmas digitales y compendios de mensajes. El proveedor predeterminado JCA en JDK 1.4.2 es SUN.  
+
Because asymmetric encryption algorithms such as RSA, DSA are computationally slower than symmetric encryption algorithms such as AES, it is a good practice, encrypt the actual message that is transmitted using a symmetric key algorithm and then encrypt the key that is used in symmetric key algorithm using an asymmetric key algorithm. For example, if you want to convey the message "Hello World Digital Signatures", then this message is first encrypted with a symmetric key, for example, an AES 128-bit key as x7oFaHSPnWxEMiZE/0qYrg and then this key is encrypted with an algorithm as RSA asymmetric key.
  
=== Consideraciones de seguridad al implementar la firma digital  ===
+
== Algorithm to implement digital signature using the RSA algorithm ==
  
Dos consideraciones principales de seguridad que se deben tener en cuenta al aplicar firmas digitales son:
+
The provider RSA Java implementation has a limitation in that encryption can be performed on the data length <= 117 bytes only. If the data is of a length> 117 bytes, it will launch a IllegalBlockSizeException: Data must have more than 117 bytes symmetry there has to be encrypted and then signed.
  
#Firma el mensaje y, a continuación cifrar el mensaje firmado.
+
RSA PKCS # 1 algorithm can only encrypt data size k - 11, where k whose length is one byte and the RSA module 11 is the number of bytes used by the filling PCKS # 1 v1.5. Therefore, if we use an RSA key size of 1024 bits, we could encrypt only 128-11 => 117 bytes of data. There are two options available to encrypt data byte size larger.
#Firma el hash del mensaje en lugar del mensaje completo.  
 
  
=== Consideraciones sobre el rendimiento al implementar la firma digital  ===
+
#We could use an RSA key length> 1024. For example, using 2048 bits, then we could encrypt 256-11 => 245 bytes of data. The disadvantage of this approach is that it would be capable of encoding data size> x bytes (in the above example x is 245).
 +
#Analyze the input data chunks of bytes in size <117 and apply encryption on each piece. The code example of this approach can be found [http://www.aviransplace.com/2004/10/12/using-rsa-encryption-with-java/3/ here].
  
Dado que los algoritmos de cifrado asimétricos, como RSA, DSA son computacionalmente más lento que los algoritmos de cifrado simétricos como AES, es una buena práctica, cifrar el mensaje real que se transmite utilizando un algoritmo de clave simétrica y luego cifrar la clave que se utiliza en el algoritmo de clave simétrica utilizando un algoritmo de clave asimétrica. Por ejemplo: si se quiere transmitir el mensaje "Hola Mundo de Firmas Digitales", entonces primero se cifra este mensaje con una clave simétrica, por ejemplo una clave AES de 128 bits como x7oFaHSPnWxEMiZE/0qYrg y luego se cifra esta clave con un algoritmo de clave asimétrica como RSA.  
+
Both approaches could affect performance since the RSA key larger or approach of [https://en.wikipedia.org/wiki/Divide_and_conquer_algorithms "divide and conquer"] of input bytes are computationally expensive.
  
== Algoritmo para implementar la firma digital utilizando el algoritmo RSA ==
+
=== Algorithm ===
  
El proveedor de la implementación en Java RSA tiene una limitación en que el cifrado se puede realizar sólo en los datos de longitud <= 117 bytes. Si los datos son de longitud > 117 bytes, se lanzaría un IllegalBlockSizeException: Los datos no debe tener más de 117 bytes ahí la simetría tiene que ser cifrados y luego firmados.  
+
With the foregoing, the following algorithm can be used for the implementation of public key cryptography in Java.  
  
El algoritmo RSA PKCS # 1 con relleno sólo puede cifrar los datos de tamaño k - 11 [http://www.rsa.com/rsalabs/node.asp?id=2125 1], donde k cuya longitud es de un octeto del módulo RSA y 11 es la cantidad de bytes utilizados por el relleno PCKS # 1 v1.5. Por lo tanto, si usamos una clave RSA de tamaño de 1024 bits, podríamos cifrar sólo 128 - 11 => 117 bytes de datos. Hay dos opciones disponibles para cifrar los datos de tamaño de byte más grande.
+
#Encrypt the message using a symmetric key
 +
#Concatenate the symmetric key + symmetric hash + hash key message.
 +
#Encrypt the concatenated string with the public key of the recipient.
 +
#Sign data to be transmitted (encrypted symmetric key + the + Hash hash key message).
 +
#Validate the signature.
 +
#Deciphering the message with the recipient's private key to obtain the symmetric key.
 +
#Validate the integrity of the key using the hash key.
 +
#It decipher the real message using the symmetric key that has been decrypted, analyzed and integrity checks.
 +
#Calculate MessageDigest of data.
 +
#Validate whether the message digest decrypted text matches the message digest of the original message.  
  
#Podríamos usar una clave RSA de longitud> 1024. Por ejemplo, si usamos 2048 bits, entonces podríamos cifrar 256-11 => 245 bytes de datos. La desventaja de este enfoque es que no sería capaz de codificar los datos de tamaño> x bytes (en el ejemplo anterior x es 245).
+
=== Commands for key generation  ===
#Analizar los datos de entrada en trozos de bytes de tamaño <117 y aplicar la encriptación en cada trozo. El código de ejemplo de este enfoque se puede encontrar aquí [http://www.aviransplace.com/2004/10/12/using-rsa-encryption-with-java/3/ here].
 
  
Ambos enfoques podrían afectar al rendimiento ya que la clave RSA de mayor tamaño o un enfoque de "divide y vencerás" de bytes de entrada son computacionalmente costosa.
+
prompt# keytool -genkey -alias testsender -keystore testkeystore.ks -keyalg RSA Enter keystore password: testpwd  
 
 
=== Algoritmo  ===
 
 
 
Con las anteriores consideraciones, el algoritmo siguiente puede ser usado para la implementación de la criptografía de clave pública en Java.
 
 
 
#Cifrar el mensaje utilizando una clave simétrica
 
#Concatenar la clave simétrica + hash de clave simétrica + hash del mensaje.
 
#Cifrar la cadena concatenada con la clave pública de los receptores.
 
#Firmar los datos a transmitir (clave simétrica cifrada + Hash de la tecla + Hash del mensaje).
 
#Validar la firma.
 
#Descifrar el mensaje con la clave privada del receptor para obtener la clave simétrica.
 
#Validar la integridad de la clave utilizando el hash de la clave. 
 
#Descifrar el mensaje real usando la clave simétrica que se ha descifrado, se analiza y se comprueba la integridad.
 
#Calcular MessageDigest de datos.
 
#Validar si la síntesis del mensaje del texto descifrado coincide con el resumen de mensaje del mensaje original.
 
 
 
=== Comandos para la generación de claves  ===
 
 
 
prompt# keytool -genkey -alias testsender -keystore testkeystore.ks -keyalg RSA Enter keystore password: testpwd What is your first and last name?
 
  
 +
What is your first and last name?
 
  [Unknown]:  Alice Sender
 
  [Unknown]:  Alice Sender
  
¿Cuál es su nombre y apellido?
+
What is your name?
 
 
 
  [Unknown]:  IT
 
  [Unknown]:  IT
  
¿Cuál es el nombre de la unidad organizativa?  
+
What is the name of the OU?
 
 
 
  [Unknown]:  ABC Inc
 
  [Unknown]:  ABC Inc
  
¿Cuál es el nombre de su organización?
+
What is the name of your organization?
 
 
 
  [Unknown]:  LA
 
  [Unknown]:  LA
  
¿Cuál es el nombre de su ciudad o localidad?
+
What is the name of your city or town?
 
 
 
  [Unknown]:  CA
 
  [Unknown]:  CA
  
¿Cuál es el nombre de su estado o provincia?
+
What is the name of your state or province?
 
 
 
  [Unknown]:  US
 
  [Unknown]:  US
  
Es CN = Alice Sender, OU = IT, O = ABC Inc, L = LA, ST = CA, C = EE.UU. correcto?
+
Is CN = Alice Sender, OU = IT, O = ABC Inc, L = LA, ST = CA, C = EE.UU. correct?
 
 
 
  [no]:  y
 
  [no]:  y
  
Introduzca la contraseña clave para &lt;testsender&gt;  
+
Enter the key password for  &lt;testsender&gt;
 
 
 
  (RETURN if same as keystore password):  send123
 
  (RETURN if same as keystore password):  send123
  
prompt # keytool -genkey -alias testrecv -keystore testkeystore.ks -keyalg RSA Introduzca la contraseña del almacén de claves: testpwd  
+
prompt # keytool -genkey -alias testrecv -keystore testkeystore.ks -keyalg RSA Enter the password of KeyStore: testpwd  
¿Cuál es su nombre y apellido?
 
  
 +
What is your name?
 
  [Unknown]:  Bob Receiver
 
  [Unknown]:  Bob Receiver
  
¿Cuál es el nombre de la unidad organizativa?
+
What is the name of the OU?
 
 
 
  [Unknown]:  HR
 
  [Unknown]:  HR
  
¿Cuál es el nombre de su organización?  
+
What is the name of your organization?
 
 
 
  [Unknown]:  ABC Inc
 
  [Unknown]:  ABC Inc
  
¿Cuál es el nombre de su ciudad o localidad?
+
What is the name of your city or town?
 
 
 
  [Unknown]:  SFO
 
  [Unknown]:  SFO
  
¿Cuál es el nombre de su estado o provincia?  
+
What is the name of your state or province?
 
 
 
  [Unknown]:  CA
 
  [Unknown]:  CA
  
¿Qué es el código de país de dos letras para esta unidad?  
+
What is the country code of two letters for this unit?
 
 
 
  [Unknown]:  US
 
  [Unknown]:  US
  
Es CN = Bob receptor, OU = HR, O = ABC Inc, L = SFO, ST = CA, C = EE.UU. correcto?  
+
Is CN = Bob receptor, OU = HR, O = ABC Inc, L = SFO, ST = CA, C = EE.UU. correct?  
 
 
 
  [no]:  y
 
  [no]:  y
  
Introduzca la contraseña clave para &lt;testrecv&gt;  
+
Enter the key password for &lt;testrecv&gt;  
 
 
 
  (RETURN if same as keystore password):  recv123
 
  (RETURN if same as keystore password):  recv123
  
=== Ejemplo de Código ===
+
=== Code Example ===
  
 
==== PublicKeyCryptography.java  ====
 
==== PublicKeyCryptography.java  ====
Line 152: Line 138:
 
import java.security.cert.*;
 
import java.security.cert.*;
 
import javax.crypto.*;
 
import javax.crypto.*;
 +
 
import sun.misc.BASE64Encoder;
 
import sun.misc.BASE64Encoder;
 
import sun.misc.BASE64Decoder;
 
import sun.misc.BASE64Decoder;
  
 
+
/ **
/**
 
 
  *  
 
  *  
 
  * @author Joe Prasanna Kumar
 
  * @author Joe Prasanna Kumar
 
  *  
 
  *  
  * 1. Cifrar los datos utilizando una clave simétrica
+
  * 1. Encrypt data using a symmetric key
  * 2. Cifrar la clave simétrica con la clave pública Receptores
+
  * 2. Encrypt the symmetric key with the public key Receivers
  * 3. Crear un resumen del mensaje de los datos a transmitir
+
  * 3. Create a message digest of the data to be transmitted
  * 4. Firma el mensaje a transmitir
+
  * 4. Sign the message to be transmitted
  * 5. Envíe los datos a través de un canal no seguro
+
  * 5. Send the data through a nonsecure channel
  * 6. Validar la firma
+
  * 6. Validate signature
  * 7. Descifrar el mensaje usando la llave privada Pets para obtener la clave simétrica
+
  * 7. Decoding the message using the private key Pets for the symmetric key
  * 8. Descifrar los datos usando la clave simétrica
+
  * 8. Deciphering the data using the symmetric key
  * 9. Calcule MessageDigest de datos + mensaje firmado
+
  * 9. Calculate MessageDigest signed message data +
  * 10.Valide si la síntesis del mensaje del texto descifrado coincide con el resumen de mensaje del mensaje original  
+
  * 10.Valide if the text message digest matches the decrypted message digest of the original message
*
 
 
  */
 
  */
  
 
public class PublicKeyCryptography {
 
public class PublicKeyCryptography {
  
/**
 
* @param args
 
*/
 
 
public static void main(String[] args) {
 
public static void main(String[] args) {
 
 
Line 201: Line 183:
 
     fis.close();
 
     fis.close();
 
      
 
      
// 2.2 Creación de un certificado X509 del receptor
+
// 2.2 Creación de un certificado X509 del receptor
 
     X509Certificate recvcert&nbsp;;
 
     X509Certificate recvcert&nbsp;;
 
     MessageDigest md = MessageDigest.getInstance("MD5");
 
     MessageDigest md = MessageDigest.getInstance("MD5");
Line 221: Line 203:
 
             }
 
             }
 
 
    // 3.1 Mensaje que se Firmado = clave secreta cifrada + MAC de los datos a transmitir
+
// 3.1 Mensaje que se Firmado = clave secreta cifrada + MAC de los datos a transmitir
 
String strMsgToSign = strSenbyteEncryptWithPublicKey + "|" + strMDofDataToTransmit;
 
String strMsgToSign = strSenbyteEncryptWithPublicKey + "|" + strMDofDataToTransmit;
 
      
 
      
 
     // 4. Firma el mensaje
 
     // 4. Firma el mensaje
    // 4.1 Obtener la clave privada del remitente desde el almacén de claves, proporcionando la contraseña establecida para la llave privada mientras se crea las llaves usados.
+
// 4.1 Obtener la clave privada del remitente desde el almacén de claves, proporcionando la contraseña establecida para la llave privada mientras se crea las llaves usados.
 
char[] keypassword = "send123".toCharArray();
 
char[] keypassword = "send123".toCharArray();
 
     Key myKey =  ks.getKey("testsender", keypassword);
 
     Key myKey =  ks.getKey("testsender", keypassword);
Line 310: Line 292:
  
 
}
 
}
</pre>  
+
</pre>
 +
 
 
==== SymmetricEncrypt.java  ====
 
==== SymmetricEncrypt.java  ====
 
<pre>package org.owasp.crypto;
 
<pre>package org.owasp.crypto;
Line 540: Line 523:
 
}
 
}
 
}
 
}
</pre>  
+
</pre>
== Referencias ==
+
 
 +
== References ==
  
 
#Computer Security Arts and Science – Matt Bishop  
 
#Computer Security Arts and Science – Matt Bishop  
 
#Core Security Patterns – Christopher Steele, Ray Lai and Ramesh Nagappan
 
#Core Security Patterns – Christopher Steele, Ray Lai and Ramesh Nagappan
  
[[Category:OWASP_Java_Project]]
+
[[Category:Java]]
  
  
'''Aplicaciones en Ambientes Libres'''
+
'''Aplications in Free Environments'''
  
 
  '''Tutor:'''  Ing. Tito Armas
 
  '''Tutor:'''  Ing. Tito Armas
  
  '''Traductoroas:''' Bravo Maria Jose y Portilla Maria Fernanda 2012
+
  '''Translator:''' Bravo Maria Jose and Portilla Maria Fernanda 2012

Latest revision as of 21:23, 25 May 2016

WARNING

Jim Manico recently brought to my attention this wiki page, the same who asked me to check exactly. In doing so, I noticed several errors and areas of weakness. Lately, I have the intention to revisit this page (hopefully with the help of one of the original owners), but I do not have time to do a full review at this time. Therefore, I will summarize the problems observed on this page and leaving you the decision to use or not, with these warnings.

  1. First, this page does not describe "digital signatures". Rather, it describes a concept known as "digital envelopes", which is a scheme used with objects such as S / MIME. Digital signatures not only encrypt the actual message text, only encrypts the hash of the message text.
  2. UTF-8 should be used to convert between Java byte strings and arrays to ensure adequate portability across different operating systems.
  3. The certificate chain must always be validated. In this example, the certificate is self-signed, so this is not relevant and will not be true in the normal case. Furthermore, it should be noted that the self-signed, but acceptable for demonstration purposes certificates is considered a dubious practice for production, as it opens the door to spoofing attacks.
  4. NIST now recommends using key size 2048 bits for RSA or DSA keys.
  5. There is a consistent use of weak algorithms. Here are some suggested replacements:
    1. Use "RSA/ECB/OAEPWithSHA1AndMGF1Padding" instead of "RSA/ECB/PKCS1Padding".
    2. Use SHA1 (or better SHA256, SHA1 but at least) instead of MD5 for message digest.
    3. Use "SHA1withRSA" for the signature algorithm instead of "MD5withRSA".
    4. When creating a symmetric encryption system to encrypt the message text, use "AES / CBC / PKCS5Padding" and choose an IV random for each text message instead of simply using "AES", ending with "AES / ECB / PKCS5Padding ". ECB mode is extremely weak for a regular plain text. (OK for random bit encryption, however, is well used with RSA.) However, the use CBC and PKCS5Padding could make it vulnerable to "Padding Oracle" attacks, so caution is advised. You can use Encryptor 2.0 ESAPI 's to avoid it. (Note also, this part is the concept of "on digital". If this page was really limited by "digital signatures" would not apply because it would be irrelevant.)


I hope to get soonest, before cleaning this wiki page. Meanwhile, email me your questions.
-Kevin Wall

Overview

This article presents a brief overview of the concepts involved with digital signatures and provides code examples for the application of digital signatures in Java using the Java Cryptography Architecture (JCA).

What is a digital signature?

A digital signature is a concept that helps to get the non-repudiation of origin (ie, the integrity of Origin) data. By digitally signing the document, the person signing, says he is the author of the document or the signed message.

Need for Digital Signature

During the "E" revolution was a need for authentication of critical transactions especially in the financial world. If Alice agreed to transfer $ x to Bob, then there had to be a way for Bob to ensure that:

  • It was Alice who performed the transaction and not someone else impersonating Alice (Authentication).
  • The amount agreed by Alice is $ x (Integrity).
  • Alice could not discuss his statement transaction $ x a Bob (Non-repudiation of origin).

These concerns were treated with a solution known as digital signatures. More background information on digital signatures can be found here

Digital signatures in Java using JCA

Java Cryptography Architecture is a framework for accessing and developing cryptographic functionality for the Java platform. JCA provider implements cryptographic functionality such as digital signatures and message digests. The default JCA provider is SUN JDK 1.4.2.

Security considerations when implementing digital signature

Two major safety considerations that must be taken into account when applying digital signatures are:

  1. Sign the message and then encrypt the signed message.
  2. Sign the hash of the message instead of the entire message.

Performance considerations when implementing digital signature

Because asymmetric encryption algorithms such as RSA, DSA are computationally slower than symmetric encryption algorithms such as AES, it is a good practice, encrypt the actual message that is transmitted using a symmetric key algorithm and then encrypt the key that is used in symmetric key algorithm using an asymmetric key algorithm. For example, if you want to convey the message "Hello World Digital Signatures", then this message is first encrypted with a symmetric key, for example, an AES 128-bit key as x7oFaHSPnWxEMiZE/0qYrg and then this key is encrypted with an algorithm as RSA asymmetric key.

Algorithm to implement digital signature using the RSA algorithm

The provider RSA Java implementation has a limitation in that encryption can be performed on the data length <= 117 bytes only. If the data is of a length> 117 bytes, it will launch a IllegalBlockSizeException: Data must have more than 117 bytes symmetry there has to be encrypted and then signed.

RSA PKCS # 1 algorithm can only encrypt data size k - 11, where k whose length is one byte and the RSA module 11 is the number of bytes used by the filling PCKS # 1 v1.5. Therefore, if we use an RSA key size of 1024 bits, we could encrypt only 128-11 => 117 bytes of data. There are two options available to encrypt data byte size larger.

  1. We could use an RSA key length> 1024. For example, using 2048 bits, then we could encrypt 256-11 => 245 bytes of data. The disadvantage of this approach is that it would be capable of encoding data size> x bytes (in the above example x is 245).
  2. Analyze the input data chunks of bytes in size <117 and apply encryption on each piece. The code example of this approach can be found here.

Both approaches could affect performance since the RSA key larger or approach of "divide and conquer" of input bytes are computationally expensive.

Algorithm

With the foregoing, the following algorithm can be used for the implementation of public key cryptography in Java.

  1. Encrypt the message using a symmetric key
  2. Concatenate the symmetric key + symmetric hash + hash key message.
  3. Encrypt the concatenated string with the public key of the recipient.
  4. Sign data to be transmitted (encrypted symmetric key + the + Hash hash key message).
  5. Validate the signature.
  6. Deciphering the message with the recipient's private key to obtain the symmetric key.
  7. Validate the integrity of the key using the hash key.
  8. It decipher the real message using the symmetric key that has been decrypted, analyzed and integrity checks.
  9. Calculate MessageDigest of data.
  10. Validate whether the message digest decrypted text matches the message digest of the original message.

Commands for key generation

prompt# keytool -genkey -alias testsender -keystore testkeystore.ks -keyalg RSA Enter keystore password: testpwd

What is your first and last name?

[Unknown]:  Alice Sender

What is your name?

[Unknown]:  IT

What is the name of the OU?

[Unknown]:  ABC Inc

What is the name of your organization?

[Unknown]:  LA

What is the name of your city or town?

[Unknown]:  CA

What is the name of your state or province?

[Unknown]:  US

Is CN = Alice Sender, OU = IT, O = ABC Inc, L = LA, ST = CA, C = EE.UU. correct?

[no]:  y

Enter the key password for <testsender>

(RETURN if same as keystore password):  send123

prompt # keytool -genkey -alias testrecv -keystore testkeystore.ks -keyalg RSA Enter the password of KeyStore: testpwd

What is your name?

[Unknown]:  Bob Receiver

What is the name of the OU?

[Unknown]:  HR

What is the name of your organization?

[Unknown]:  ABC Inc

What is the name of your city or town?

[Unknown]:  SFO

What is the name of your state or province?

[Unknown]:  CA

What is the country code of two letters for this unit?

[Unknown]:  US

Is CN = Bob receptor, OU = HR, O = ABC Inc, L = SFO, ST = CA, C = EE.UU. correct?

[no]:  y

Enter the key password for <testrecv>

(RETURN if same as keystore password):  recv123

Code Example

PublicKeyCryptography.java

package org.owasp.crypto;

import java.security.*;
import java.security.cert.*;
import javax.crypto.*;

import sun.misc.BASE64Encoder;
import sun.misc.BASE64Decoder;

/ **
 * 
 * @author Joe Prasanna Kumar
 * 
 * 1. Encrypt data using a symmetric key 
 * 2. Encrypt the symmetric key with the public key Receivers 
 * 3. Create a message digest of the data to be transmitted 
 * 4. Sign the message to be transmitted 
 * 5. Send the data through a nonsecure channel 
 * 6. Validate signature
 * 7. Decoding the message using the private key Pets for the symmetric key 
 * 8. Deciphering the data using the symmetric key 
 * 9. Calculate MessageDigest signed message data +
 * 10.Valide if the text message digest matches the decrypted message digest of the original message 
 */

public class PublicKeyCryptography {

	public static void main(String[] args) {
		
	SymmetricEncrypt encryptUtil = new SymmetricEncrypt();
	String strDataToEncrypt = "Hello World";
	byte[] byteDataToTransmit = strDataToEncrypt.getBytes();

	// Generación de un SecretKey para el cifrado simétrico
	SecretKey senderSecretKey = SymmetricEncrypt.getSecret();
	
	//1. Cifrar los datos utilizando una clave simétrica
	byte[] byteCipherText = encryptUtil.encryptData(byteDataToTransmit,senderSecretKey,"AES");
	String strCipherText = new BASE64Encoder().encode(byteCipherText);
	
	
	//2. Cifrar la clave simétrica con la clave pública 
	try{
		// 2.1 Especifique el almacén de claves que se haya importado el certificado Receptores
	KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
	char [] password = "testpwd".toCharArray();
	java.io.FileInputStream fis = new java.io.FileInputStream("/home/Joebi/workspace/OWASP_Crypto/org/owasp/crypto/testkeystore.ks");
    ks.load(fis, password);
    fis.close();
    
		// 2.2 Creación de un certificado X509 del receptor
    X509Certificate recvcert ;
    MessageDigest md = MessageDigest.getInstance("MD5");
    recvcert = (X509Certificate)ks.getCertificate("testrecv");
    // 2.3 Obtención de la llave pública de los certificados
    PublicKey pubKeyReceiver = recvcert.getPublicKey();
    
    // 2.4 Cifrado de la SecretKey con la clave pública Receptores
    byte[] byteEncryptWithPublicKey = encryptUtil.encryptData(senderSecretKey.getEncoded(),pubKeyReceiver,"RSA/ECB/PKCS1Padding");
    String strSenbyteEncryptWithPublicKey = new BASE64Encoder().encode(byteEncryptWithPublicKey);
        
    // 3. Crear un resumen del mensaje de los datos a transmitir
    md.update(byteDataToTransmit);
	byte byteMDofDataToTransmit[] = md.digest();
	
	String strMDofDataToTransmit = new String();
	for (int i = 0; i < byteMDofDataToTransmit.length; i++){
		strMDofDataToTransmit = strMDofDataToTransmit + Integer.toHexString((int)byteMDofDataToTransmit[i] & 0xFF) ;
             }
	
	// 3.1 Mensaje que se Firmado = clave secreta cifrada + MAC de los datos a transmitir
	String strMsgToSign = strSenbyteEncryptWithPublicKey + "|" + strMDofDataToTransmit;
    
    // 4. Firma el mensaje
	// 4.1 Obtener la clave privada del remitente desde el almacén de claves, proporcionando la contraseña establecida para la llave privada mientras se crea las llaves usados.
	char[] keypassword = "send123".toCharArray();
    Key myKey =  ks.getKey("testsender", keypassword);
    PrivateKey myPrivateKey = (PrivateKey)myKey;
    
    // 4.2 Firmar el mensaje
    Signature mySign = Signature.getInstance("MD5withRSA");
    mySign.initSign(myPrivateKey);
    mySign.update(strMsgToSign.getBytes());
    byte[] byteSignedData = mySign.sign();
        
	// 5. Los valores byteSignedData (la firma) y strMsgToSign (los datos que se firmó) se pueden enviar a través del receptor
	
	// 6. Validar la firma
    // 6.1 Extraer la clave pública de su certificado de remitentes
	X509Certificate sendercert ;
	sendercert = (X509Certificate)ks.getCertificate("testsender");
    PublicKey pubKeySender = sendercert.getPublicKey();
    // 6.2 Verificar la Firma
    Signature myVerifySign = Signature.getInstance("MD5withRSA");
    myVerifySign.initVerify(pubKeySender);
    myVerifySign.update(strMsgToSign.getBytes());
    
    boolean verifySign = myVerifySign.verify(byteSignedData);
    if (verifySign == false)
    {
    	System.out.println(" Error in validating Signature ");
    }
    
    else
    	System.out.println(" Successfully validated Signature ");

    // 7. Descifrar el mensaje usando la llave privada Pets para obtener la clave simétrica
    char[] recvpassword = "recv123".toCharArray();
    Key recvKey =  ks.getKey("testrecv", recvpassword);
    PrivateKey recvPrivateKey = (PrivateKey)recvKey;
    
    // Analizar el MessageDigest y el valor cifrado
    String strRecvSignedData = new String (byteSignedData);
    String[] strRecvSignedDataArray = new String [10];
    strRecvSignedDataArray = strMsgToSign.split("|");
    int intindexofsep = strMsgToSign.indexOf("|");
    String strEncryptWithPublicKey = strMsgToSign.substring(0,intindexofsep);
    String strHashOfData = strMsgToSign.substring(intindexofsep+1);

    // Descifrado para obtener la clave simétrica
    byte[] bytestrEncryptWithPublicKey = new BASE64Decoder().decodeBuffer(strEncryptWithPublicKey);
    byte[] byteDecryptWithPrivateKey = encryptUtil.decryptData(byteEncryptWithPublicKey,recvPrivateKey,"RSA/ECB/PKCS1Padding");
    
    // 8. Descifrar los datos usando la clave simétrica
    javax.crypto.spec.SecretKeySpec secretKeySpecDecrypted = new javax.crypto.spec.SecretKeySpec(byteDecryptWithPrivateKey,"AES");
    byte[] byteDecryptText = encryptUtil.decryptData(byteCipherText,secretKeySpecDecrypted,"AES");
    String strDecryptedText = new String(byteDecryptText);
    System.out.println(" Decrypted data is " +strDecryptedText);
    
    // 9. Calcule MessageDigest de datos + mensaje firmado
    MessageDigest recvmd = MessageDigest.getInstance("MD5");
    recvmd.update(byteDecryptText);
	byte byteHashOfRecvSignedData[] = recvmd.digest();

	String strHashOfRecvSignedData = new String();
		
	for (int i = 0; i < byteHashOfRecvSignedData.length; i++){
		strHashOfRecvSignedData = strHashOfRecvSignedData + Integer.toHexString((int)byteHashOfRecvSignedData[i] & 0xFF) ;
             }
	// 10. Validar si la síntesis del mensaje del texto coincide con el mensaje descifrado 
   Digest of the Original Message

	if (!strHashOfRecvSignedData.equals(strHashOfData))
	{
		System.out.println(" Message has been tampered ");
	}
	
	}
	
	catch(Exception exp)
	{
		System.out.println(" Exception caught " + exp);
		exp.printStackTrace();
	}
	
	
	}

}

SymmetricEncrypt.java

package org.owasp.crypto;

import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.Cipher;
import java.security.Key;

import java.security.NoSuchAlgorithmException;
import java.security.InvalidKeyException;
import java.security.InvalidAlgorithmParameterException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.BadPaddingException;
import javax.crypto.IllegalBlockSizeException;

import sun.misc.BASE64Encoder;

/**
 * @author Joe Prasanna Kumar
 * Este programa ofrece las funcionalidades criptográficas siguientes
 * 1. Cifrado con AES
 * 2. El descifrado con AES
 *
 * Algoritmo de alto nivel:
 * 1. Generar una clave DES (especificar el tamaño de la clave durante esta fase)
 * 2. Cree el Cipher
 * 3. Para cifrar: Inicializar el cifrado para el cifrado
 * 4. Para descifrar: Inicializar el cifrado para descifrar
 * 
 * 
 */

public class SymmetricEncrypt {
			
		String strDataToEncrypt = new String();
		String strCipherText = new String();
		String strDecryptedText = new String();
		static KeyGenerator keyGen;
		private static String strHexVal = "0123456789abcdef";

		public static SecretKey getSecret(){
		/**
		 *  Paso 1. Generación de una clave AES mediante keygenerator 
		 *  		Inicializa el tamaño de clave de 128
		 * 
		 */
			
			try{
				keyGen = KeyGenerator.getInstance("AES");
				keyGen.init(128);

				}
					
			catch(Exception exp)
			{
				System.out.println(" Exception inside constructor " +exp);
			}
			
			SecretKey secretKey = keyGen.generateKey();
			return secretKey;
		}
		
		/**
		 *  Paso 2. Crear un sistema de cifrado mediante la especificación de los siguientes parámetros 
		 * 			a. Nombre del algoritmo - aquí es AES 
		 */
		
		
		public byte[] encryptData(byte[] byteDataToEncrypt, Key secretKey, String Algorithm) {
			byte[] byteCipherText = new byte[200];
			
			try {
			Cipher aesCipher = Cipher.getInstance(Algorithm);
		
		/**
		 *  Paso 3. Inicialice el cifrado para el cifrado 
		 */
			if(Algorithm.equals("AES")){
				aesCipher.init(Cipher.ENCRYPT_MODE,secretKey,aesCipher.getParameters());
				}
				else if(Algorithm.equals("RSA/ECB/PKCS1Padding")){
				aesCipher.init(Cipher.ENCRYPT_MODE,secretKey);
				} 
				
		/**
		 *  Paso 4. Cifrar los datos
		 *  		1. Declarar / inicializar los datos. Aquí los datos son de tipo String 
		 *  		2. Convertir el texto de entrada a Bytes
		 *  		3. Cifrado de los bytes, utilizando el método doFinal
		 */
		byteCipherText = aesCipher.doFinal(byteDataToEncrypt); 
		strCipherText = new BASE64Encoder().encode(byteCipherText);

			}
			
			catch (NoSuchAlgorithmException noSuchAlgo)
			{
				System.out.println(" No Such Algorithm exists " + noSuchAlgo);
			}
			
				catch (NoSuchPaddingException noSuchPad)
				{
					System.out.println(" No Such Padding exists " + noSuchPad);
				}
			
					catch (InvalidKeyException invalidKey)
					{
						System.out.println(" Invalid Key " + invalidKey);
					}
					
					catch (BadPaddingException badPadding)
					{
						System.out.println(" Bad Padding " + badPadding);
					}
					
					catch (IllegalBlockSizeException illegalBlockSize)
					{
						System.out.println(" Illegal Block Size " + illegalBlockSize);
						illegalBlockSize.printStackTrace();
					}
					catch (Exception exp)
					{
						exp.printStackTrace();
					}
					
		return byteCipherText;
		}
		/**
		 *  Paso 5. Descifrar los datos
		 *  		1. Inicialice el cifrado para descifrar 
		 *  		2. Descifrar los bytes cifrados utilizando el método doFinal 
		 */
		
		public byte[] decryptData(byte[] byteCipherText, Key secretKey, String Algorithm) {
			byte[] byteDecryptedText = new byte[200];
						
			try{	
		Cipher aesCipher = Cipher.getInstance(Algorithm);
		if(Algorithm.equals("AES")){
		aesCipher.init(Cipher.DECRYPT_MODE,secretKey,aesCipher.getParameters());
		}
		else if(Algorithm.equals("RSA/ECB/PKCS1Padding")){
		aesCipher.init(Cipher.DECRYPT_MODE,secretKey);
		} 
		
		byteDecryptedText = aesCipher.doFinal(byteCipherText);
		strDecryptedText = new String(byteDecryptedText);
			}
		
		catch (NoSuchAlgorithmException noSuchAlgo)
		{
			System.out.println(" No Such Algorithm exists " + noSuchAlgo);
		}
		
			catch (NoSuchPaddingException noSuchPad)
			{
				System.out.println(" No Such Padding exists " + noSuchPad);
			}
		
				catch (InvalidKeyException invalidKey)
				{
					System.out.println(" Invalid Key " + invalidKey);
					invalidKey.printStackTrace();
				}
				
				catch (BadPaddingException badPadding)
				{
					System.out.println(" Bad Padding " + badPadding);
					badPadding.printStackTrace();
				}
				
				catch (IllegalBlockSizeException illegalBlockSize)
				{
					System.out.println(" Illegal Block Size " + illegalBlockSize);
					illegalBlockSize.printStackTrace();
				}
				
				catch (InvalidAlgorithmParameterException invalidParam)
				{
					System.out.println(" Invalid Parameter " + invalidParam);
				}
	
		return byteDecryptedText;
		}
		
		
		public static byte[] convertStringToByteArray(String strInput) {
			strInput = strInput.toLowerCase();
			byte[] byteConverted = new byte[(strInput.length() + 1) / 2];
			int j = 0;
			int interimVal;
			int nibble = -1;

			for (int i = 0; i < strInput.length(); ++i) {
				interimVal = strHexVal.indexOf(strInput.charAt(i));
				if (interimVal >= 0) {
					if (nibble < 0) {
						nibble = interimVal;
					} else {
						byteConverted[j++] = (byte) ((nibble << 4) + interimVal);
						nibble = -1;
					}
				}
			}

			if (nibble >= 0) {
				byteConverted[j++] = (byte) (nibble << 4);
			}

			if (j < byteConverted.length) {
				byte[] byteTemp = new byte[j];
				System.arraycopy(byteConverted, 0, byteTemp, 0, j);
				byteConverted = byteTemp;
			}

			return byteConverted;
		}
		
		public static String convertByteArrayToString(byte[] block) {
			StringBuffer buf = new StringBuffer();

			for (int i = 0; i < block.length; ++i) {
				buf.append(strHexVal.charAt((block[i] >>> 4) & 0xf));
				buf.append(strHexVal.charAt(block[i] & 0xf));
			}

			return buf.toString();
		}
}

References

  1. Computer Security Arts and Science – Matt Bishop
  2. Core Security Patterns – Christopher Steele, Ray Lai and Ramesh Nagappan


Aplications in Free Environments

Tutor:  Ing. Tito Armas
Translator: Bravo Maria Jose and Portilla Maria Fernanda 2012