How to encrypt or decrypt a file in Java?

I want to encrypt and decrypt a file in java, I read this url http://www-users.york.ac.uk/~mal503/lore/pkencryption.htm , and I have two files, namely: public Security certificate and private security certificate file and private.pem file, I copied these files and pasted them into the current directory and worte java code as follows, when I run it, encryption or decryption is not performed, see this and tell me where I made a mistake

Encrypt code

File ecryptfile=new File("encrypt data"); File publickeydata=new File("/publickey"); File encryptmyfile=new File("/sys_data.db"); File copycontent =new File("Copy Data"); secure.makeKey(); secure.saveKey(ecryptfile, publickeydata); secure.encrypt(encryptmyfile, copycontent); 

Decrypt Code

 File ecryptfile=new File("encrypt data"); File privateKeyFile=new File("/privatekey"); File encryptmyfile=new File("/sys_data.db"); File unencryptedFile =new File("unencryptedFile"); try { secure.loadKey(encryptmyfile, privateKeyFile); secure.decrypt(encryptmyfile, unencryptedFile); } catch (GeneralSecurityException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } 
+4
source share
2 answers

You just messed up your files. This code works using DER files generated from openssl, as described in the article you linked:

  FileEncryption secure = new FileEncryption(); // Encrypt code { File encryptFile = new File("encrypt.data"); File publicKeyData = new File("public.der"); File originalFile = new File("sys_data.db"); File secureFile = new File("secure.data"); // create AES key secure.makeKey(); // save AES key using public key secure.saveKey(encryptFile, publicKeyData); // save original file securely secure.encrypt(originalFile, secureFile); } // Decrypt code { File encryptFile = new File("encrypt.data"); File privateKeyFile = new File("private.der"); File secureFile = new File("secure.data"); File unencryptedFile = new File("unencryptedFile"); // load AES key secure.loadKey(encryptFile, privateKeyFile); // decrypt file secure.decrypt(secureFile, unencryptedFile); } 
+9
source

Here is the simplest piece of code to encrypt a document with any key (here's a random key)

 randomKey = randomKey.substring(0, 16); keyBytes = randomKey.getBytes(); key = new SecretKeySpec(keyBytes, "AES"); paramSpec = new IvParameterSpec(iv); ecipher = Cipher.getInstance("AES/CBC/PKCS5Padding"); ecipher.init(Cipher.ENCRYPT_MODE, key, paramSpec); in = new FileInputStream(srcFile); out = new FileOutputStream(encryptedFile); out = new CipherOutputStream(out, ecipher); int numRead = 0; while ((numRead = in.read(buf)) >= 0) { out.write(buf, 0, numRead); } in.close(); out.flush(); out.close(); 
+1
source

Source: https://habr.com/ru/post/1347685/


All Articles