Hacker Scripts..Based on a true story

Posted in Server Side Programming | Leave a comment

TechUtils.in

Hi Guys,

We have moved to out new Webpage: techutils.in

Please follow us there and also register.. ūüôā

Cheers

Posted in Server Side Programming | Leave a comment

How to create a Custom ADF Component

In this tutorial, we will create a custom ADF Component.

Create new files and package structure as shown:

Structure

Source Code of the required files is as below:

AlertDemo.java

package com.techutils.adf.jsf.faces.component;

import javax.faces.event.AbortProcessingException;
import javax.faces.event.FacesEvent;

import org.apache.myfaces.trinidad.bean.FacesBean;
import org.apache.myfaces.trinidad.bean.PropertyKey;
import org.apache.myfaces.trinidad.component.UIXObject;


public class AlertDemo extends UIXObject {
    public AlertDemo() {
        super(RENDERER_TYPE);
    }
    static public final FacesBean.Type TYPE =
        new FacesBean.Type(UIXObject.TYPE);

    static public final PropertyKey VISIBLE_KEY =
        TYPE.registerKey("visible", Boolean.class, Boolean.TRUE);

    static public final PropertyKey PARTIAL_TRIGGERS_KEY =
        TYPE.registerKey("partialTriggers", String[].class);

    static public final PropertyKey CLIENT_COMPONENT_KEY =
        TYPE.registerKey("clientComponent", Boolean.class);

    static public final String RENDERER_TYPE = "com.techutils.adf.jsf.AlertDemo";

    static public final String COMPONENT_TYPE = "com.techutils.adf.jsf.AlertDemo";

    public void setPartialTriggers(String[] newpartialTriggers) {
        setProperty(PARTIAL_TRIGGERS_KEY, newpartialTriggers);
    }

    public String[] getPartialTriggers() {
        return (String[])getProperty(PARTIAL_TRIGGERS_KEY);
    }

    @Override
    protected FacesBean.Type getBeanType() {
        return TYPE;
    }

    @Override
    public void broadcast(FacesEvent facesEvent) throws AbortProcessingException {
        super.broadcast(facesEvent);
    }

    public void setVisible(boolean newvisible) {
        setBooleanProperty(VISIBLE_KEY, newvisible);
    }

    public boolean isVisible() {
        return getBooleanProperty(VISIBLE_KEY, Boolean.TRUE);
    }

    static {
        // register the new TYPE by family and rendererType
        TYPE.lockAndRegister(UIXObject.COMPONENT_FAMILY, RENDERER_TYPE);
    }
}


AlertDemoRenderer.java

package com.techutils.adf.jsf.faces.renderer;

import com.techutils.adf.jsf.faces.component.AlertDemo;

import java.io.IOException;

import java.util.Collections;
import java.util.List;

import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.context.ResponseWriter;

import oracle.adf.view.rich.render.ClientComponent;
import oracle.adf.view.rich.render.ClientEvent;
import oracle.adf.view.rich.render.ClientMetadata;
import oracle.adf.view.rich.render.RichRenderer;

import org.apache.myfaces.trinidad.bean.FacesBean;
import org.apache.myfaces.trinidad.bean.PropertyKey;
import org.apache.myfaces.trinidad.context.RenderingContext;

import java.io.IOException;

import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;

import oracle.adf.view.rich.render.ClientComponent;
import oracle.adf.view.rich.render.RichRenderer;

import org.apache.myfaces.trinidad.bean.FacesBean;
import org.apache.myfaces.trinidad.context.RenderingContext;

public class AlertDemoRenderer extends RichRenderer {
    public AlertDemoRenderer() {
        super(AlertDemo.TYPE);
    }
    private static final String _CLIENT_COMPONENT = "TUAlertDemo";
    private static PropertyKey _DATA_KEY = null;
    private static final String _ROOT_STYLE_KEY = "TU|AlertDemo";

    protected void encodeAll(FacesContext context, RenderingContext arc,
                             UIComponent component, ClientComponent client,
                             FacesBean bean) throws IOException {
        ResponseWriter writer = context.getResponseWriter();
        {
            writer.startElement("div", component);
            renderStyleClass(context, arc, "col-md-6");
            renderId(context, component);
            {
                writer.startElement("label", component);
                renderStyleClass(context, arc, "label");
                writer.writeAttribute("for",
                                      getClientId(context, component) + "_input",
                                      null);
                writer.writeText("Input Value: ", null);
                writer.endElement("label");
            }
            {
                writer.startElement("input", component);
                renderStyleClass(context, arc, "inputStyleClass");
                writer.writeAttribute("id",
                                      getClientId(context, component) + "_input",
                                      null);
                writer.writeAttribute("name",
                                      getClientId(context, component) + "_input",
                                      null);
                writer.writeAttribute("type", "text", null);
                writer.writeAttribute("placeholder", "placeholder", null);
                writer.writeAttribute("value", "123", null);
                writer.writeAttribute("maxLength", "10", null);
                writer.endElement("input");
            }
            {
                writer.startElement("button", component);
                renderStyleClass(context, arc, "label");
                writer.writeAttribute("id",
                                      getClientId(context, component) + "_submit",
                                      null);
                writer.writeAttribute("onClick",
                                      "javascript:alert($(#'"+getClientId(context, component) + "_input"+"').val());",
                                      null);
                writer.writeText("Submit", null);
                writer.endElement("button");
            }
            writer.endElement("div");
        }

    }

    protected String getClientConstructor() {
        return _CLIENT_COMPONENT;
    }

    @Override
    protected ClientComponent.Type getDefaultClientComponentType() {
        return ClientComponent.Type.CREATE_WITH_REQUIRED_ATTRS;
    }

    @Override
    protected String getDefaultStyleClass(FacesContext context,
                                          RenderingContext arc,
                                          FacesBean bean) {
        return this._ROOT_STYLE_KEY;
    }

    @Override
    protected void findTypeConstants(FacesBean.Type type,
                                     ClientMetadata metadata) {
        super.findTypeConstants(type, metadata);

    }


}


DemoResourceLoader.java

package com.techutils.adf.jsf.faces.resource;

import java.io.IOException;

import java.net.URL;

import org.apache.myfaces.trinidad.resource.ClassLoaderResourceLoader;
import org.apache.myfaces.trinidad.resource.RegexResourceLoader;

public class DemoResourceLoader extends RegexResourceLoader {
    public DemoResourceLoader() {
        super();
        register("(/.*\\.(jpg|gif|png|jpeg))",
                 new ClassLoaderResourceLoader("META-INF"));
    }

    @Override
    protected URL findResource(String string) throws IOException {
        return super.findResource(string);
    }
}


DemoSimpleDesktopBundle.java

package com.techutils.adf.jsf.faces.resource;

import java.util.ListResourceBundle;

public class DemoSimpleDesktopBundle extends ListResourceBundle {
    public DemoSimpleDesktopBundle() {
        super();
    }

    protected Object[][] getContents() {
        return new Object[0][0];
    }
}



AlertDemoTag.java

package com.techutils.adf.jsf.faces.tag;

import com.techutils.adf.jsf.faces.component.AlertDemo;

import javax.el.ValueExpression;

import org.apache.myfaces.trinidad.bean.FacesBean;
import org.apache.myfaces.trinidad.webapp.UIXComponentELTag;

public class AlertDemoTag extends UIXComponentELTag {
    public AlertDemoTag() {
        super();
    }
    private ValueExpression _partialTriggers = null;
    private ValueExpression _visible = null;

    static public final String COMPONENT_TYPE =
        "com.techutils.adf.jsf.AlertDemo";
    static public final String RENDERER_TYPE =
        "com.techutils.adf.jsf.AlertDemo";


    public String getComponentType() {
        return COMPONENT_TYPE;
    }

    public String getRendererType() {
        return RENDERER_TYPE;
    }

    public void setPartialTriggers(ValueExpression _partialTriggers) {
        this._partialTriggers = _partialTriggers;
    }

    public ValueExpression getPartialTriggers() {
        return _partialTriggers;
    }

    public void setVisible(ValueExpression _visible) {
        this._visible = _visible;
    }

    public ValueExpression getVisible() {
        return _visible;
    }


    @Override
    protected void setProperties(FacesBean facesBean) {
        super.setProperties(facesBean);
        setStringArrayProperty(facesBean, AlertDemo.PARTIAL_TRIGGERS_KEY,
                               _partialTriggers);
        setProperty(facesBean, AlertDemo.VISIBLE_KEY, _visible);
    }
}

AlertDemo.js

AdfUIComponents.createComponentClass(
 "AlertDemo",
 {
      componentType:"com.techutils.adf.jsf.AlertDemo",superclass:AdfUIObject 
 }
);

AlertDemoPeer.js

AdfRichUIPeer.createPeerClass(AdfRichUIPeer, "AlertDemoPeer", true);//Create Subclass of AdfRichUIPeer
AlertDemoPeer.InitSubclass = function () {
    AdfRichUIPeer.addComponentEventHandlers(this, AdfUIInputEvent.CLICK_EVENT_TYPE);//Subscribe Click Events to Peer
}
//Register Peer to main Object
AdfPage.PAGE.getLookAndFeel().registerPeerConstructor("com.techutils.adf.jsf.AlertDemo", "AlertDemoPeer");

demo.resources

\\BasicComponents\components\src\META-INF\servlets\resources\
com.techutils.adf.jsf.faces.resource.DemoResourceLoader

techutils.tld

<?xml version = '1.0' encoding = 'windows-1252'?>
<taglib xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-jsptaglibrary_2_1.xsd"
 version="2.1" xmlns="http://java.sun.com/xml/ns/javaee">
 <display-name>techutils</display-name>
 <tlib-version>1.0</tlib-version>
 <short-name>techutils</short-name>
 <uri>/techutils/demo</uri>
 <tag>
 <name>AlertDemo</name>
 <tag-class>com.techutils.adf.jsf.faces.tag.AlertDemoTag</tag-class>
 <body-content>JSP</body-content>
 <attribute>
 <name>id</name>
 <rtexprvalue>true</rtexprvalue>
 </attribute>
 <attribute>
 <name>rendered</name>
 <deferred-value>
 <type>boolean</type>
 </deferred-value>
 </attribute>
 <attribute>
 <name>visible</name>
 <deferred-value>
 <type>boolean</type>
 </deferred-value>
 </attribute>
 <attribute>
 <name>partialTriggers</name>
 <deferred-value></deferred-value>
 </attribute>
 <attribute>
 <name>binding</name>
 <deferred-value/>
 </attribute>
 </tag>
</taglib>

adf-js-features.xml

 <?xml version="1.0" encoding="UTF-8" ?>
<features xmlns="http://xmlns.oracle.com/adf/faces/feature">
 <feature>
 <feature-name>AlertDemo</feature-name>
 <feature-class>
 com/techutils/adf/jsf/js/component/AlertDemo.js
 </feature-class>
 <feature-class>
 com/techutils/adf/jsf/js/event/AlertDemoEvent.js
 </feature-class>
 <feature-class>
 com/techutils/adf/jsf/js/component/AlertDemoPeer.js
 </feature-class>
 </feature>
</features>

demo.taglib.xml

 <?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE facelet-taglib
 PUBLIC "-//Sun Microsystems, Inc.//DTD Facelet Taglib 1.0//EN" "http://java.sun.com/dtd/facelet-taglib_1_0.dtd">
<facelet-taglib xmlns="http://java.sun.com/JSF/Facelet">
 <namespace>http://xmlns.techutils.components/demo</namespace>
 <tag>
 <tag-name>alertDemo</tag-name>
 <handler-class>oracle.adfinternal.view.faces.facelets.rich.RichComponentHandler</handler-class>
 </tag>
