I used the DES algorithm for encryption and decryption.
For encryption: here after encryption I write a file to save. You can save it with a different name (temp) and send it to the server. After sending successfully, you can delete this encrypted file.
FileOutputStream fos = null ; CipherInputStream cis; byte key[] = "abcdEFGH".getBytes(); SecretKeySpec secretKey = new SecretKeySpec(key,"DES"); Cipher encrypt = Cipher.getInstance("DES/ECB/PKCS5Padding"); encrypt.init(Cipher.ENCRYPT_MODE, secretKey); InputStream fis = new ByteArrayInputStream(fileData);//Here I am getting file data as byte array. You can convert your file data to InputStream by other way too. File dataFile = new File(dataDir,fileName); //dataDir is location where my file is stored if(!dataFile.exists()){ cis = new CipherInputStream(fis,encrypt); try { fos = new FileOutputStream(dataFile); byte[] b = new byte[8]; int i; while ((i=cis.read(b)) != -1) { fos.write(b, 0, i); } return fileName; } finally{ try { if(fos != null) { fos.flush(); fos.close(); } cis.close(); fis.close(); } catch (IOException e) { //IOException } } } return "";
To decrypt:
CipherInputStream cis; FileOutputStream fos = null; FileInputStream fis = null; File dataFile = new File(dataDir,fileName); // here I am getting encrypted file from server File newDataFile = new File(dataDir,fileName+"_TEMP"); // I am creating temporary decrypted file byte key[] = "abcdEFGH".getBytes(); SecretKeySpec secretKey = new SecretKeySpec(key,"DES"); Cipher decrypt = Cipher.getInstance("DES/ECB/PKCS5Padding"); decrypt.init(Cipher.DECRYPT_MODE, secretKey); try { fis = new FileInputStream(dataFile); } catch(Exception e) { //Exception } if(dataFile.exists()){ cis = new CipherInputStream(fis,decrypt); try { fos = new FileOutputStream(newDataFile); byte[] b = new byte[8]; int i; while ((i=cis.read(b)) != -1) { fos.write(b, 0, i); } return newDataFile; } finally{ try { if(fos != null) { fos.flush(); fos.close(); } cis.close(); fis.close(); } catch (IOException e) { //IOException } } }
source share