In Java, Programação

Criptografia Triple DES em Java

Posted July 6th, 2009 by Rodrigo Lazoti.
Tagged: , , , , .

Um dos posts que mais foram acessados e comentados em meu blog foi um escrito sobre Criptografia em Java utilizando Hashs criptográficos.

Depois de receber alguns pedidos resolvi escrever este novo post utilizando no exemplo uma criptografia do tipo Triple DES, com esta criptografia podemos encriptografar e descriptografar informações utilizando Java.

Triple DES é a mais segura versão do algoritmo original Data Encryption Standard (DES) e você pode saber sobre este algoritmo aqui.

Agora vamos a implementação do algoritmo, eu criei uma classe simples que fornece dois métodos de instância para encriptografar e descriptografar uma String.

package br.com.rodrigolazoti;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.KeySpec;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESedeKeySpec;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

/**
 * Class that supplies a criptography of triple type DES.
 * @author Rodrigo Lazoti
 * @since 05/07/2009
 */
public class CryptographyTripleDES {
 private Cipher cipher;
 private byte[] encryptKey;
 private KeySpec keySpec;
 private SecretKeyFactory secretKeyFactory;
 private SecretKey secretKey;

 /**
 * Method that create a new instance of class.
 * @return
 * @throws InvalidKeyException
 * @throws UnsupportedEncodingException
 * @throws NoSuchAlgorithmException
 * @throws NoSuchPaddingException
 * @throws InvalidKeySpecException
 */
 public static CryptographyTripleDES newInstance() throws InvalidKeyException, UnsupportedEncodingException,
 NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeySpecException {
 return new CryptographyTripleDES();
 }

 /**
 * Default Constructor.
 * @throws UnsupportedEncodingException
 * @throws NoSuchAlgorithmException
 * @throws NoSuchPaddingException
 * @throws InvalidKeyException
 * @throws InvalidKeySpecException
 */
 private CryptographyTripleDES() throws UnsupportedEncodingException, NoSuchAlgorithmException,
 NoSuchPaddingException, InvalidKeyException, InvalidKeySpecException {
 String key = "http://www.rodrigolazoti.com.br";
 encryptKey = key.getBytes( "UTF-8" );
 cipher = Cipher.getInstance( "DESede" );
 keySpec = new DESedeKeySpec( encryptKey );
 secretKeyFactory = SecretKeyFactory.getInstance( "DESede" );
 secretKey = secretKeyFactory.generateSecret( keySpec );
 }

 /**
 * Method that encrypts a value.
 * @param value
 * @return
 * @throws InvalidKeyException
 * @throws IllegalBlockSizeException
 * @throws BadPaddingException
 * @throws UnsupportedEncodingException
 */
 public String encrypt( String value ) throws InvalidKeyException, IllegalBlockSizeException, BadPaddingException,
 UnsupportedEncodingException {
 cipher.init( Cipher.ENCRYPT_MODE, secretKey );
 byte[] cipherText = cipher.doFinal( value.getBytes( "UTF-8" ) );
 BASE64Encoder encoder = new BASE64Encoder();
 return encoder.encode( cipherText );
 }

 /**
 * Methot that decrypts a value.
 * @param value
 * @return
 * @throws InvalidKeyException
 * @throws IllegalBlockSizeException
 * @throws BadPaddingException
 * @throws IOException
 */
 public String decrypt( String value ) throws InvalidKeyException, IllegalBlockSizeException, BadPaddingException,
 IOException {
 cipher.init( Cipher.DECRYPT_MODE, secretKey );
 BASE64Decoder dec = new BASE64Decoder();
 byte[] decipherText = cipher.doFinal( dec.decodeBuffer( value ) );
 return new String( decipherText );
 }

}

A seguir criei uma pequena classe para realizar um teste:

package br.com.rodrigolazoti;

import java.io.IOException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.spec.InvalidKeySpecException;
import javax.crypto.BadPaddingException;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;

public class TestCryptographyTripleDES {

 public static void main( String[] args ) throws InvalidKeyException, NoSuchAlgorithmException,
 NoSuchPaddingException, InvalidKeySpecException, IllegalBlockSizeException, BadPaddingException, IOException {

 CryptographyTripleDES cryptography = CryptographyTripleDES.newInstance();
 String value = "Rodrigo Lazoti";
 System.out.println( "Valor utilizado => " + value );
 String encryptedValue = cryptography.encrypt( value );
 System.out.println( "Valor criptografado => " + encryptedValue );
 String decryptedValue = cryptography.decrypt( encryptedValue );
 System.out.println( "Valor descriptografado => " + decryptedValue );

 }

}

