PBE - Criptografia

0 respostas
P

Boa tarde a todos.

Estou tentando montar um programa que trabalhe com PBE, eu quero que os dados criptografados sejam gravados por exemplo dessa forma: c:\dados_cript.dat, isso ai eu já consegui mas o meu problema esta que quando eu abro ele e a msm aparece criptografada num jtextArea em seguida na hora de decriptografar: que aparece o seguinte erro: ... at Menu.decryptPBE(Menu.java:419) at Menu$2.actionPerformed(Menu.java:184) at javax.swing.AbstractButton.fireActionPerformed(Unknown Source) at javax.swing.AbstractButton$Handler.actionPerformed(Unknown Source) at javax.swing.DefaultButtonModel.fireActionPerformed(Unknown Source) at javax.swing.DefaultButtonModel.setPressed(Unknown Source) at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(Unknown Source) ... Esse é meu codigo:
import java.awt.BorderLayout;

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.PBEKeySpec;
import javax.crypto.spec.PBEParameterSpec;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JFrame;
import javax.swing.JButton;
import java.awt.Rectangle;
import javax.swing.JTextArea;
import javax.swing.JLabel;
import java.awt.Color;
import java.io.File;
import java.io.FileOutputStream;
import java.io.RandomAccessFile;
import java.security.spec.AlgorithmParameterSpec;
import java.security.spec.KeySpec;

import javax.swing.JComboBox;

public class Menu extends JFrame {

	private static final long serialVersionUID = 1L;

	private JPanel jContentPane = null;

	private JButton jButtonCriptografar = null;

	private JButton jButtonDecritografar = null;

	private JTextArea jTextArea = null;

	private JButton jButtonSalvarArquivoDeDados = null;

	private JButton jButtonCrregarChave = null;

	private JLabel jLabel = null;

	private JLabel jLabelTexto = null;
	private java.util.Vector dados = new java.util.Vector();  //  @jve:decl-index=0:

	private JLabel jLabelDados = null;

	private JComboBox jComboBox = null;

	private JLabel jLabel1ComoVc = null; 
	int iterationCount = 19;
	
	Cipher ecipher;
	Cipher dcipher;

	// 8-byte Salt
	byte[] salt =
		{
			(byte) 0xA9, (byte) 0x9B,
			(byte) 0xC8, (byte) 0x32,
			(byte) 0x56, (byte) 0x35,
			(byte) 0xE3, (byte) 0x03 };	

	private String dadosTexto;
	private String chave;
	private String dadosCod;  //  @jve:decl-index=0:
	
	
	/**
	 * This is the default constructor
	 */
	public Menu() {
		super();
		initialize();
	}

	/**
	 * This method initializes this
	 * 
	 * @return void
	 */
	private void initialize() {
		this.setSize(640, 480);
		this.setContentPane(getJContentPane());
		this.setTitle("Trabalho - POS");
		this.setVisible(true);
	
	}

	/**
	 * This method initializes jContentPane
	 * 
	 * @return javax.swing.JPanel
	 */
	private JPanel getJContentPane() {
		if (jContentPane == null) {
			jLabel1ComoVc = new JLabel();
			jLabel1ComoVc.setBounds(new Rectangle(17, 216, 207, 22));
			jLabel1ComoVc.setText("Como você deseja fazer ?");
			jLabelDados = new JLabel();
			jLabelDados.setBounds(new Rectangle(15, 276, 246, 22));
			jLabelDados.setText("Não há nenhuma Texto carregado !");
			jLabelDados.setBackground(Color.red);
			jLabelTexto = new JLabel();
			jLabelTexto.setBounds(new Rectangle(15, 21, 273, 16));
			jLabelTexto.setText("Texto não criptografado :");
			jLabel = new JLabel();
			jLabel.setBounds(new Rectangle(15, 303, 246, 23));
			jLabel.setBackground(Color.red);
			jLabel.setText("Não há nenhuma chave carregada !");
			jContentPane = new JPanel();
			jContentPane.setLayout(null);
			jContentPane.add(getJButtonCriptografar(), null);
			jContentPane.add(getJButtonDecritografar(), null);
			jContentPane.add(getJTextArea(), null);
			jContentPane.add(getJButtonSalvarArquivoDeDados(), null);
			jContentPane.add(getJButtonCrregarChave(), null);
			jContentPane.add(jLabel, null);
			jContentPane.add(jLabelTexto, null);
			jContentPane.add(jLabelDados, null);
			jContentPane.add(getJComboBox(), null);
			jContentPane.add(jLabel1ComoVc, null);
		}
		return jContentPane;
	}