</facelet-taglib>

faces-config.xml

<?xml version="1.0" encoding="windows-1252"?>
<faces-config version="1.2" xmlns="http://java.sun.com/xml/ns/javaee">
<application></application>
<component>
<component-type>com.techutils.adf.jsf.AlertDemo</component-type>
<component-class>com.techutils.adf.jsf.faces.component.AlertDemo</component-class>
</component>
<render-kit>
<render-kit-id>oracle.adf.rich</render-kit-id>
<renderer>
<component-family>org.apache.myfaces.trinidad.Object</component-family>
<renderer-type>com.techutils.adf.jsf.AlertDemo</renderer-type>
<renderer-class>com.techutils.adf.jsf.faces.renderer.AlertDemoRenderer</renderer-class>
</renderer>
</render-kit>
</faces-config>

 

trinidad-config.xml

<?xml version="1.0" encoding="windows-1252"?>
<trinidad-config xmlns="http://myfaces.apache.org/trinidad/config">
<skin-family>oneportal-customskin</skin-family>
<animation-enabled>false</animation-enabled>
<debug-output>false</debug-output>
</trinidad-config>

 

trinidad-skins.xml

<?xml version="1.0" encoding="UTF-8" ?>
<skins xmlns="http://myfaces.apache.org/trinidad/skin">
<skin-addition>
<skin-id>simple.desktop</skin-id>
<style-sheet-name>demo_skins/styles/demo-simple-desktop.css</style-sheet-name>
<bundle-name>com.techutils.adf.jsf.faces.resource.DemoSimpleDesktopBundle</bundle-name>
</skin-addition>
</skins>

Final Output:

final

Posted in Oracle, Oracle ADF | Tagged , , , , , , , | Leave a comment

How to add inbuilt task flows in WebCenter Portal

In this tutorial, I will add an internal task flow to Web Center Portal. For demo, i will use the login task flow of the Web Center Portal.

Posted in Oracle, WebCenter Portal | Tagged , , , , , , | Leave a comment

Retrieve GET parameters from URL in Managed Bean in Oracle ADF

For obtaining parameter from URL in java code in Oracle ADF use the below code
URL:
http://127.0.0.1:7101/Application-ViewController-context-root/faces/page.jspx?paramName=Testing123
Use the code:
String test = FacesContext.
getCurrentInstance().getExternalContext().getRequestParameterMap().get("paramName");

Posted in Oracle, Oracle ADF | Tagged , , , , , | Leave a comment

How to create new Portal in WebCenter Portal

In this tutorial, we will create a small portal application in the Oracle WebCenter Portal.

Posted in Oracle, WebCenter Portal | Tagged , , , , | Leave a comment

How to start up Oracle WebCenter Portal

In this small tutorial we just start up the Web Center Portal and Navigate around.

Prerequisite: Installation should be complete

Steps:

  1. Navigate to Oracle Middleware Home(in my case C:/Oracle/mw10.3.6)
  2. Navigate to the Application Domain(C:\Oracle\mw10.3.6\user_projects\domains\portal_domain)
  3. Execute startWeblogic.cmd(or .sh in case of linux)
  4. Once the Server comes to running state, navigate to bin folder in the same folder and execute the following command

    startManagedWeblogic.cmd WC_Spaces http://localhost:7001

  5. The script would ask you about the username and password of the weblogic user.
  6. Once in running state, open browser and enter the following URL:

    http://localhost:8888/webcenter

Result:

Posted in Oracle, WebCenter Portal | Tagged , , , | Leave a comment

Finding loop in a singly linked-list

You can detect it by simply running two pointers through the list.
Start the first pointer p1 on the first node and the second pointer p2 on the second node.

Advance the first pointer by one every time through the loop, advance the second pointer by two. If there is a loop, they will eventually point to the same node. If there’s no loop, you’ll eventually hit the end with the advance-by-two pointer.

Consider the following loop:

head -> 1 -> 2 -> 3 -> 4 -> 5 -> 6 -> 7 -> 8
                  ^                        |
                  |                        |
                  +------------------------+

Starting A at 1 and B at 2, they take on the following values:

p1   p2
=    =
1    2
2    4
3    6
4    8
5    4
6    6

Because they’re equal, and P2¬†should always be beyond p1¬†in a non-looping list (because it’s advancing by two as opposed to the advance-by-one behavior of p1), it means you’ve discovered a loop.

The pseudo-code will go something like this:

  • Start with hn(Head Node )of the linked list
  • If hn==null; return false; //empty list
  • if hn.next!=null
    • p1=hn; p2=hn;
    • While p2!=null loop
      • p1=p1.next//Advancing p1 by¬†1
      • if p2.next!=null
        • p2=p2.next.next//Advancing p2¬†by 2
        • else return false
      • if p1==p2
        • return true// Loop was found
    • return false// till now no loop was found

Once you know a node within the loop, there’s an O(n) guaranteed method to find the start of the loop.

Let’s return to the original position after you’ve found an element somewhere in the loop but you’re not sure where the start of the loop is.

                                 p1,p2 (this is where p1 and p2
                                 |               first met).
                                 v
head -> 1 -> 2 -> 3 -> 4 -> 5 -> 6 -> 7 -> 8
                  ^                        |
                  |                        |
                  +------------------------+

This is the process to follow:

  • First, advance p2¬†and set the loopsize to 1.
  • Second, while p1¬†and p2¬†are not equal, continue to advance p2, increasing the loopsize each time. That gives the size of the loop, six in this case.
    If the loopsize ends up as 1, you know that you must already be at the start of the loop, so simply return A as the start, and skip the rest of the steps below.
  • Third, simply set both p1¬†and p2¬†to the first element then advance p2¬†exactly loopsize times (to the 7 in this case). This gives two pointers that are different by the size of the loop.
  • Lastly, while p1¬†and p2¬†are not equal, you advance them together. Since they remain exactly loopsize elements apart from each other at all times, p1¬†will enter the loop at exactly the same time as p2¬†returns to the start of the loop. You can see that with the following walk through:
    • loopsize is evaluated as 6
    • set both p1¬†and p2¬†to 1
    • advance p2¬†by loopsize elements to 7
    • 1 and 7 aren’t equal so advance both
    • 2 and 8 aren’t equal so advance both
    • 3 and 3 are equal so that is your loop start

Now, since each those operations are O(n) and performed sequentially, the whole thing is O(n).

Source

Algorithm Name:¬†Floyd‚ÄďWarshall algorithm

Posted in Algorithms, Interview Puzzles | Tagged , , , | Leave a comment

File Sorting based on parameters

Many times our file directories are full of files that we may like to be sorted in some particular manner. Below is the code to sort the files as per the following ways:

  • Month Sorting
  • Alphabetic Sorting
  • Music Album Sorting
  • Extension Sorting
import java.io.File;

import java.text.ParseException;
import java.text.SimpleDateFormat;

import java.util.Date;
import java.util.Scanner;
import java.util.TreeSet;

import org.blinkenlights.jid3.ID3Tag;
import org.blinkenlights.jid3.MP3File;
import org.blinkenlights.jid3.MediaFile;
import org.blinkenlights.jid3.v2.ID3V2_3_0Tag;

public class FileSorter {
    private Date getLastModified(File file) {
        return new Date(file.lastModified());
    }

    private String convert(Date file) throws ParseException {
        return new SimpleDateFormat("yyyy-MM").format(file.getTime());
    }

