Erro com Serialize/Deserialize java

4 respostas
A

Pessoal, quem pode me ajudar? Eu serializei com o seguinte código preciso fazer o inverso, o deserialize:

Listing 20.19. Serialize the key pair to disk files

BigInteger mod = RSAprivKey.getModulus();

out = new FileOutputStream(outdir + RSAmod.dat);

out.write(mod.toByteArray());

out.flush(); out.close();
Na apostila fala desse, porém  erro. segue abaixo:

Listing 20.20. Deserialize the key pair in CryptoEngine constructor

Class c = this.getClass();

InputStream is;

is = c.getResourceAsStream("/keys/RSAmod.dat");

BigInteger RSAmod = new BigInteger(readFromStream(is));

is.close();
Eu criei esse abaixo mas acho que não é o correto:

BigInteger mod = RSAprivKey.getModulus();

out = new FileOutputStream(RSAmod.dat);

out.write(mod.toByteArray());

out.flush();

out.close();

Acho que não é correto por que me mostra assim, veja a private é diferente do privado depois de fazer o deserialize:
Private: org.bouncycastle.crypto.params.RSAPrivateCrtKeyParameters@e4f972
Public: org.bouncycastle.crypto.params.RSAKeyParameters@b4d3d5

Privado-: org.bouncycastle.crypto.params.RSAPrivateCrtKeyParameters@1bf52a5
Pupblico-: org.bouncycastle.crypto.params.RSAKeyParameters@1cafa9e

4 Respostas

Vini_Fernandes

Cara, o codigo abaixo serializa e deserializa uma classe e seus atributos. Veja se da pra seguir a diante e qualquer problema escreva novamente!

import java.io.*;
import java.util.*;

public class Teste2{
	public static void main(String [] asdf){
		A a = null;
		File f = null;
		try{
			//serializando
			String fileName = "a.txt";
			f = new File(fileName);
			ObjectOutputStream o = new ObjectOutputStream(new FileOutputStream (f));
			a = new A(10);
			a.b.x = 1234;
			o.writeObject(a);
			o.close();
			
			//deserializando	
			ObjectInputStream i = new ObjectInputStream (new FileInputStream (f));
			a = (A)i.readObject();
			
			System.out.println("teste 1: "+a.x);
			System.out.println("teste 2: "+a.b.x);
			
		}
		catch(Exception e){
			e.printStackTrace();
		}
		
		
	}
}

class A implements Serializable{
	int x = 89;
	B b = new B(77777);
	A(){}
	A(int x){
		this.x = x;
	}
}
class B implements Serializable{
	int x ;
	B(int z){
		x=z;
	}
}

abracao

LPJava

veja se este post ajuda:

link

A

Amigos, vai o meu código completo. Acho que está certo na hora de deserializar. Pois
Já deixei comentado as linhas que gera as chave automáticas e ele consegue ler os arquivos do disco e fazer
a encriptacao e descriptação.

Agora o problema é que no J2ME não aceita ou não reconhece os pacotes FileInputStream, FileOutputStream dos

pacotes

import java.io.FileInputStream;

import java.io.FileNotFoundException;

import java.io.FileOutputStream;

Assim não consigo armazenar ou persistir as chaves em arquivos. Alguém sabe??
Por ironia peguei essa parte de Serialização de um livro J2me e que na verdade não reconhece esses pacotes.

package rsa;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.math.BigInteger;
import java.security.SecureRandom;
import org.bouncycastle.crypto.AsymmetricBlockCipher;
import org.bouncycastle.crypto.AsymmetricCipherKeyPair;
import org.bouncycastle.crypto.encodings.PKCS1Encoding;
import org.bouncycastle.crypto.engines.RSAEngine;
import org.bouncycastle.crypto.generators.RSAKeyPairGenerator;
import org.bouncycastle.crypto.params.RSAKeyGenerationParameters;
import org.bouncycastle.crypto.params.RSAKeyParameters;
import org.bouncycastle.crypto.params.RSAPrivateCrtKeyParameters;

public class Encryption {

    /**
     * @param args the command line arguments
     */
    private RSAPrivateCrtKeyParameters _RSAPrivateKey;
    private RSAKeyParameters _RSAPublicKey;

    public static void main(String[] args) {
        // TODO code application logic here

        Encryption theEncryption = new Encryption();
        String theStringBeforeEncryption = "Boa noite cuiaba";
        String theStringAfterEncryption = null;
        byte[] theEncryptedString;
        try {
            System.out.println(theStringBeforeEncryption);
            theEncryption.generateRSAKeyPair();
            theEncryptedString = theEncryption.RSAEncrypt(theStringBeforeEncryption.getBytes());
            theStringAfterEncryption = new String(theEncryption.RSADecrypt(theEncryptedString));
            System.out.println(theStringAfterEncryption);

        } catch (Exception e) {
            // TODO Handle exception!
            e.printStackTrace();
        }

    }
  
    private RSAPrivateCrtKeyParameters RSAprivKey_des;
    private RSAKeyParameters RSApubKey_des;
 
    
    private void Deserialize() throws IOException, ClassNotFoundException  {
  
        FileInputStream fis = new FileInputStream("RSAmod.dat");   
        byte[] newArrayBytes = new byte[fis.available()];   
        fis.read(newArrayBytes);
        BigInteger RSAmod = new BigInteger(newArrayBytes);   
        fis.close(); 
        
        
        FileInputStream fis1 = new FileInputStream("RSAprivExp.dat");   
        byte[] newArrayBytes1 = new byte[fis1.available()];   
        fis1.read(newArrayBytes1);
           
        BigInteger RSAprivExp = new BigInteger(newArrayBytes1);   
        fis1.close(); 
        
        FileInputStream fis2 = new FileInputStream("RSApubExp.dat");   
        byte[] newArrayBytes2 = new byte[fis2.available()];   
        fis2.read(newArrayBytes2);
           
        BigInteger RSApubExp = new BigInteger(newArrayBytes2);   
        fis2.close(); 
        
        FileInputStream fis3 = new FileInputStream("RSAdp.dat");   
        byte[] newArrayBytes3 = new byte[fis3.available()];   
        fis3.read(newArrayBytes3);
           
        BigInteger RSAdp = new BigInteger(newArrayBytes3);   
        fis3.close(); 
        
        FileInputStream fis4 = new FileInputStream("RSAdq.dat");   
        byte[] newArrayBytes4 = new byte[fis4.available()];   
        fis4.read(newArrayBytes4);
           
        BigInteger RSAdq = new BigInteger(newArrayBytes4);   
        fis4.close();
        
        FileInputStream fis5 = new FileInputStream("RSAp.dat");   
        byte[] newArrayBytes5 = new byte[fis5.available()];   
        fis5.read(newArrayBytes5);
           
        BigInteger RSAp = new BigInteger(newArrayBytes5);   
        fis5.close();
        
        FileInputStream fis6 = new FileInputStream("RSAq.dat");   
        byte[] newArrayBytes6 = new byte[fis6.available()];   
        fis6.read(newArrayBytes6);
           
        BigInteger RSAq = new BigInteger(newArrayBytes6);   
        fis6.close();
        
        FileInputStream fis7 = new FileInputStream("RSAqInv.dat");   
        byte[] newArrayBytes7 = new byte[fis7.available()];   
        fis7.read(newArrayBytes7);
           
        BigInteger RSAqInv = new BigInteger(newArrayBytes7);   
        fis7.close();
        

        RSAprivKey_des = new RSAPrivateCrtKeyParameters(
                RSAmod, RSApubExp, RSAprivExp, RSAp,
                RSAq, RSAdp, RSAdq, RSAqInv);
        RSApubKey_des = new RSAKeyParameters(false, RSAmod, RSApubExp);

        
        System.out.println("Privado-: "+ RSAprivKey_des);
         System.out.println("Pupblico-: "+RSApubKey_des);

    }


    private void SerializetoFile(RSAPrivateCrtKeyParameters RSAprivKey) throws FileNotFoundException, IOException, Exception {
          
        FileOutputStream out;
        BigInteger pubExp;
        
        BigInteger mod = RSAprivKey.getModulus();
        out = new FileOutputStream("RSAmod.dat");
        out.write(mod.toByteArray());
        out.flush();
        out.close();

        BigInteger privExp = RSAprivKey.getExponent();
        out = new FileOutputStream("RSAprivExp.dat");
        out.write(privExp.toByteArray());
        out.flush();
        out.close();

        pubExp = RSAprivKey.getPublicExponent();
        if (!pubExp.equals(new BigInteger("10001", 16))) {
            throw new Exception("wrong public exponent");
        }
        
        out = new FileOutputStream("RSApubExp.dat");
        out.write(pubExp.toByteArray());
        out.flush();
        out.close();

        BigInteger dp = RSAprivKey.getDP();
        out = new FileOutputStream("RSAdp.dat");
        out.write(dp.toByteArray());
        out.flush();
        out.close();

        BigInteger dq = RSAprivKey.getDQ();
        out = new FileOutputStream("RSAdq.dat");
        out.write(dq.toByteArray());
        out.flush();
        out.close();

        BigInteger p = RSAprivKey.getP();
        out = new FileOutputStream("RSAp.dat");
        out.write(p.toByteArray());
        out.flush();
        out.close();

        BigInteger q = RSAprivKey.getQ();
        out = new FileOutputStream("RSAq.dat");
        out.write(q.toByteArray());
        out.flush();
        out.close();

        BigInteger qInv = RSAprivKey.getQInv();
        out = new FileOutputStream("RSAqInv.dat");
        out.write(qInv.toByteArray());
        out.flush();
        out.close();

    }
   
    private void generateRSAKeyPair() throws Exception {
        SecureRandom theSecureRandom = new SecureRandom();
        BigInteger thePublicExponent = new BigInteger("10001", 16);
        RSAKeyGenerationParameters theRSAKeyGenParam =
                new RSAKeyGenerationParameters(thePublicExponent, theSecureRandom, 1024, 80);
        RSAKeyPairGenerator theRSAKeyPairGen = new RSAKeyPairGenerator();
        theRSAKeyPairGen.init(theRSAKeyGenParam);
        AsymmetricCipherKeyPair theKeyPair = theRSAKeyPairGen.generateKeyPair();

        _RSAPrivateKey = (RSAPrivateCrtKeyParameters) theKeyPair.getPrivate();
        _RSAPublicKey = (RSAKeyParameters) theKeyPair.getPublic();

        System.out.println("Private: "+ _RSAPrivateKey );
        System.out.println("Public: "+ _RSAPublicKey );
        
        SerializetoFile(_RSAPrivateKey); 
        
        Deserialize();


    }

    private byte[] RSAEncrypt(byte[] toEncrypt) throws Exception {
        if (RSApubKey_des == null) {
            throw new Exception("Please generate RSA keys first in order to work");
        }

        
        
        AsymmetricBlockCipher theEngine = new RSAEngine();
        theEngine = new PKCS1Encoding(theEngine);
        theEngine.init(true, RSApubKey_des);
        return theEngine.processBlock(toEncrypt, 0, toEncrypt.length);
    }

    private byte[] RSADecrypt(byte[] toDecrypt) throws Exception {
        if (RSAprivKey_des == null) {
            throw new Exception("Please generate RSA keys first in order to work");
        }

        AsymmetricBlockCipher theEngine = new RSAEngine();
        theEngine = new PKCS1Encoding(theEngine);
        theEngine.init(false, RSAprivKey_des);
        return theEngine.processBlock(toDecrypt, 0, toDecrypt.length);
    }
}
A

s

Criado 11 de fevereiro de 2009
Ultima resposta 12 de fev. de 2009
Respostas 4
Participantes 3