	/**
	 * This method initializes jButtonCriptografar	
	 * 	
	 * @return javax.swing.JButton	
	 */
	private JButton getJButtonCriptografar() {
		if (jButtonCriptografar == null) {
			jButtonCriptografar = new JButton();
			jButtonCriptografar.setText("Criptografar");
			jButtonCriptografar.setBounds(new Rectangle(473, 31, 147, 28));
			jButtonCriptografar.addActionListener(new java.awt.event.ActionListener() {
				public void actionPerformed(java.awt.event.ActionEvent e) {
					
					
					String tipoCript= getJComboBox().getSelectedItem().toString();
					String PBE = "PBE";
					
					if(tipoCript.equals(PBE)){
						
									
					PBE("Senha boa");
				    // Encrypt
					dadosTexto = getJTextArea().getText();
					encryptPBE(dadosTexto);
					
					
					
					
					
					
					
					
					
					
					}
					
					
					
					
					
				}
			});
		}
		return jButtonCriptografar;
	}

	/**
	 * This method initializes jButtonDecritografar	
	 * 	
	 * @return javax.swing.JButton	
	 */
	private JButton getJButtonDecritografar() {
		if (jButtonDecritografar == null) {
			jButtonDecritografar = new JButton();
			jButtonDecritografar.setText("Decriptografar");
			jButtonDecritografar.setBounds(new Rectangle(474, 62, 145, 28));
			jButtonDecritografar.addActionListener(new java.awt.event.ActionListener() {
				public void actionPerformed(java.awt.event.ActionEvent e) {
					decryptPBE(dadosCod);
					
					
					jLabelTexto.setText("Texto não criptografado :");
					
					
				}
			});
		}
		return jButtonDecritografar;
	}

	/**
	 * This method initializes jTextArea	
	 * 	
	 * @return javax.swing.JTextArea	
	 */
	private JTextArea getJTextArea() {
		if (jTextArea == null) {
			jTextArea = new JTextArea();
			jTextArea.setBounds(new Rectangle(15, 53, 398, 158));
		}
		return jTextArea;
	}

	/**
	 * This method initializes jButtonSalvarArquivoDeDados	
	 * 	
	 * @return javax.swing.JButton	
	 */
	private JButton getJButtonSalvarArquivoDeDados() {
		if (jButtonSalvarArquivoDeDados == null) {
			jButtonSalvarArquivoDeDados = new JButton();
			jButtonSalvarArquivoDeDados.setText("Carregar dados.dat");
			jButtonSalvarArquivoDeDados.setBounds(new Rectangle(473, 94, 148, 28));
			jButtonSalvarArquivoDeDados
					.addActionListener(new java.awt.event.ActionListener() {
						public void actionPerformed(java.awt.event.ActionEvent e) {
							 String line_str;

						        try{
						            javax.swing.JFileChooser arquivo = new javax.swing.JFileChooser();
						            arquivo.setFileFilter(new DatFilter());
						            if(arquivo.showOpenDialog(arquivo) == javax.swing.JFileChooser.APPROVE_OPTION){
						                File file = arquivo.getSelectedFile();

						                String textoEntrada = "";
						                
						                java.io.FileInputStream isTwo = new java.io.FileInputStream(  "" +file.getPath() );
						                java.io.DataInputStream dsTwo = new java.io.DataInputStream(isTwo);

						                dados.removeAllElements();
						                
						                jLabelTexto.setText("Texto criptografado :");
						                jLabelDados.setText("Dados .... OK");
						                
						                while((line_str = dsTwo.readLine()) != null){
						                    dados.add( line_str );
						                    textoEntrada +=  line_str + "\n";
						                    dadosCod=textoEntrada;
						                }
						                
						                getJTextArea().setText(textoEntrada);

						                dsTwo.close( );
						            }
						        }catch (java.io.IOException e2) {
						            javax.swing.JOptionPane.showMessageDialog( null, "File error: " + e.toString() );
						        }
						  
						}
					});
		}
		return jButtonSalvarArquivoDeDados;
	}

	/**
	 * This method initializes jButtonCrregarChave	
	 * 	
	 * @return javax.swing.JButton	
	 */
	
   

    
	
