Wednesday, October 26, 2016

Using the Cipher Class for File Encryption



{snip}

    fileChooser1.setFileFilter(new BBSFilter());
    if(fileChooser1.APPROVE_OPTION != fileChooser1.showOpenDialog(this)) return;
    clearFileName = fileChooser1.getSelectedFile().getPath();
    File clearFile = new File(clearFileName);
    int prefix = clearFileName.length()-4;
    cryptoFileName = (clearFileName.substring(0,prefix)).concat(".XXX");
    File cryptoFile = new File(cryptoFileName);
    plainFileName = (clearFileName.substring(0,prefix)).concat(".TXT");
    File plainFile = new File(plainFileName);

    byte[] keyBytes = new byte[] {
           0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
           0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
           0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17 };
    byte[] ivBytes = new byte[] {
           0x00, 0x01, 0x02, 0x03, 0x00, 0x01, 0x02, 0x03,
           0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01 };

    try{

      SecretKeySpec key = new SecretKeySpec(keyBytes,"Twofish");
      IvParameterSpec ivSpec = new IvParameterSpec(ivBytes);
      Cipher cipher = Cipher.getInstance("Twofish/CTR/NoPadding","BC");

      // encryption pass
      cipher.init(Cipher.ENCRYPT_MODE, key, ivSpec);
      FileInputStream fis = new FileInputStream(clearFile);
      BufferedInputStream bis = new BufferedInputStream(fis,DSKBLOK);
      CipherInputStream cis = new CipherInputStream(bis,cipher);
      FileOutputStream fos = new FileOutputStream(cryptoFile);
      BufferedOutputStream bos = new BufferedOutputStream(fos,DSKBLOK);
      int ch; while((ch = cis.read()) >= 0) bos.write(ch);
      bos.flush(); bos.close();

      // decryption pass
      cipher.init(Cipher.DECRYPT_MODE, key, ivSpec);
      fis = new FileInputStream(cryptoFileName);
      bis = new BufferedInputStream(fis,DSKBLOK);
      cis = new CipherInputStream(bis,cipher);
      fos = new FileOutputStream(plainFile);
      bos = new BufferedOutputStream(fos,DSKBLOK);
      while ((ch = cis.read()) >= 0) bos.write(ch);
      bos.flush(); bos.close();
    } catch(Exception ee) { statusBar.setText("\n   Oooops!\n"); }


{snip}

No comments: