Segue anexo um bom exemplo de criptografia usando JAVA. O c�digo foi escrito
como exemplo para um capitulo sobre seguran�a do livro "Advanced Java 2
Platform", da Deitel.
Espero que seja �til como foi para mim.
[]�s
Carlos.
-- Mensagem original --
>Ola Paulo
>
>Segue anexo, classe Java que efetua criptografia usando o m�todo de
>Vigener�. Apesar de ser uma rotina conhecida por muitas pessoas, aposto
>alguem descritografar um texto gerada por ela. Para saber mais detalhes
>do
>funcionamento e algumas dicas de uso, visite minha home-page (
>http://albb.cjb.net <http://albb.cjb.net> ), entre na sess�o "InfoTec",
>sub-sess�o "Delphi" e olhe o artigo sobre criptografia.
>Em www.mundodelphi.com.br <http://www.mundodelphi.com.br> tamb�m h� um
>artigo sobre criptografia, escrito por mim, com outros m�todos de
>criptografia.
>
>Boa Sorte e a Paz do Senhor
>
>[:>} Alan Candido ><>
>
> __~`.
> .[====].[====].[====].[____].]@|-Y\_
>_____o__o___o__o___o__o___o__o___O_ooo______________________________________
>_______________________________
>--< Escrevendo para mim (profissional/pessoal >------|--< Quando estiver
>On-line, procure-me >-------------
> <mailto:[EMAIL PROTECTED]> [EMAIL PROTECTED]
><mailto:[EMAIL PROTECTED]> [EMAIL PROTECTED] | ICQ 14310772 ICQ
>117513933 MSN [EMAIL PROTECTED] <mailto:[EMAIL PROTECTED]>
>--< Trazendo uma d�vida e levando mais 5 >-----------|--< Home-page, minha
>cara na www >-------------------
>Para se inscrever, mande e-mail para a lista | Almanaque BR�D�O
>&
>br�dinho
>Delphi: <mailto:[EMAIL PROTECTED]>
>[EMAIL PROTECTED] | <http://albb.cjb.net/>
>http://albb.cjb.net
> <mailto:[EMAIL PROTECTED]>
>[EMAIL PROTECTED] : ERP |
>-----------------------------------------------------|----------------------
>-------------------------------
>[:? Ufa!!! At� que enfim terminou minha assinatura.
>
>
>-----Mensagem original-----
>De: [EMAIL PROTECTED] [mailto:[EMAIL PROTECTED]]
>Enviada em: segunda-feira, 13 de maio de 2002 12:44
>Para: [EMAIL PROTECTED]
>Assunto: Re: [java-list] Password
>
>
>
>opa Samuel,
>
>seu quero gravar o usuario/senha, que dar� acesso ao meu banco de dados,
>em
>um arquivo, entende?
>Minha classe dever� ler desse arquivo, descriptografar e autenticar-se
com
>o
>banco.
>
>E a�? vc tem alguma sugestao/ideia/example???
>
>valeu
>Atenciosamente
>PAULO BRANCO
>DIRETIVA DIGITAL
>
>
>
> "Samuel Yuen" <[EMAIL PROTECTED]>
>
>
>12/05/2002 00:26
>Responder a java-list
>
>
>
> Para: <[EMAIL PROTECTED]>
> cc:
> Assunto: Re: [java-list] Password
>
>
>Paulo,
>
>o que exatamente voc� n�o pode gravar no .class? A senha?
>O que voc� poderia estar fazendo seria utilizar um algoritmo de criptografia
>para cifrar a senha antes de grav�-la no arquivo e decifr�-lo ao efetuar
>a
>conex�o com o banco de dados. Claro que n�o poderia ser um algoritmo f�cil
>de ser descoberto, voc� poderia ofuscar a classe para dificultar um pouco
>as
>coisas.
>
>Algo mais sofisticado seria usar um algoritmo que use chaves sim�tricas
>e
>al�m de guardar a chave usada no .class, guard�-la tamb�m em um local seguro
>para ser usada sempre que a senha for trocada. O uso de chaves assim�tricas
>n�o traz nenhuma real vantagem, fora a desnecessidade de grande seguran�a
>para guardar a chave a ser usada para cifrar a palavra.
>
>Bem, tudo isso n�o vai te proteger totalmente, nada impede que um bom
>conhecedor de Java decompile a sua classe e descubra como funciona o
>mecanismo, mesmo que ela esteja ofuscada (para tal esfor�o provavelmente
>seria algu�m mal intencionado). Mais do que uma criptografia, � necess�ria
>uma pol�tica de seguran�a, que impe�a o acesso ao sistema nos n�veis de
>hardware e software e que tamb�m involva as pessoas da empresa.
>
>Samuel
>
>----- Original Message -----
>From: <mailto:[EMAIL PROTECTED]> [EMAIL PROTECTED]
>To: <mailto:[EMAIL PROTECTED]> [EMAIL PROTECTED]
>Sent: Friday, May 10, 2002 10:01 AM
>Subject: Re: [java-list] Password
>
>
>ola ALL,
>
>Obrigado pela ajuda.
>O meu problema � que preciso gravar a senha de acesso ao banco em um arquivo
>.properties por exemplo. Pois minha aplicacao lera desse arquivo para
>conectar ao banco. Isso que vc falou est� correto para os demais usu�rios,
>mas e o user que se logar� no banco como proceder? Eu nao posso deixar
>gravado dentro do .class, pois trata-se de uma aplicacao comercial, entao
>como fazer? Quero pegar a senha, criptografa-la, grava-la em um .properties,
>e quando precisar acessar o banco, ler o arquivo, descriptografar a senha,
>autenticar no banco.
>
>Caso vc tenha QUALQUER ajuda/exemplo agrade�o muito.
>
>
>"Valeu ;) "
>
>Atenciosamente
>PAULO BRANCO
>DIRETIVA DIGITAL
>
>
>
>Garante sim.
>
>A fun��o hash funciona assim:
>Dado um texto de entrada, uma sa�da � gerada.
>A partir da sa�da, � imposs�vel se chegar novamente ao
>texto da entrada. Mas dada a mesma entrada, a mesma
>sa�da � gerada.
>Se vc aplica essa fun��o na senha do usu�rio quando o
>est� cadastrando ou trocando de senha, o que fica
>guardado � essa sa�da, que n�o significa nada para
>ningu�m que venha a pegar esse arquivo. Quando o
>usu�rio vai logar, vc aplica a fun��o na entrada dele
>e, se bater o resultado com o que est� guardado, ele
>bateu a senha correta.
>Esse tipo de autentica��o � usado no UNIX.
>
>JP
>
>--- [EMAIL PROTECTED] wrote:
>> Mas Marco, na realidade esse algoritmo nao garante
>> seguranca nenhuma, ou
>> nao?
>> Como gravar em um arquivo essa "password" se quando
>> transformada em string
>> fica identica?
>>
>> Atenciosamente
>> PAULO BRANCO
>> DIRETIVA DIGITAL
>>
>>
>>
>>
>> "Marco Aurelio Vilela Garcia" <[EMAIL PROTECTED]>
>> 06/05/2002 12:54
>> Please respond to java-list
>>
>>
>> To: <[EMAIL PROTECTED]>
>> cc:
>> Subject: Re: [java-list] Password
>>
>>
>> Caro Matheus;
>> No caso de criptografar uma senha, eu sugiro que n�o
>> utilize nada para
>> criptografia. A documenta��o ainda est� fraca, pois
>> a API de criptografia
>> foi liberada para usu�rios fora dos EUA h� muito
>> pouco tempo. � poss�vel
>> obter uma funcionalidade parecida usando um digesto
>> de mensagem.
>> O procedimento � o seguinte: uma classe ir�, a
>> partir da sua senha, criar
>> uma string que parece ser criptografada. Mas n�o se
>> trata de criptografia,
>> �
>> apenas uma forma de autentica��o. Eu estou usando
>> isso para armazenar
>> senhas
>> numa base de dados. Estou satisfeito at� agora.
>>
>> Logo abaixo escrevo um c�digo para vc experimentar.
>>
>> Abra�os
>> Marco
>>
>>
>>
>> import java.security.*;
>>
>> /**
>> * @author Marco Aur�lio Vilela Garcia
>> * @version 1,0
>> */
>> public final class PasswordEncDec {
>>
>> public static String cryptSenha(String senha){
>> try{
>> MessageDigest md =
>> MessageDigest.getInstance("SHA");
>> byte[] buf = senha.getBytes();
>> md.update(buf);
>> byte[] digest = md.digest();
>>
>> return new String(digest);
>> }
>> catch(NoSuchAlgorithmException nsae){
>>
>>
>System.err.println("===============================================");
>>
>>
>System.err.println("===============================================");
>> System.err.println(" Erro
>> acontecendo no
>> PasswordEncDec");
>> System.err.println(" M�todo
>> cryptSenha ");
>> System.err.println("Exce��o: "+ nsae);
>>
>>
>System.err.println("===============================================");
>>
>>
>System.err.println("===============================================");
>> return null;
>> }
>> }
>> }
>>
>>
>>
>> ----- Original Message -----
>> From: "MATHEUS Fabio O CONFAB"
>> <[EMAIL PROTECTED]>
>> To: <[EMAIL PROTECTED]>
>> Sent: Monday, May 06, 2002 8:54 AM
>> Subject: [java-list] Password
>>
>>
>> Pessoall,
>>
>> Algu�m teria um exemplo simples de criptografia de
>> uma string, ou
>> simplesmente s� o algoritimo??
>> Qquer ajuda seria importante..
>>
>> Grato e boa semana!
>> F�bio Oliveira Matheus
>> Confab Industrial S/A. - Depto. Sistemas
>> Pindamonhangaba - S�o Paulo - Brasil
>> E-Mail: [EMAIL PROTECTED]
>> Fone: 12-244-9316 Fax: 12-244-9304
>>
>>
>>
>> ------------------------------ LISTA SOUJAVA
>> ----------------------------
>> http://www.soujava.org.br - Sociedade de Usu�rios
>> Java da Sucesu-SP
>> d�vidas mais comuns:
>> http://www.soujava.org.br/faq.htm
>> regras da lista:
>> http://www.soujava.org.br/regras.htm
>> historico:
>>
>http://www.mail-archive.com/java-list%40soujava.org.br
>> para sair da lista: envie email para
>> [EMAIL PROTECTED]
>>
>-------------------------------------------------------------------------
>>
>>
>>
>> ------------------------------ LISTA SOUJAVA
>> ----------------------------
>> http://www.soujava.org.br - Sociedade de Usu�rios
>> Java da Sucesu-SP
>> d�vidas mais comuns:
>> http://www.soujava.org.br/faq.htm
>> regras da lista:
>> http://www.soujava.org.br/regras.htm
>> historico:
>>
>http://www.mail-archive.com/java-list%40soujava.org.br
>> para sair da lista: envie email para
>> [EMAIL PROTECTED]
>>
>-------------------------------------------------------------------------
>>
>>
>>
>>
>>
>
>
>__________________________________________________
>Do You Yahoo!?
>Yahoo! Health - your guide to health and wellness
>http://health.yahoo.com
>
>------------------------------ LISTA SOUJAVA ----------------------------
>
>http://www.soujava.org.br - Sociedade de Usu�rios Java da Sucesu-SP
>d�vidas mais comuns: http://www.soujava.org.br/faq.htm
>regras da lista: http://www.soujava.org.br/regras.htm
>historico: http://www.mail-archive.com/java-list%40soujava.org.br
>para sair da lista: envie email para [EMAIL PROTECTED]
>
>-------------------------------------------------------------------------
>
>
>
>
>
>
>
>
// EncipherDecipher.java
// Displays a frame that allows users to specify
// a password and a file name. Contents written
// to an Editor Pane can be encrypted and written
// to a file, or encrypted contents can be read from
// a file and decrypted
// Java core package
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.util.*;
import java.security.*;
import java.security.spec.*;
// third-party packages
import com.sun.crypto.provider.SunJCE;
// Java extension package
import javax.swing.*;
import javax.crypto.*;
import javax.crypto.spec.*;
public class EncipherDecipher extends JFrame {
// salt for password-based encryption-decryption algorithm
private static final byte[] salt = {
( byte )0xf5, ( byte )0x33, ( byte )0x01, ( byte )0x2a,
( byte )0xb2, ( byte )0xcc, ( byte )0xe4, ( byte )0x7f
};
// iteration count
private int iterationCount = 100;
// user input components.
private JTextField passwordTextField;
private JTextField fileNameTextField;
private JEditorPane fileContentsEditorPane;
// frame constructor
public EncipherDecipher() {
// set security provider
Security.addProvider( new SunJCE() );
// initialize main frame
setSize( new Dimension( 400, 400 ) );
setTitle( "Encryption and Decryption Example" );
// construct top panel
JPanel topPanel = new JPanel();
topPanel.setBorder( BorderFactory.createLineBorder(
Color.black ) );
topPanel.setLayout( new BorderLayout() );
// panel where password and file name labels will be placed
JPanel labelsPanel = new JPanel();
labelsPanel.setLayout( new GridLayout( 2, 1 ) );
JLabel passwordLabel = new JLabel( " Password: " );
JLabel fileNameLabel = new JLabel( " File Name: " );
labelsPanel.add( fileNameLabel );
labelsPanel.add( passwordLabel );
topPanel.add( labelsPanel, BorderLayout.WEST );
// panel where password and file name textfields will be placed
JPanel textFieldsPanel = new JPanel();
textFieldsPanel.setLayout( new GridLayout( 2, 1 ) );
passwordTextField = new JPasswordField();
fileNameTextField = new JTextField();
textFieldsPanel.add( fileNameTextField );
textFieldsPanel.add( passwordTextField );
topPanel.add( textFieldsPanel, BorderLayout.CENTER );
// construct middle panel
JPanel middlePanel = new JPanel();
middlePanel.setLayout( new BorderLayout() );
// construct and place title label for contents pane
JLabel fileContentsLabel = new JLabel();
fileContentsLabel.setText( " File Contents" );
middlePanel.add( fileContentsLabel, BorderLayout.NORTH );
// initialize and place editor pane within scroll panel
fileContentsEditorPane = new JEditorPane();
middlePanel.add(
new JScrollPane( fileContentsEditorPane ),
BorderLayout.CENTER );
// construct bottom panel
JPanel bottomPanel = new JPanel();
// create encrypt button
JButton encryptButton =
new JButton( "Encrypt and Write to File" );
encryptButton.addActionListener(
new ActionListener() {
public void actionPerformed( ActionEvent event )
{
encryptAndWriteToFile();
}
}
);
bottomPanel.add( encryptButton );
// create decrypt button
JButton decryptButton =
new JButton( "Read from File and Decrypt" );
decryptButton.addActionListener(
new ActionListener() {
public void actionPerformed( ActionEvent event )
{
readFromFileAndDecrypt();
}
}
);
bottomPanel.add( decryptButton );
// initialize main frame window
JPanel contentPane = ( JPanel ) this.getContentPane();
contentPane.setLayout( new BorderLayout() );
contentPane.add( topPanel, BorderLayout.NORTH );
contentPane.add( middlePanel, BorderLayout.CENTER );
contentPane.add( bottomPanel, BorderLayout.SOUTH );
} // end constructor
// obtain contents from editor pane and encrypt
private void encryptAndWriteToFile()
{
// obtain user input
String originalText = fileContentsEditorPane.getText();
String password = passwordTextField.getText();
String fileName = fileNameTextField.getText();
// create secret key and get cipher instance
Cipher cipher = null;
try {
// create password based encryption key object
PBEKeySpec keySpec =
new PBEKeySpec( password.toCharArray() );
// obtain instance for secret key factory
SecretKeyFactory keyFactory =
SecretKeyFactory.getInstance( "PBEWithMD5AndDES" );
// generate secret key for encryption
SecretKey secretKey = keyFactory.generateSecret( keySpec );
// specifies parameters used with password based encryption
PBEParameterSpec parameterSpec =
new PBEParameterSpec( salt, iterationCount );
// obtain cipher instance reference
cipher = Cipher.getInstance( "PBEWithMD5AndDES" );
// initialize cipher in encrypt mode
cipher.init( Cipher.ENCRYPT_MODE, secretKey,
parameterSpec );
}
// handle NoSuchAlgorithmException
catch ( NoSuchAlgorithmException exception ) {
exception.printStackTrace();
System.exit( 1 );
}
// handle InvalidKeySpecException
catch ( InvalidKeySpecException exception ) {
exception.printStackTrace();
System.exit( 1 );
}
// handle InvalidKeyException
catch ( InvalidKeyException exception ) {
exception.printStackTrace();
System.exit( 1 );
}
// handle NoSuchPaddingException
catch ( NoSuchPaddingException exception ) {
exception.printStackTrace();
System.exit( 1 );
}
// handle InvalidAlgorithmParameterException
catch ( InvalidAlgorithmParameterException exception ) {
exception.printStackTrace();
System.exit( 1 );
}
// create array of bytes
byte[] outputArray = null;
try {
outputArray = originalText.getBytes( "ISO-8859-1" );
}
// handle UnsupportedEncodingException
catch ( UnsupportedEncodingException exception ) {
exception.printStackTrace();
System.exit( 1 );
}
// create FileOutputStream
File file = new File( fileName );
FileOutputStream fileOutputStream = null;
try {
fileOutputStream = new FileOutputStream( file );
}
// handle IOException
catch ( IOException exception ) {
exception.printStackTrace();
System.exit( 1 );
}
// create CipherOutputStream
CipherOutputStream out =
new CipherOutputStream( fileOutputStream, cipher );
// write contents to file and close
try {
out.write( outputArray );
out.flush();
out.close();
}
// handle IOException
catch ( IOException exception ) {
exception.printStackTrace();
System.exit( 1 );
}
// contain bytes read from file
Vector fileBytes = new Vector();
// read contents from file to show user encrypted text
try {
FileInputStream in = new FileInputStream( file );
// read bytes from stream.
byte contents;
while ( in.available() > 0 ) {
contents = ( byte )in.read();
fileBytes.add( new Byte( contents ) );
}
in.close();
}
// handle IOException
catch ( IOException exception ) {
exception.printStackTrace();
System.exit( 1 );
}
// create byte array from contents in Vector fileBytes
byte[] encryptedText = new byte[ fileBytes.size() ];
for ( int i = 0; i < fileBytes.size(); i++ ) {
encryptedText[ i ] =
( ( Byte ) fileBytes.elementAt( i ) ).byteValue();
}
// update Editor Pane contents
fileContentsEditorPane.setText( new String( encryptedText ) );
}
// obtain contents from file and decrypt
private void readFromFileAndDecrypt()
{
// used to rebuild byte list
Vector fileBytes = new Vector();
// obtain user input
String password = passwordTextField.getText();
String fileName = fileNameTextField.getText();
// create secret key
Cipher cipher = null;
try {
// create password based encryption key object
PBEKeySpec keySpec =
new PBEKeySpec( password.toCharArray() );
// obtain instance for secret key factory
SecretKeyFactory keyFactory =
SecretKeyFactory.getInstance( "PBEWithMD5AndDES" );
// generate secret key for encryption
SecretKey secretKey = keyFactory.generateSecret( keySpec );
// specifies parameters used with password based encryption
PBEParameterSpec parameterSpec =
new PBEParameterSpec( salt, iterationCount );
// obtain cipher instance reference.
cipher = Cipher.getInstance( "PBEWithMD5AndDES" );
// initialize cipher in decrypt mode
cipher.init( Cipher.DECRYPT_MODE, secretKey,
parameterSpec );
}
// handle NoSuchAlgorithmException
catch ( NoSuchAlgorithmException exception ) {
exception.printStackTrace();
System.exit( 1 );
}
// handle InvalidKeySpecException
catch ( InvalidKeySpecException exception ) {
exception.printStackTrace();
System.exit( 1 );
}
// handle InvalidKeyException
catch ( InvalidKeyException exception ) {
exception.printStackTrace();
System.exit( 1 );
}
// handle NoSuchPaddingException
catch ( NoSuchPaddingException exception ) {
exception.printStackTrace();
System.exit( 1 );
}
// handle InvalidAlgorithmParameterException
catch ( InvalidAlgorithmParameterException exception ) {
exception.printStackTrace();
System.exit( 1 );
}
// read and decrypt contents from file
try {
File file = new File( fileName );
FileInputStream fileInputStream =
new FileInputStream( file );
CipherInputStream in =
new CipherInputStream( fileInputStream, cipher );
// read bytes from stream.
byte contents = ( byte ) in.read();
while ( contents != -1 ) {
fileBytes.add( new Byte( contents ) );
contents = ( byte ) in.read();
}
in.close();
}
// handle IOException
catch ( IOException exception ) {
exception.printStackTrace();
System.exit( 1 );
}
// create byte array from contents in Vector fileBytes
byte[] decryptedText = new byte[ fileBytes.size() ];
for ( int i = 0; i < fileBytes.size(); i++ ) {
decryptedText[ i ] =
( ( Byte )fileBytes.elementAt( i ) ).byteValue();
}
// update Editor Pane contents.
fileContentsEditorPane.setText( new String( decryptedText ) );
}
// create frame and display
public static void main( String[] args )
{
EncipherDecipher crypto =
new EncipherDecipher();
crypto.validate();
crypto.setVisible( true );
}
}
/***************************************************************
* (C) Copyright 2002 by Deitel & Associates, Inc. and *
* Prentice Hall. All Rights Reserved. *
* *
* DISCLAIMER: The authors and publisher of this book have *
* used their best efforts in preparing the book. These *
* efforts include the development, research, and testing of *
* the theories and programs to determine their effectiveness. *
* The authors and publisher make no warranty of any kind, *
* expressed or implied, with regard to these programs or to *
* the documentation contained in these books. The authors *
* and publisher shall not be liable in any event for *
* incidental or consequential damages in connection with, or *
* arising out of, the furnishing, performance, or use of *
* these programs. *
***************************************************************/
------------------------------ LISTA SOUJAVA ----------------------------
http://www.soujava.org.br - Sociedade de Usu�rios Java da Sucesu-SP
d�vidas mais comuns: http://www.soujava.org.br/faq.htm
regras da lista: http://www.soujava.org.br/regras.htm
historico: http://www.mail-archive.com/java-list%40soujava.org.br
para sair da lista: envie email para [EMAIL PROTECTED]
-------------------------------------------------------------------------