Problema no 2ª vez, Encripta

13 respostas
A

Pessoal,

Fiz o esquema para encryptar... mas caso eu deseje salvar o texto, fechar o programa na próxima vez qeu eu abrir ele não consegue desencryptar o mesmo texto....

Abaixo estão o código para vocês testarem...

import javax.crypto.*;

public class DesEncrypter {
        Cipher ecipher;
        Cipher dcipher;
    
        DesEncrypter(SecretKey key) {
            try {
                ecipher = Cipher.getInstance("DES");
                dcipher = Cipher.getInstance("DES");
                ecipher.init(Cipher.ENCRYPT_MODE, key);
                dcipher.init(Cipher.DECRYPT_MODE, key);
    
            } catch (javax.crypto.NoSuchPaddingException e) {
            } catch (java.security.NoSuchAlgorithmException e) {
            } catch (java.security.InvalidKeyException e) {
            }
        }
    
        public String encrypt(String str) {
            try {
                // Encode the string into bytes using utf-8
                byte[] utf8 = str.getBytes("UTF8");
    
                // Encrypt
                byte[] enc = ecipher.doFinal(utf8);
    
                // Encode bytes to base64 to get a string
                return new sun.misc.BASE64Encoder().encode(enc);
            } catch (javax.crypto.BadPaddingException e) {
            } catch (IllegalBlockSizeException e) {
            } catch (java.io.IOException e) {
            }
            return null;
        }
    
        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 (javax.crypto.BadPaddingException e) {
            } catch (IllegalBlockSizeException e) {
            } catch (java.io.IOException e) {
            }
            return null;
        }
    }
import javax.swing.*;
import javax.crypto.*;
import java.awt.*;
import java.awt.event.*;
import java.util.*;

public class Princ1 extends JFrame{
	
	JTextArea text, texto;
	JPanel p, p1, p2;
	JButton encry, decry;
	SecretKey key;
    DesEncrypter descry;
	
	public Princ1(){
		super( "Encriptar Texto !" );
		try{
		key = KeyGenerator.getInstance("DES").generateKey();
   		descry = new DesEncrypter(key);
   		}
   		catch(java.security.NoSuchAlgorithmException e){}
        p = new JPanel();p1 = new JPanel();p2 = new JPanel();
        p1.setLayout( new FlowLayout() );
        Container c = getContentPane();
		c.setLayout ( new BorderLayout() );
        JLabel titulo=new JLabel("Digite o texto: ");
		p.add(titulo);
		p.add(text = new JTextArea(4,25));
		
		p1.add(decry=new JButton("<<< Desencryptar"));
		p1.add(encry=new JButton("Encryptar >>>"));
		        
        p2.add(texto=new JTextArea(4,25));
        encry.addActionListener( new ActionListener() {
				public void actionPerformed( ActionEvent e )
				{
			        // Encrypt
			        String testee = descry.encrypt(text.getText());
					texto.setText(testee);
				}
			}
			);
    
        decry.addActionListener( new ActionListener() {
				public void actionPerformed( ActionEvent e )
				{
			        // Decrypt
			        String tested = descry.decrypt(texto.getText());					
					text.setText(tested);
				}
			}
			);
		c.add( p, BorderLayout.NORTH );
		c.add( p1, BorderLayout.CENTER );
		c.add( p2, BorderLayout.SOUTH );
			
	}
	public static void main( String x[] )
	{
		Princ1 tela = new Princ1();
		tela.setSize( 280, 220 );
		tela.show();
		tela.addWindowListener( new WindowAdapter() {
			public void windowClosing( WindowEvent e )
			{
				System.exit( 0 );
			}
		}
	);
	}
}

13 Respostas

danieldestro

Isso ocorre pois a cada execução da sua aplicação ele gera uma nova chave e você não consegue decriptar.

Eu acabei testando duas soluções no meu caso:

  1. Criar uma chave, serializar o objeto e utilizar sempre este objeto para encriptar e decriptar.

  2. Criar um certificado digital extrair a chave dele pra usar na (de)criptação.

A

Com faço então para usar esta função, e resolver o problema??

danieldestro

Para trabalhar com a criptografia, com MD5 e RSA.

package br.com.guj.crypto;

import java.util.*;
import java.security.*;
import java.security.spec.*;

import java.io.InputStream;
import java.io.FileInputStream;

public class Criptografia {

	private static final String algorithm = "RSA";
	private static final String signature = "MD5withRSA";

	private static PrivateKey privateKey;
	private static PublicKey publicKey;

	public static void main(String[] args) {
		String txt = "String a ser encriptada";

		try {
			KeyPair kp = generateKeyPair();
			privateKey = kp.getPrivate();
			publicKey = kp.getPublic();

			byte[] txtAssinado = createSignature( privateKey, txt.getBytes() );

			if( verifySignature( publicKey, txt.getBytes(), txtAssinado ) ) {
				System.out.println("Assinatura OK!");
			} else {
				System.out.println("Assinatura NOT OK!");
			}

		} catch( Exception e ) {
			e.printStackTrace();
		}
	}

	private static KeyPair generateKeyPair() throws Exception {
		// Generate a 1024-bit Digital Signature Algorithm (DSA) key pair
		KeyPairGenerator keyGen = KeyPairGenerator.getInstance( algorithm );
		keyGen.initialize(1024);
		KeyPair keypair = keyGen.genKeyPair();
		return keypair;
	}

    public static PrivateKey getPrivateKeyFromInputStream( InputStream is, String name, String password ) throws Exception {
        KeyStore ks = KeyStore.getInstance ( "JKS" );
        char[] pwd = password.toCharArray();
        ks.load( is, pwd );
        is.close();
        Key key = ks.getKey( name, pwd );
        if( key instanceof PrivateKey ) {
            return (PrivateKey) key;
        }
        return null;
    }

    public static PrivateKey getPrivateKeyFromFile( String certFile, String name, String pwd ) throws Exception {
        InputStream is = new FileInputStream( certFile );
        return getPrivateKeyFromInputStream( is, name, pwd );
    }

    public static PrivateKey getPrivateKeyFromResource( String certFile, String name, String pwd ) throws Exception {
        InputStream is = Thread.currentThread().getContextClassLoader().getResourceAsStream( certFile );
        return getPrivateKeyFromInputStream( is, name, pwd );
    }

	/**
     * Returns the signature for the given buffer of bytes using the private key.
     */
	public static byte[] createSignature(PrivateKey key, byte[] buffer) throws Exception {
		Signature sig = Signature.getInstance( signature ); //key.getAlgorithm());
		sig.initSign(key);
		sig.update(buffer, 0, buffer.length);
		return sig.sign();
	}

	/**
     * Verifies the signature for the given buffer of bytes using the public key.
     */
	public static boolean verifySignature(PublicKey key, byte[] buffer, byte[] sign) throws Exception {
		Signature sig = Signature.getInstance( signature ); //key.getAlgorithm());
		sig.initVerify(key);
		sig.update(buffer, 0, buffer.length);
		return sig.verify( sign );
	}

	public static byte[] getKeyedDigest(byte[] buffer, byte[] key) throws Exception {
		MessageDigest md5 = MessageDigest.getInstance( algorithm );
		md5.update(buffer);
		return md5.digest(key);
	}
	
	public static String txt2Hexa(byte[] bytes) {
        if( bytes == null ) return null;
		String hexDigits = "0123456789abcdef"; 
		StringBuffer sbuffer = new StringBuffer();
		for (int i = 0; i < bytes.length; i++) {
			int j = ((int) bytes[i]) & 0xFF;
			sbuffer.append(hexDigits.charAt(j / 16));
			sbuffer.append(hexDigits.charAt(j % 16));
		}
		return sbuffer.toString();
	}
}

Para gerar o certificado digital:

keytool -genkey -alias nome_da_sua_key -keyalg RSA -dname "cn=Sua Empresa, ou=Departamento, o=Sua Empresa, S=SP, c=BR" -keystore c:meucertificado.jks -storepass SENHA123
danieldestro

Amigão…
Empolgado com este post, eu fiz o artigo sobre certificado e assinatura digital. Dá uma olhada aí:

http://www.guj.com.br/user.article.get.chain?page=1&article.id=141

A
Eu fiz esta classe
import javax.swing.*;
import javax.crypto.*;
import java.awt.*;
import java.awt.event.*;
import java.util.*;

public class Encry extends JFrame{
	
	JTextArea text, texto;
	JPanel p, p1, p2;
	JButton encryb, decry;
	Encrypter obj;
	
	public Encry(){
		super( "Encriptar Texto !" );
        p = new JPanel();p1 = new JPanel();p2 = new JPanel();
        p1.setLayout( new FlowLayout() );
        Container c = getContentPane();
		c.setLayout ( new BorderLayout() );
        JLabel titulo=new JLabel("Digite o texto: ");
		p.add(titulo);
		p.add(text = new JTextArea(4,25));
		
		p1.add(decry=new JButton("<<< Desencryptar"));
		p1.add(encryb=new JButton("Encryptar >>>"));
		        
        p2.add(texto=new JTextArea(4,25));
        encryb.addActionListener( new ActionListener() {
				public void actionPerformed( ActionEvent e )
				{
			        // Encrypt
			        String recebe=text.getText();
			        recebe.trim();
			        String testee = obj.encrypt(recebe);
			        texto.setText(testee);
				}
			}
			);
    
        decry.addActionListener( new ActionListener() {
				public void actionPerformed( ActionEvent e )
				{
			        // Decrypt
			        String tested = obj.decrypt(texto.getText());					
					text.setText(tested);
				}
			}
			);
		c.add( p, BorderLayout.NORTH );
		c.add( p1, BorderLayout.CENTER );
		c.add( p2, BorderLayout.SOUTH );
			
	}
	public static void main( String x[] )
	{
		Encry tela = new Encry();
		tela.setSize( 280, 220 );
		tela.show();
		tela.addWindowListener( new WindowAdapter() {
			public void windowClosing( WindowEvent e )
			{
				System.exit( 0 );
			}
		}
	);
	}
}