	private JButton getJButtonCrregarChave() {
		if (jButtonCrregarChave == null) {
			jButtonCrregarChave = new JButton();
			jButtonCrregarChave.setText("Carregar Chave");
			jButtonCrregarChave.setBounds(new Rectangle(473, 126, 148, 28));
			jButtonCrregarChave.addActionListener(new java.awt.event.ActionListener() {
				public void actionPerformed(java.awt.event.ActionEvent e) {
//					 TODO add your handling code here:
			        String line_str;

			        try{
			            javax.swing.JFileChooser arquivo = new javax.swing.JFileChooser();
			            arquivo.setFileFilter(new KeyFilter());
			            if(arquivo.showOpenDialog(arquivo) == javax.swing.JFileChooser.APPROVE_OPTION){
			                File file = arquivo.getSelectedFile();

			                String textoEntrada = "";
			                
			                java.io.FileInputStream isTwo = new java.io.FileInputStream(  "" +file.getPath() );
			                java.io.DataInputStream dsTwo = new java.io.DataInputStream(isTwo);

			                dados.removeAllElements();
			                
			                while((line_str = dsTwo.readLine()) != null){
			                    dados.add( line_str );
			                    textoEntrada +=  line_str + "\n";
			                }
			                
			                chave = textoEntrada ;
			                jLabel.setText("Chave .... OK");
			                
			                

			                dsTwo.close( );
			            }
			        }catch (java.io.IOException e2) {
			            javax.swing.JOptionPane.showMessageDialog( null, "File error: " + e.toString() );
			        }
			    }//GEN-LAST:event_bAbrirActionPerformed
			    
			    
			});
		}
		return jButtonCrregarChave;
	}

	/**
	 * This method initializes jComboBox	
	 * 	
	 * @return javax.swing.JComboBox	
	 */
	private JComboBox getJComboBox() {
		if (jComboBox == null) {
			jComboBox = new JComboBox();
			jComboBox.setBounds(new Rectangle(15, 240, 175, 25));
			jComboBox.addItem("PBE");
			jComboBox.addItem("AES");
			jComboBox.addItem("DES");
			jComboBox.addItem("TRIPLEDES");
			jComboBox.addItem("BLOW FISH");
			
		}
		return jComboBox;
	}
	
	
	
	public void PBE(String senha) {
		try {
			// Especificacao das Chave PBE - senha + salt + iteraçoes - 
			KeySpec keySpec = new PBEKeySpec(senha.toCharArray(), 
			                                  salt, 
			                                  iterationCount);
			// fabrica de chaves PBE                                  
			SecretKeyFactory fabricaChaves = SecretKeyFactory.getInstance("PBEWithMD5AndDES"); 
			// gerar a chave secreta, a partir da esepcificacao                                
			SecretKey chaveSecreta = fabricaChaves.generateSecret(keySpec);
			byte minhaChave[] = chaveSecreta.toString().getBytes(); 
			
			chave = minhaChave.toString();
			String dir = "c:/sua_chave.key";
			FileOutputStream out = new FileOutputStream(dir);

				out.write(minhaChave);

				out.close();
				JOptionPane.showMessageDialog(null, "Sua cheve esta salva no c:, como sua_chave.key.");
			
			
			
			// criando cifradores
			ecipher = Cipher.getInstance(chaveSecreta.getAlgorithm());
			dcipher = Cipher.getInstance(chaveSecreta.getAlgorithm());

			// criando especificacao para cifradores
			AlgorithmParameterSpec especCifradores = new PBEParameterSpec(salt, 
			                                                              iterationCount);

			//inicializando os cifradores
			ecipher.init(Cipher.ENCRYPT_MODE, chaveSecreta, especCifradores);
			dcipher.init(Cipher.DECRYPT_MODE, chaveSecreta, especCifradores);
			
		} catch (Exception exc) {
			exc.printStackTrace();
		}
	}
	public String encryptPBE(String mensagem) {
		try {
			
			// Encode the string into bytes using utf-8
			byte[] utf8 = mensagem.getBytes("UTF8");

			// Encriptou...
			byte[] enc = ecipher.doFinal(utf8);

			// Codifica o array de bytes em uma string Base64
			
			
			
			byte b[] = enc;

			String dados ="c:/dados.dat";

			FileOutputStream out = new FileOutputStream(dados);

			out.write(b);
			

			out.close();
			
			JOptionPane.showMessageDialog(null, "Seu arquivo de dados esta salvo no c:, como dados.dat .");
			
			return new sun.misc.BASE64Encoder().encode(enc);
		} catch (Exception exc) {
			exc.printStackTrace();
		} 
		return null;
	}
	public String decryptPBE(String Cod) {
		try {
			
			
			
			// Decode base64 to get bytes
			byte[] dec = new sun.misc.BASE64Decoder().decodeBuffer(Cod);
			
			
			
			// Decrypt
			byte[] utf8 = dcipher.doFinal(dec);
			System.out.println(utf8);
			
			

			// Decode using utf-8
			return new String(utf8, "UTF8");
          
		} catch (Exception exc) {
			exc.printStackTrace();
		} 
		return null;
	}

	
	
	
	

}