O resultado do teste é:

Valor utilizado => Rodrigo Lazoti
Valor criptografado => RgYlMeQBUcyx6419bKlqRw==
Valor descriptografado => Rodrigo Lazoti

Com isso já temos uma boa base de como utilizar este tipo de criptografia em aplicações Java.

Related Posts

  1. Como utilizar criptografia em Java
  2. Autenticação com Jboss Seam
  3. Herança de propriedades entre entidades com JPA

8 responses to Criptografia Triple DES em Java

  1. Romulo says:

    Muito bom. Como eu poderia utlizar um algoritmo de criptografia se eu tiver utilizando sockets para compartilhar um arquivo????

    Abraço.

  2. Romulo says:

    E se a String value = “c:\arquitoTeste.txt” , for um arquivo eu consigo criptografar ?????

  3. fabio nunes de souza says:

    Gostei da dica, mas gostaria de saber o motivo pelo qual é exibidos estes warnings.

    init:
    deps-jar:
    Compiling 1 source file to C:FabioJAVABibliotecasbuildclasses
    C:FabioJAVABibliotecassrcSegurancaCriptografia.java:28: warning: sun.misc.BASE64Decoder is Sun proprietary API and may be removed in a future release
    import sun.misc.BASE64Decoder;
    C:FabioJAVABibliotecassrcSegurancaCriptografia.java:29: warning: sun.misc.BASE64Encoder is Sun proprietary API and may be removed in a future release
    import sun.misc.BASE64Encoder;
    C:FabioJAVABibliotecassrcSegurancaCriptografia.java:94: warning: sun.misc.BASE64Encoder is Sun proprietary API and may be removed in a future release
    BASE64Encoder encoder = new BASE64Encoder();
    ^
    C:FabioJAVABibliotecassrcSegurancaCriptografia.java:94: warning: sun.misc.BASE64Encoder is Sun proprietary API and may be removed in a future release
    BASE64Encoder encoder = new BASE64Encoder();
    ^
    C:FabioJAVABibliotecassrcSegurancaCriptografia.java:113: warning: sun.misc.BASE64Decoder is Sun proprietary API and may be removed in a future release
    BASE64Decoder dec = new BASE64Decoder();
    ^
    C:FabioJAVABibliotecassrcSegurancaCriptografia.java:113: warning: sun.misc.BASE64Decoder is Sun proprietary API and may be removed in a future release
    BASE64Decoder dec = new BASE64Decoder();
    ^
    6 warnings
    compile-single:
    CONSTRUÍDO COM SUCESSO (tempo total: 0 segundos)

  4. Juliano Denner says:

    Muito bom. Funcionou aqui.

    Mas como o Fabio já questionou, por que gera esses alertas?

    Desde já obrigado!

  5. Marcos Leon says:

    Olá pessoal, tudo na paz?

    Esse aviso é exibido pois como a mensagem já diz essa é uma classe proprietária da sun. Em relação ao questionamento do Romulo, se o conteúdo do arquivo for texto você pode tentar jogar o conteúdo do arquivo para uma String e depois criptografá-la, vale lembrar que nem todos os métodos de criptografia aceitam grandes strings.

    Espero que possa ter ajudado… aquele abraço…

  6. RHTA says:

    Rodrigo, blz?

    Otimo post, valeu pelo empenho de ajudar a comunidade.

    Cara estou com um problema quando utilizo um string para criptografar e essa string contem caracteres especiais os caracteres saem todos fora do padrão comforme exemplo abaixo

    Valor utilizado => ABCÇÃãõô6uܨ
    Valor criptografado => Hr3qDfzkPcMw2JDJ+iZAoKHLyy/hnvgK
    Valor descriptografado => ABCÇÃãõô6uܨ

    Será que temos alguma solução para isso ?

    Valeu

  7. gleydson santos de souza says:

    queria saber faço para criptografar um arquivo txt. como ex. um texto com no máximo 256 palavras.
    falou..

  8. Pablo D P Bom (Daruz) says:

    Primeiramente Rodrigo Lazoti, muito obrigado por compartilhar este OTIMO codigo…

    Pessoal para quem esta com problemas por conta da classe da sun.
    Eu usei esta classe e substitui a da sun … não tem as mesmas funções porém faz oque é preciso …

    http://stackoverflow.com/questions/469695/decode-base64-data-in-java/4265472#4265472

    Espero ter ajudado …

    Abraços a todos.

Leave a response: