RSA-Keys to/from File

xrax

Erfahrenes Mitglied
Hallo zusammen,
der folgende Code soll beide RSA-Keys in jeweils ein File speichern und wieder auslesen. Leider erhalte ich den Fehler:
"Exception in thread "main" java.security.spec.InvalidKeySpecException: java.security.InvalidKeyException: IOException: algid parse error, not a sequence
at sun.security.rsa.RSAKeyFactory.engineGeneratePublic(RSAKeyFactory.java:188).........................................."

Was mache ich falsch? Gibts einen besseren Weg?

Betsen Dank
xrax

Code:
package tryanderror;

import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.security.Key;
import java.security.KeyFactory;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.X509EncodedKeySpec;

import javax.crypto.Cipher;

public class Crypt {
    
    public static void main(String[] args)throws Exception{
        
        KeyPairGenerator kpg = KeyPairGenerator.getInstance( "RSA" );
        kpg.initialize( 1024 );
        KeyPair keyPair = kpg.genKeyPair();
        
        Key pub=keyPair.getPublic();
        Key priv=keyPair.getPrivate();
        
        byte[] pubArray=pub.getEncoded();
        byte[] privArray=priv.getEncoded();
        
        File pubFile=new File("D:\\test\\pub.txt");
        File privFile=new File("D:\\test\\priv.txt");
        
        FileOutputStream keyfos = new FileOutputStream(pubFile);
        keyfos.write(pubArray);
        keyfos.close();
        
        keyfos = new FileOutputStream(privFile);
        keyfos.write(privArray);
        keyfos.close();

        DataInputStream dis = new DataInputStream(new FileInputStream(pubFile));
        pubArray = new byte[(int)pubFile.length()];
        dis.readFully(pubArray);
        dis.close();

        dis = new DataInputStream(new FileInputStream(privFile));
        privArray = new byte[(int)privFile.length()];
        dis.readFully(privArray);
        dis.close();
        
        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        
        X509EncodedKeySpec spec = new X509EncodedKeySpec(pubArray);
        RSAPublicKey pubKey = (RSAPublicKey) keyFactory.generatePublic(spec);
        
        spec = new X509EncodedKeySpec(privArray);
        RSAPrivateKey privKey = (RSAPrivateKey) keyFactory.generatePublic(spec);
        
        String toEncrypt="abc";
        byte[] enc=toEncrypt.getBytes();
        
        Cipher cipher = Cipher.getInstance( "RSA" ); 
        cipher.init( Cipher.ENCRYPT_MODE, pubKey ); 
        byte[] verschlüsselt = cipher.doFinal( enc );
         
        cipher.init( Cipher.DECRYPT_MODE, privKey ); 
        byte[] entschlüsselt = cipher.doFinal( verschlüsselt );

        System.out.println( new String(entschlüsselt) );
    }
}
 
Zurück