Mas tem uma coisa curiosa : tenho um exemplo funcionando bem simples que quando eu tentei rodalo da mesma forma funcionou certinho, mas a msm criptografada é diferente, mesmo senha e chave iguais.

o codigo simples é esse:
import java.security.spec.AlgorithmParameterSpec;
import java.security.spec.KeySpec;

import javax.crypto.*;
import javax.crypto.spec.PBEKeySpec;
import javax.crypto.spec.PBEParameterSpec;
import javax.security.*;


public class PBEexemplo {
	Cipher ecipher;
	Cipher dcipher;

	// 8-byte Salt
	byte[] salt =
		{
			(byte) 0xA9, (byte) 0x9B,
			(byte) 0xC8, (byte) 0x32,
			(byte) 0x56, (byte) 0x35,
			(byte) 0xE3, (byte) 0x03 };

	// Iteration count
	int iterationCount = 19;

	public PBEexemplo(String senha) {
		try {
			// Especificacao das Chave PBE - senha + salt + iteraçoes - 
			KeySpec keySpec = new PBEKeySpec(senha.toCharArray(), 
			                                  salt, 
			                                  iterationCount);
			// fabrica de chaves PBE                                  
			SecretKeyFactory fabricaChaves = SecretKeyFactory.getInstance("PBEWithMD5AndDES"); 
			// gerar a chave secreta, a partir da esepcificacao                                
			SecretKey chaveSecreta = fabricaChaves.generateSecret(keySpec);
			
			// criando cifradores
			ecipher = Cipher.getInstance(chaveSecreta.getAlgorithm());
			dcipher = Cipher.getInstance(chaveSecreta.getAlgorithm());

			// criando especificacao para cifradores
			AlgorithmParameterSpec especCifradores = new PBEParameterSpec(salt, 
			                                                              iterationCount);

			//inicializando os cifradores
			ecipher.init(Cipher.ENCRYPT_MODE, chaveSecreta, especCifradores);
			dcipher.init(Cipher.DECRYPT_MODE, chaveSecreta, especCifradores);
			
		} catch (Exception exc) {
			exc.printStackTrace();
		}
	}

    /**
     * metodo para criptografar 
     * @param msgString string com msg
     * 
     * @return string criptografada em formato Base64
     */
	public String encrypt(String msgString) {
		try {
			// Encode the string into bytes using utf-8
			byte[] utf8 = msgString.getBytes("UTF8");

			// Encriptou...
			byte[] enc = ecipher.doFinal(utf8);

			// Codifica o array de bytes em uma string Base64
			return new sun.misc.BASE64Encoder().encode(enc);
		} catch (Exception exc) {
			exc.printStackTrace();
		} 
		return null;
	}


    /**
     * 
     * @param str
     * @return
     */
	public String decrypt(String str) {
		try {
			// Decode base64 to get bytes
			byte[] dec = new sun.misc.BASE64Decoder().decodeBuffer(str);

			// Decrypt
			byte[] utf8 = dcipher.doFinal(dec);

			// Decode using utf-8
			return new String(utf8, "UTF8");
		} catch (Exception exc) {
			exc.printStackTrace();
		} 
		return null;
	}



	public static void main(String[] args) {		
		try {
			// Create encrypter/decrypter class
			PBEexemplo encrypter = new PBEexemplo("Senha boa");

			// Encrypt
			String encrypted = encrypter.encrypt("ABC");
             System.out.println("encriptado " + encrypted);

			// Decrypt
			String decrypted = encrypter.decrypt(encrypted);
			System.out.println("decriptado " + decrypted );
			
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}

OB.: no 1° codigo o que grava ele o arquivo com msm criptografada a msm criptografada é essa: "Ë6R?ëiz" já no 2° codigo ( o que esta funcionando direitinho ) a msm cript. é essa: "H8s2UofraXo="

Será que o ploblema tem haver com a falta de algum tratamento ao gravar e ler o arquivo na maquina e depois decriptografalo, e se form como eu faço isso?

Muito obrigado a todos

Criado 21 de abril de 2008
Respostas 0
Participantes 1