    public static void main(String[] args) {
        FileSorter p = new FileSorter();
        Scanner in = new Scanner(System.in);
        System.out.println("Please enter the folder path that you want sorted: ");
        String filePath = in.nextLine();
        System.out.println("Please enter what kind of sorting you want??");
        System.out.println("   1. Month Sorting");
        System.out.println("   2. Alphabetic Sorting");
        System.out.println("   3. Music Album Sorting");
        System.out.println("   5. Extension Sorting");
        try {
            int s = Integer.parseInt(in.nextLine());
            switch (s) {
            case 1:
                p.startSort(filePath);
                break;
            case 2:
                p.alphaSort(filePath);
                break;
            case 3:
                p.startMusicSort(filePath);
                break;
            case 5:
                p.extnSort(filePath);
                break;
            default:
                System.out.println("Invalid Option");
                break;
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public String getRange(String path) {
        String ret_String = "";
        for (int i = 97; i <= 122; i++) { if ((int) path.toLowerCase().charAt(0) >= i && (int) path.toLowerCase().charAt(0) <= (i + 3)) { ret_String = ((char) i + "-" + ((char) (i + 3))); break; } else if ((int) path.toLowerCase().charAt(0) >= 32 && (int) path.toLowerCase().charAt(0) <= 64) {
                ret_String = ("#0-9");
                break;
            } else {
                i += 3;
            }
        }
        return ret_String;
    }

    public void startSort(String filePath) throws Exception, ParseException {

        File dir = new File(filePath);
        File folder = null;
        String newFilePath = null;
        TreeSet ts = new TreeSet();

        if (dir.isDirectory()) {

            for (File file : dir.listFiles()) {
                newFilePath = convert(getLastModified(file));
                ts.add(newFilePath);
            }

            for (String o : ts) {
                folder = new File(filePath + "\\" + o);
                folder.mkdirs();

                for (File file : dir.listFiles()) {
                    newFilePath = convert(getLastModified(file));
                    if (newFilePath.equals(o)) {
                        if (file.isFile()) {
                            file.renameTo(new File(filePath + "\\" + o + "\\" + file.getName()));
                        }
                    }
                }
            }
        }
    }

    public void alphaSort(String filePath) throws Exception, ParseException {

        File dir = new File(filePath);
        File folder = null;
        String newFilePath = null;
        TreeSet ts = new TreeSet();

        if (dir.isDirectory()) {

            for (File file : dir.listFiles()) {
                newFilePath = getRange(file.getName());
                ts.add(newFilePath);
            }

            for (String o : ts) {
                folder = new File(filePath + "\\" + o);
                folder.mkdirs();

                for (File file : dir.listFiles()) {
                    newFilePath = getRange(file.getName());
                    if (newFilePath.equals(o)) {
                        if (file.isFile()) {
                            file.renameTo(new File(filePath + "\\" + o + "\\" + file.getName()));
                        }
                    }
                }
            }
        }
    }

    public void extnSort(String filePath) throws Exception, ParseException {

        File dir = new File(filePath);
        File folder = null;
        String newFilePath = null;
        TreeSet ts = new TreeSet();

        if (dir.isDirectory()) {

            for (File file : dir.listFiles()) {
                if (file.getName().lastIndexOf(".") > 0) {
                    newFilePath =
                        (file.getName().substring(file.getName().lastIndexOf(".") + 1,
                                                  file.getName().length())).toLowerCase();
                } else {
                    continue;
                }
                ts.add(newFilePath);
            }

            for (String o : ts) {
                folder = new File(filePath + "\\" + o);
                folder.mkdirs();

                for (File file : dir.listFiles()) {
                    if (file.getName().lastIndexOf(".") > 0) {
                        newFilePath =
                            (file.getName().substring(file.getName().lastIndexOf(".") + 1,
                                                      file.getName().length())).toLowerCase();
                    } else {
                        continue;
                    }

                    if (newFilePath.equals(o)) {
                        if (file.isFile()) {
                            file.renameTo(new File(filePath + "\\" + o + "\\" + file.getName()));
                        }
                    }
                }
            }
        }
    }

    public void startMusicSort(String filePath) throws Exception, ParseException {

        File dir = new File(filePath);
        File folder = null;
        String newFilePath = null;
        TreeSet ts = new TreeSet();

        if (dir.isDirectory()) {

            for (File file : dir.listFiles()) {
                newFilePath = (getAlbumName(file));
                ts.add(newFilePath);
            }

            for (String o : ts) {
                folder = new File(filePath + "\\" + o);
                folder.mkdirs();

                for (File file : dir.listFiles()) {
                    newFilePath = (getAlbumName(file));
                    if (newFilePath.equals(o)) {
                        if (file.isFile()) {
                            file.renameTo(new File(filePath + "\\" + o + "\\" + file.getName()));
                        }
                    }
                }
            }
        }
    }

    private String getAlbumName(File oSourceFile) {
        MediaFile oMediaFile = new MP3File(oSourceFile);
        ID3Tag[] aoID3Tag;
        try {
            aoID3Tag = oMediaFile.getTags();
            for (int i = 0; i < aoID3Tag.length; i++) {
                if (aoID3Tag[i] instanceof ID3V2_3_0Tag) {
                    ID3V2_3_0Tag oID3V2_3_0Tag = (ID3V2_3_0Tag) aoID3Tag[i];
                    try {
                        return ("".equals(oID3V2_3_0Tag.getAlbum().trim()) ? "Misc" :
                                oID3V2_3_0Tag.getAlbum().replaceAll("\"", "")); // reads TYER frame
                    } catch (Exception e) {
                        e.getStackTrace();
                    }
                }
            }
        } catch (Exception e) {
            e.getStackTrace();
        }
        return "Misc";
    }

    public String toString() {
        return super.toString();
    }
}

Libraries can be found at:

Posted in Java, Open Source | Tagged , , , , , , | Leave a comment

Code to Encrypt Folder Structure Completely

Below is the code to encrypt/decrypt complete folder structure in java

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

import javax.crypto.Cipher;
import javax.crypto.CipherInputStream;
import javax.crypto.CipherOutputStream;
import javax.crypto.spec.SecretKeySpec;

public class CryptoX {
    static String pwd = "";

    private static String compressPassword(String pass) {
        char[] tmp = new char[8];
        if (pass.length() > 8) {
            for (int i = 0; i < pass.toCharArray().length; i++) {
                tmp[i % 7] += pass.toCharArray()[i];
            }
            pass = new String(tmp);
        }
        return pass;
    }

    public void beginEncrypt(String in, String pass, String outputPath) throws Exception {
        try {
            pass = compressPassword(pass);
            processEncrypt(in, outputPath, (pass));
        } catch (IOException e) {
            e.printStackTrace();
            throw e;
        }
    }

    private String encryptName(String str) {
        String encrypted = "";
        int keyLength = pwd.length();
        for (int i = 0; i < str.length(); i++) { int c = str.charAt(i); if (Character.isUpperCase(c)) { // 26 letters of the alphabet so mod by 26 c = c + (keyLength % 26); if (c > 'Z')
                    c = c - 26;
            } else if (Character.isLowerCase(c)) {
                c = c + (keyLength % 26);
                if (c > 'z')
                    c = c - 26;
            }
            encrypted += (char) c;
        }
        return encrypted;
    }

    private void encrypt(File fileIn, File fileOut, String pass) throws Exception {
        fileIn.setReadable(true);
        fileOut.setWritable(true);
        fileOut.setReadable(true);
        FileInputStream fis = new FileInputStream(fileIn);
        FileOutputStream fos = new FileOutputStream(fileOut);
        byte k[] = pass.getBytes();
        final String algo = "DES/ECB/PKCS5Padding";
        SecretKeySpec key = new SecretKeySpec(k, algo.split("/")[0]);
        Cipher encrypt = Cipher.getInstance(algo);
        encrypt.init(Cipher.ENCRYPT_MODE, key);
        CipherOutputStream cout = new CipherOutputStream(fos, encrypt);

        byte[] buf = new byte[1024];
        int read;
        while ((read = fis.read(buf)) != -1) {
            cout.write(buf, 0, read);
            //            System.out.print(".");

        }

        fis.close();
        cout.flush();
        cout.close();
    }

    private void processEncrypt(String in, String out, String pass) throws IOException {

        File fin = new File(in);
        File fout = new File(out);
        fout.setWritable(true);
        fout.setReadable(true);
        fin.setReadable(true);

        if (fin.getName().startsWith(".")) {
            return;
        }

        if (!fout.exists() && fin.isDirectory() && !fin.getName().equals("Encrypt")) {
            fout.mkdirs();
            fout.setWritable(true);
        } else if (!fin.isDirectory()) {
            try {
                encrypt(fin, new File(out), pass);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        if (fin.isDirectory() && !fin.getName().equals("Encrypt")) {
            for (int i = 0; i < fin.list().length; i++) {
                processEncrypt(in + "/" + fin.list()[i], out + "/" + encryptName(fin.list()[i]), pass);
            }
        }
    }

    public void beginDecrypt(String in, String pass, String output) throws Exception {
        try {
            processDecrypt(in, output, compressPassword(pass));
        } catch (Exception e) {
            e.printStackTrace();
            throw e;
        }
    }

    private String decryptName(String str) {
        String decrypted = "";

        int keyLength = pwd.length();
        for (int i = 0; i < str.length(); i++) {
            int c = str.charAt(i);
            if (Character.isUpperCase(c)) {
                c = c - (keyLength % 26);
                if (c < 'A')
                    c = c + 26;
            } else if (Character.isLowerCase(c)) {
                c = c - (keyLength % 26);
                if (c < 'a')
                    c = c + 26;
            }
            decrypted += (char) c;
        }
        return decrypted;
    }

    private void processDecrypt(String in, String out, String pass) throws Exception {

        File fin = new File(in);
        File fout = new File(out);

        if (!fin.exists()) {
            return;
        }

        if (fin.getName().startsWith(".")) {
            return;
        }

        if (!fout.exists() && fin.isDirectory()) {
            fout.mkdirs();
            fout.setWritable(true);
        } else if (!fin.isDirectory()) {
            try {
                // out = out.substring(0, out.length()
                // - encryptName(".enc").length());

                decrypt(fin, new File(out), pass);

            } catch (Exception e) {
                e.printStackTrace();
                throw e;
            }
        }

        if (fin.isDirectory()) {
            for (int i = 0; i < fin.list().length; i++) {
                processDecrypt(in + "/" + fin.list()[i], out + "/" + decryptName(fin.list()[i]), pass);
            }
        }
    }

    private void decrypt(File fileIn, File fileOut, String pass) throws Exception {
        fileOut.setWritable(true);
        fileOut.setReadable(true);
        fileIn.setReadable(true);
        final String algo = "DES/ECB/PKCS5Padding";
        FileInputStream fis = new FileInputStream(fileIn);
        FileOutputStream fos = new FileOutputStream(fileOut);
        byte k[] = pass.getBytes();
        SecretKeySpec key = new SecretKeySpec(k, algo.split("/")[0]);
        Cipher decrypt = Cipher.getInstance(algo);
        decrypt.init(Cipher.DECRYPT_MODE, key);
        CipherInputStream cin = new CipherInputStream(fis, decrypt);

        byte[] buf = new byte[1024];
        int read = 0;
        while ((read = cin.read(buf)) != -1) {
            fos.write(buf, 0, read);
        }
        cin.close();
        fos.flush();
        fos.close();
    }

    public CryptoX() {
        super();
    }
}

The Code takes 3 parameters:

  • in: String: input path of the folder that u want to encrypt
  • password: String: Used to encrypt/decrypt the files
  • output: String: Folder path in which u wish to publish the encrypted/decrypted files
Posted in Java | Tagged , , , , , , , | Leave a comment