Foros del Web » Programación para mayores de 30 ;) » Java »

FileEncryption

Estas en el tema de FileEncryption en el foro de Java en Foros del Web. Ole! Estoy desesperada con un tema del "FileEncryption", es una tonteria lo que me queda, pero no lo consigo...He encontrado este fichero que encripta/desencripta. openssl ...
  #1 (permalink)  
Antiguo 25/01/2012, 07:19
 
Fecha de Ingreso: septiembre-2011
Mensajes: 44
Antigüedad: 12 años, 7 meses
Puntos: 0
FileEncryption

Ole!

Estoy desesperada con un tema del "FileEncryption", es una tonteria lo que me queda, pero no lo consigo...He encontrado este fichero que encripta/desencripta.

openssl genrsa -out private.pem 2048

To get it into the required (PKCS#8, DER) format:
openssl pkcs8 -topk8 -in private.pem -outform DER -out private.der -nocrypt

To generate a public key from the private key:
openssl rsa -in private.pem -pubout -outform DER -out public.der

An example of how to use the code:
FileEncryption secure = new FileEncryption();

// to encrypt a file
secure.makeKey();
secure.saveKey(encryptedKeyFile, publicKeyFile);
secure.encrypt(fileToEncrypt, encryptedFile);

// to decrypt it again
secure.loadKey(encryptedKeyFile, privateKeyFile);
secure.decrypt(encryptedFile, unencryptedFile);


¿¿¿¿¿¿¿Qué tipo de fichero es "encryptedKeyFile????????¿¿Qué extensión le pongo???? he probado con .key, .pem, sin extensión etc.. y siempre me da el error "invalid key format"...ayudadme plisssssssssss


Código:

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.security.*;
import java.security.spec.*;

import javax.crypto.*;
import javax.crypto.spec.*;


public class FileEncryption {
	
	private static final int AES_Key_Size = 256;
	
	Cipher pkCipher, aesCipher;
	byte[] aesKey;
	SecretKeySpec aeskeySpec;
	
	/**
	 * Constructor: creates ciphers
	 */
	public FileEncryption() throws GeneralSecurityException {
            Provider sunjce = new com.sun.crypto.provider.SunJCE();
            Security.addProvider(sunjce);
            // create RSA public key cipher
            pkCipher = Cipher.getInstance("RSA");
	    // create AES shared key cipher
	    aesCipher = Cipher.getInstance("AES");
	}
	
	/**
	 * Creates a new AES key
	 */
	public void makeKey() throws NoSuchAlgorithmException {

            KeyGenerator kgen = KeyGenerator.getInstance("AES");
	    kgen.init(AES_Key_Size);
	    SecretKey key = kgen.generateKey();
	    aesKey = key.getEncoded();
	    aeskeySpec = new SecretKeySpec(aesKey, "AES");
	}

	/**
	 * Decrypts an AES key from a file using an RSA private key
	 */
	public void loadKey(File in, File privateKeyFile) throws GeneralSecurityException, IOException {
		// read private key to be used to decrypt the AES key
		byte[] encodedKey = new byte[(int)privateKeyFile.length()];
		new FileInputStream(privateKeyFile).read(encodedKey);
		
		// create private key
		PKCS8EncodedKeySpec privateKeySpec = new PKCS8EncodedKeySpec(encodedKey);
		KeyFactory kf = KeyFactory.getInstance("RSA");
		PrivateKey pk = kf.generatePrivate(privateKeySpec);
		
		// read AES key
		pkCipher.init(Cipher.DECRYPT_MODE, pk);
		aesKey = new byte[AES_Key_Size/8];
		CipherInputStream is = new CipherInputStream(new FileInputStream(in), pkCipher);
		is.read(aesKey);
		aeskeySpec = new SecretKeySpec(aesKey, "AES");
                System.out.println("Private AES key loaded.");
	}
	
	/**
	 * Encrypts the AES key to a file using an RSA public key
	 */
	public void saveKey(File out, File publicKeyFile) throws IOException, GeneralSecurityException {
		// read public key to be used to encrypt the AES key
		byte[] encodedKey = new byte[(int)publicKeyFile.length()];
		new FileInputStream(publicKeyFile).read(encodedKey);
		
		// create public key
		X509EncodedKeySpec publicKeySpec = new X509EncodedKeySpec(encodedKey);
		KeyFactory kf = KeyFactory.getInstance("RSA");
		PublicKey pk = kf.generatePublic(publicKeySpec);
		
		// write AES key
		pkCipher.init(Cipher.ENCRYPT_MODE, pk);
		CipherOutputStream os = new CipherOutputStream(new FileOutputStream(out), pkCipher);
		os.write(aesKey);
                System.out.println("Written AES key " + new String(aesKey));
		os.close();
	}
	
	/**
	 * Encrypts and then copies the contents of a given file.
	 */
	public void encrypt(File in, File out) throws IOException,
                            InvalidKeyException,
                            NoSuchAlgorithmException, 
                            NoSuchPaddingException {

            // aesCipher = Cipher.getInstance("AES");
            aesCipher.init(Cipher.ENCRYPT_MODE, aeskeySpec);

            FileInputStream is = new FileInputStream(in);
            CipherOutputStream os = new CipherOutputStream(new FileOutputStream(out), aesCipher);

            Long fileLength = in.length();
            System.out.println("File to encrypt: " + in.getName() + "; length: " + fileLength.toString() + " bytes.");

            copy(is, os);
            os.close();
            System.out.println("Encryption performed. Output in " + out.getAbsolutePath());
	}
	
	/**
	 * Decrypts and then copies the contents of a given file.
	 */
	public void decrypt(File in, File out) throws IOException, InvalidKeyException {
		aesCipher.init(Cipher.DECRYPT_MODE, aeskeySpec);

                Long fileLength;

		CipherInputStream is = new CipherInputStream(new FileInputStream(in), aesCipher);
		FileOutputStream os = new FileOutputStream(out);
		
		copy(is, os);
		
		is.close();
		os.close();

                fileLength = out.length();
                System.out.println("New file decrypted: " + out.getAbsolutePath() + "; length: " + fileLength.toString() + " bytes.");
	}
	
	/**
	 * Copies a stream.
	 */
	private void copy(InputStream is, OutputStream os) throws IOException {
		int i;
		byte[] b = new byte[1024];
		while((i=is.read(b))!=-1) {
			os.write(b, 0, i);
		}
	}
}
  #2 (permalink)  
Antiguo 07/02/2012, 14:54
 
Fecha de Ingreso: septiembre-2011
Mensajes: 44
Antigüedad: 12 años, 7 meses
Puntos: 0
Respuesta: FileEncryption

Gracias majos!

Ya lo solucioné, pero bueno, como nadie ha dicho nada, supongo que no interesa a nadie...
  #3 (permalink)  
Antiguo 08/02/2012, 15:10
Avatar de Xerelo  
Fecha de Ingreso: mayo-2009
Mensajes: 2.175
Antigüedad: 14 años, 11 meses
Puntos: 306
Respuesta: FileEncryption

Bueno, no todo el mundo puede solucionar tu problema o tiene tiempo para ello, sin embargo tú sí podrías haber puesto como lo solucionaste.
__________________
Cada vez que solucionas los problemas de alguien que no se esfuerza, piensa en que el día de mañana puede llegar a ser tu compañero de trabajo, o peor, tu jefe.

Etiquetas: desencriptar, encriptar, encryption
Atención: Estás leyendo un tema que no tiene actividad desde hace más de 6 MESES, te recomendamos abrir un Nuevo tema en lugar de responder al actual.
Respuesta




La zona horaria es GMT -6. Ahora son las 12:18.