/* ****************************************************************************** * JavaSec: TripleDESEncryption * Copyright (C) 2003 Daniel Lerch Hostalot * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * ****************************************************************************** * * ============================================================================ * EL ALGORITMO TRIPLE DES * ============================================================================ * * ---------------------------------------------------------------------------- * Introducción: * ---------------------------------------------------------------------------- * * El algoritmo DES tiene un grave problema con la longitud de la clave (56 * bits). Por este motivo no es el algoritmo más indicado para cifrar datos * importantes. * * Para solucionar el problema con la longitud de la clave nace el algoritmo * Triple DES, que consiste en utilizar tres veces DES. * * La clave utilizada por Triple DES es de 128 bits (112 de clave y 16 de * paridad) , es decir, dos claves de 64 bits (56 de clave y 8 de paridad) de * los utilizados en DES. El motivo de utilizar este de tipo de clave es la * compatibilidad con DES. Si la clave utilizada es el conjunto de dos claves * DES iguales el resultado será el mismo para DES y para Triple DES. * * ---------------------------------------------------------------------------- * Encriptar mediante Triple DES * ---------------------------------------------------------------------------- * * Para encriptar mediante el algoritmo Triple DES seguiremos los siguientes * pasos: * * 1. Dividir la clave de 128 bits en dos partes de 64 bits: k1 y k2. * 2. Se cifra el texto en claro con k1. El resultado es conocido como ANTIDES. * 3. Se cifra ANTIDES con k2. * 4. Se cifra el resultado con k1. * 5. Si k1=k2 el resultado coincide con una encriptación mediante DES. * * Otra forma de utilizar Triple DES es con una clave de 192 bits (168 bits * de clave y 24 bits de paridad). En este caso se cifrará primero con k1, * a continuación con k2 y finalmente con k3. * * Para ser compatible con DES es necesario que k1=k2=k3. * * ============================================================================ */ import javax.crypto.*; import javax.crypto.spec.*; import java.security.*; import java.security.spec.*; import sun.misc.*; import java.io.*; class TripleDESEncryption { /** * Encripta un String utilizando el algoritmo Triple DES * * @param clearText Texto en ckaro a encriptar * @return texto encriptado en base 64 */ public String encrypt (String clearText, Key key) { String cipherTextB64 = ""; try { // Necesitamos un cifrador Cipher cipher = Cipher.getInstance("DESede"); // Ciframos el texto en claro cipher.init(Cipher.ENCRYPT_MODE, key); byte cipherText[] = cipher.doFinal(clearText.getBytes()); // Codificamos el texto cifrado en base 64 BASE64Encoder base64encoder = new BASE64Encoder(); cipherTextB64 = base64encoder.encode(cipherText); } catch(NoSuchAlgorithmException nsae) {nsae.printStackTrace(); } catch(InvalidKeyException ike) {ike.printStackTrace(); } catch(NoSuchPaddingException nspe) {nspe.printStackTrace(); } catch(IllegalBlockSizeException ibse) {ibse.printStackTrace(); } catch(BadPaddingException bpe) {bpe.printStackTrace(); } // Retornamos el texto cifrado en BASE64 return cipherTextB64; } /** * Desencripta un testo cifrado en Triple DES i codificado en base 64 * * @param String cipherTextB64 Testo cifrado en Triple DES y codificado en B64 * @return String Texto en claro */ public String decrypt (String cipherTextB64, Key key) { String clearText = ""; try { // Necesitamos un cifrador Cipher cipher = Cipher.getInstance("DESede"); // La clave está codificada en base 64 BASE64Decoder base64decoder = new BASE64Decoder(); byte cipherText[] = base64decoder.decodeBuffer(cipherTextB64); // Ciframos el texto en claro cipher.init(Cipher.DECRYPT_MODE, key); byte bclearText[] = cipher.doFinal(cipherText); clearText = new String(bclearText); } catch(NoSuchAlgorithmException nsae) {nsae.printStackTrace(); } catch(NoSuchPaddingException nspe) {nspe.printStackTrace(); } catch(InvalidKeyException ike) {ike.printStackTrace(); } catch(IllegalBlockSizeException ibse) {ibse.printStackTrace(); } catch(BadPaddingException bpe) {bpe.printStackTrace(); } catch(IOException ioe) {ioe.printStackTrace(); } return clearText; } /** * Test de la clase */ public static void main (String args[]) { // Tres claves de 64 bits tipo DES // Por lo tanto este algoritmo es compatible con DES byte[] secret = { 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08}; Key key = null; try { SecretKeyFactory skf = SecretKeyFactory.getInstance("DESede"); key = skf.generateSecret(new DESedeKeySpec(secret)); } catch(NoSuchAlgorithmException nsae) {nsae.printStackTrace(); } catch(InvalidKeyException ike) {ike.printStackTrace(); } catch(InvalidKeySpecException ikse) {ikse.printStackTrace(); } TripleDESEncryption tripledesencryption = new TripleDESEncryption(); String cipherText = tripledesencryption.encrypt("Texto en claro", key); System.out.println("Texto cifrado: " + cipherText); String clearText = tripledesencryption.decrypt(cipherText, key); System.out.println("Texto en claro: " + clearText); } }