Para manipular a Encrypter mas recebo a mensagem de NullPointerException o que pode ser??

danieldestro

Veja em que linha ocorre o NullPointerException… esse erro ocorre porquÊ você está tentando usar um objeto que não existe, ou seja, sua variável não aponta pra nenhum objeto, ela é null.

A

Veja em que linha ocorre o NullPointerException… esse erro ocorre porquÊ você está tentando usar um objeto que não existe, ou seja, sua variável não aponta pra nenhum objeto, ela é null.

E como posso fazer para corrigir isto?

danieldestro

Na própria msg de erro ele fala a linha em que ocorre o NullPointerException.

A

Mas qual a solução… Eu não sei mais o que fazer para resolver isto !!

danieldestro

O erro está nesta linha:

String tested = obj.decrypt(texto.getText());

Você não está instanciando “obj”, que é do tipo Encrypter.

A
"danieldestro":
O erro está nesta linha:

String tested = obj.decrypt(texto.getText());

Você não está instanciando "obj", que é do tipo Encrypter.

Cara arrumei a classe mas quanod eu vou desencriuptar uma string ja encriptada sem antes encripta-la ele não consegue desencriptar o que pdoe ser....

ai vai o código corrigido

import javax.swing.*; 
import javax.crypto.*; 
import java.awt.*; 
import java.awt.event.*; 
import java.util.*; 

public class Encry extends JFrame{ 
    
   JTextArea text, texto; 
   JPanel p, p1, p2; 
   JButton encryb, decry; 
   Encrypter obj=new Encrypter(); 
    
   public Encry(){ 
      super( "Encriptar Texto !" ); 
        p = new JPanel();p1 = new JPanel();p2 = new JPanel(); 
        p1.setLayout( new FlowLayout() ); 
        Container c = getContentPane(); 
      c.setLayout ( new BorderLayout() ); 
        JLabel titulo=new JLabel("Digite o texto: "); 
      p.add(titulo); 
      p.add(text = new JTextArea(4,25)); 
       
      p1.add(decry=new JButton("<<< Desencryptar")); 
      p1.add(encryb=new JButton("Encryptar >>>")); 
              
        p2.add(texto=new JTextArea(4,25)); 
        encryb.addActionListener( new ActionListener() { 
            public void actionPerformed( ActionEvent e ) 
            { 
                 // Encrypt 
                 String recebe=text.getText(); 
                 recebe.trim(); 
                 String testee = obj.encrypt(recebe); 
                 texto.setText(testee); 
            } 
         } 
         ); 
    
        decry.addActionListener( new ActionListener() { 
            public void actionPerformed( ActionEvent e ) 
            { 
                // Decrypt 
                String recebe=texto.getText();
                recebe.trim();
                String tested = obj.decrypt(recebe);                
               	text.setText(tested); 
            } 
         } 
         ); 
      c.add( p, BorderLayout.NORTH ); 
      c.add( p1, BorderLayout.CENTER ); 
      c.add( p2, BorderLayout.SOUTH ); 
          
   } 
   public static void main( String x[] ) 
   { 
      Encry tela = new Encry(); 
      tela.setSize( 280, 220 ); 
      tela.show(); 
      tela.addWindowListener( new WindowAdapter() { 
         public void windowClosing( WindowEvent e ) 
         { 
            System.exit( 0 ); 
         } 
      } 
   ); 
   } 
}
danieldestro

cara… você leu todo esta POST?

Na segunda mensagem, que é a minha, eu falo o que pode estar acontecendo… le tudo de novo e vê se voce saca alguma coisa… senao aconselho vc a ler o artigo que eu fiz…

R

por favor alguem pode me dizer que erro seria esse : ERRO: NAO FOI POSSIVEL OBTER A LISTA DE CSP
ESTOU FAZENDO UM CADASTRO NO SITE DO SERPRO PARA CERTIFICADO DIGITAL, E NO FINAL DA ESSA MENSAGEM AI…

Criado 24 de maio de 2004
Ultima resposta 24 de jul. de 2008
Respostas 13
Participantes 3