Desenvolvimento de software e tecnologia em geral
Criptografia Triple DES em Java
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:
| Imprimir artigo | Este artigo foi escrito por Rodrigo Lazoti em 06/07/2009 às 0:10, e está arquivado em Java, Programação. Siga quaisquer respostas a este artigo através do RSS 2.0. Você pode deixar uma resposta ou fazer um trackback do seu próprio site. |


há 1 ano atrás
Muito bom. Como eu poderia utlizar um algoritmo de criptografia se eu tiver utilizando sockets para compartilhar um arquivo????
Abraço.
há 1 ano atrás
E se a String value = “c:\\arquitoTeste.txt” , for um arquivo eu consigo criptografar ?????
há 1 ano atrás
Gostei da dica, mas gostaria de saber o motivo pelo qual é exibidos estes warnings.
init:
deps-jar:
Compiling 1 source file to C:\Fabio\JAVA\Bibliotecas\build\classes
C:\Fabio\JAVA\Bibliotecas\src\Seguranca\Criptografia.java:28: warning: sun.misc.BASE64Decoder is Sun proprietary API and may be removed in a future release
import sun.misc.BASE64Decoder;
C:\Fabio\JAVA\Bibliotecas\src\Seguranca\Criptografia.java:29: warning: sun.misc.BASE64Encoder is Sun proprietary API and may be removed in a future release
import sun.misc.BASE64Encoder;
C:\Fabio\JAVA\Bibliotecas\src\Seguranca\Criptografia.java:94: warning: sun.misc.BASE64Encoder is Sun proprietary API and may be removed in a future release
BASE64Encoder encoder = new BASE64Encoder();
^
C:\Fabio\JAVA\Bibliotecas\src\Seguranca\Criptografia.java:94: warning: sun.misc.BASE64Encoder is Sun proprietary API and may be removed in a future release
BASE64Encoder encoder = new BASE64Encoder();
^
C:\Fabio\JAVA\Bibliotecas\src\Seguranca\Criptografia.java:113: warning: sun.misc.BASE64Decoder is Sun proprietary API and may be removed in a future release
BASE64Decoder dec = new BASE64Decoder();
^
C:\Fabio\JAVA\Bibliotecas\src\Seguranca\Criptografia.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)
há 1 ano atrás
Muito bom. Funcionou aqui.
Mas como o Fabio já questionou, por que gera esses alertas?
Desde já obrigado!
há 11 meses atrás
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…
há 10 meses atrás
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
há 3 meses atrás
queria saber faço para criptografar um arquivo txt. como ex. um texto com no máximo 256 palavras.
falou..