Senin, 12 Oktober 2015

Compressi ShannonFano Source Code Using Java







package lp2maray.com;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.BitSet;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Vector;

public class ShannonFano{
   
   
public static void main(String[] args){
InputStream is, isDecompress;
OutputStream os, osDecompress;
String filename = "file3MB.txt";
               
Path currentRelativePath = Paths.get("");
String s = currentRelativePath.toAbsolutePath().toString();
System.out.println("Current relative path is: " + s);

    String fileCom = s+"/doc/file3MB.txt";
    String fileDec = s+"/doc/dec.zsf";
    //file3MB.txt.zsf
   new ShannonFanoCompress(fileCom,null,true); //compress

}

    public ShannonFanoCompress(String filename,String destination,boolean verbose){           

                if(verbose)
                 System.out.println("compression started, source : "+filename);
            
                 HashMap<String,Integer> occurenceTable=new HashMap<String,Integer>();
                 int total=0;
             try{
                 if(verbose)
                 System.out.println("counting occurences...");
                 BufferedReader in=new BufferedReader(new FileReader(filename));                   
                 String s=null,c=null;
                 char tab[]=new char[1];
                 int i,lineCount=0;
                 while((s=in.readLine())!=null){
                         for(i=0;i<s.length();i++)
                          {tab[0]=s.charAt(i);
                           c=new String(tab);
                           if(occurenceTable.containsKey(c))
                               occurenceTable.put(c,new Integer(occurenceTable.get(c).intValue()+1));
                           else
                               occurenceTable.put(c,new Integer(1));
                          }
                      total+=s.length()+1;
                      //count each newline too
                      lineCount++;
                     }//while
                  in.close();
                  //put ("newline",...) in occurenceTable
                  occurenceTable.put("newline",new Integer(lineCount));
                  if(verbose){
                      System.out.println(lineCount+" line(s) in the file : "+filename);
                       System.out.println("occurence table");
                       for(Map.Entry<String,Integer> m:occurenceTable.entrySet())
                           System.out.println(m.getKey()+" "+m.getValue());
                      }
             }
             catch(IOException ioe){ioe.printStackTrace();
              return;
             }
            
             if(verbose)
                     System.out.println("computing frequency table...");
                    LinkedHashMap<String,Float> tmpfrequencyTable=new LinkedHashMap<String,Float>();  
             for(String tmp:occurenceTable.keySet())
             tmpfrequencyTable.put(tmp,new Float(((float)occurenceTable.get(tmp).intValue())/total));      
            
             Vector<Float> l=new Vector<Float>();
             l.addAll(tmpfrequencyTable.values());
             Collections.sort(l,Collections.reverseOrder());
             LinkedHashMap<String,Float> frequencyTable=new LinkedHashMap<String,Float>();
             for(Float value:l)
                 for(String key:tmpfrequencyTable.keySet())             
                     if(tmpfrequencyTable.get(key).equals(value))
                         {frequencyTable.put(key,value);
                          tmpfrequencyTable.remove(key);
                          break;
                         }
             if(verbose)
                 {System.out.println("frequency table");
                  for(Map.Entry<String,Float> m:frequencyTable.entrySet())
                      System.out.println(m.getKey()+" "+m.getValue());
                 }
             if(verbose)
                 System.out.println("computing code table...");
             LinkedHashMap<String,StringBuffer> codeTable=new LinkedHashMap<String,StringBuffer>();
             for(String tmp:frequencyTable.keySet())
                 codeTable.put(tmp,new StringBuffer(""));              
             updateTables(frequencyTable,codeTable);   
             if(verbose)
                 {System.out.println("code table");
                  for(Map.Entry<String,StringBuffer> m:codeTable.entrySet())
                      System.out.println(m.getKey()+" "+m.getValue());
                 }
            
            
            
             File f;
             if(destination==null)
                 f=new File(filename+".zsf");
             else
                 f=new File(destination);
             if(verbose)
                 System.out.println("destination file : "+f.getName());     
             try {
                 if(verbose)
                 System.out.println("computing bit set from source file by using code table (main compression step)...");
                  BufferedReader in=new BufferedReader(new FileReader(filename));
                  String s=null,c=null;
                  char tab[]=new char[1];
                  int i=0,j=0,k=0;               
                  BitSet content=new BitSet();           
                  String value=null,newlineValue=new String(codeTable.get("newline"));
                  while((s=in.readLine())!=null)
                      {for(i=0;i<s.length();i++)
                          {tab[0]=s.charAt(i);
                           c=new String(tab);
                           value=new String(codeTable.get(c));
                           for(j=0;j<value.length();j++,k++)
                               if(value.charAt(j)=='1')
                                   content.set(k,true);
                          }
                       for(j=0;j<newlineValue.length();j++,k++)
                           if(newlineValue.charAt(j)=='1')
                               content.set(k,true);                   
                      }
                  content.set(k,true);
                  in.close();            
                  if(f.createNewFile() && verbose)
                      System.out.println("file "+f.getName()+" created");
                 
                 
                  if(verbose)
                      System.out.println("writing code table...");
                  PrintWriter out=new PrintWriter(new BufferedWriter(new FileWriter(f)));
                  out.println(codeTable.size());
                  for(Map.Entry<String,StringBuffer> m:codeTable.entrySet())
                      out.println(m.getKey()+" "+m.getValue());          
                  byte[] byteContent=convertBitSetInBytes(content);
                  if(verbose)
                      System.out.println("writing size of compressed content : "+byteContent.length+" bytes");
                  out.println(byteContent.length);
                  out.close();
                  if(verbose)
                      System.out.println("writing compressed content...");
                  BufferedOutputStream out2=new BufferedOutputStream(new FileOutputStream(f,true));
                  out2.write(byteContent);               
                  out2.close();
                  if(verbose)
                      System.out.println("compression successful");
                 }
             catch(IOException ioe)
             {ioe.printStackTrace();
              return;
             }
        
    }
   
    private static void updateTables(LinkedHashMap<String,Float> frequencyTablePart,
                                     LinkedHashMap<String,StringBuffer> codeTablePart){
        float leftSum=0,rightSum=0;
        int limit=0;
        for(Float val:frequencyTablePart.values())
            rightSum+=val.floatValue();
        for(Float x:frequencyTablePart.values())
            {leftSum+=x;
             rightSum-=x;
             limit++;
             if(leftSum>=rightSum)
                 break;     
            }
        int j=0;
        for(Map.Entry<String,StringBuffer> m:codeTablePart.entrySet())
            {if(j<limit)
                 codeTablePart.put(m.getKey(),m.getValue().append("0"));
             else
                 codeTablePart.put(m.getKey(),m.getValue().append("1"));
             j++;
            }  
        LinkedHashMap<String,Float> nextFrequencyTablePart;
        LinkedHashMap<String,StringBuffer> nextCodeTablePart;
        Iterator<String> frequencyKeySetIterator;
        Iterator<Float> frequencyValuesIterator;
        Iterator<String> codeKeySetIterator;
        Iterator<StringBuffer> codeValuesIterator;
        if(limit>1)
            {frequencyKeySetIterator=frequencyTablePart.keySet().iterator();
             frequencyValuesIterator=frequencyTablePart.values().iterator();
             codeKeySetIterator=codeTablePart.keySet().iterator();
             codeValuesIterator=codeTablePart.values().iterator();
             nextFrequencyTablePart=new LinkedHashMap<String,Float>();      
             for(int i=0;i<limit;i++)
                 nextFrequencyTablePart.put(frequencyKeySetIterator.next(),frequencyValuesIterator.next());
             nextCodeTablePart=new LinkedHashMap<String,StringBuffer>();
             for(int i=0;i<limit;i++)
                 nextCodeTablePart.put(codeKeySetIterator.next(),codeValuesIterator.next());
             updateTables(nextFrequencyTablePart,nextCodeTablePart);
            }
        if(limit<codeTablePart.size()-1)
            {frequencyKeySetIterator=frequencyTablePart.keySet().iterator();
             frequencyValuesIterator=frequencyTablePart.values().iterator();
             codeKeySetIterator=codeTablePart.keySet().iterator();
             codeValuesIterator=codeTablePart.values().iterator();
             for(int i=0;i<limit;i++)
                 {frequencyKeySetIterator.next();
                  frequencyValuesIterator.next();
                  codeKeySetIterator.next();
                  codeValuesIterator.next();
                 }
             nextFrequencyTablePart=new LinkedHashMap<String,Float>();      
             while(frequencyKeySetIterator.hasNext())
                 nextFrequencyTablePart.put(frequencyKeySetIterator.next(),frequencyValuesIterator.next());           
             nextCodeTablePart=new LinkedHashMap<String,StringBuffer>();
             while(codeKeySetIterator.hasNext())
                 nextCodeTablePart.put(codeKeySetIterator.next(),codeValuesIterator.next());                
             updateTables(nextFrequencyTablePart,nextCodeTablePart);
            }
    }
   
    public static byte[] convertBitSetInBytes(BitSet bitSet){
        byte[] byteContent=new byte[(int)Math.ceil(bitSet.length()/8.0f)];     
        int i;
        for(i=0;i<byteContent.length;i++)
            byteContent[i]=(byte)0x0000;
        for(i=0;i<bitSet.size();i++)
            if(bitSet.get(i))
                byteContent[i/8]|=1<<(7-(i%8));
        return(byteContent);
    }
   
    public static BitSet convertBytesInBitSet(byte[] array){       
        BitSet bitset=new BitSet();
        int j;
        byte[] mask={(byte)0x01,(byte)0x02,(byte)0x04,(byte)0x08,(byte)0x10,(byte)0x20,(byte)0x40,(byte)0x80};
        for(int i=0;i<array.length;i++)
            for(j=0;j<8;j++)
                if((array[i] & mask[j])!=0)
                    bitset.set(i*8+(7-j),true);                            
        return(bitset);
    }
   
    public static String toBitString(BitSet bitset,int length){
        String s=new String("");
        for(int i=0;i<length;i++)
            if(bitset.get(i))
                s+="1";
            else
                s+="0";
        return(s);
    }         
   
  
}
HasilCompressi:


Compressi LZ78 Source Code


package lz78ok;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.file.Path;
import java.nio.file.Paths;


public class LZ78OK {
    public static void main(String[] args) {
        LZ78 lz78 = new LZ78();

        InputStream is, isDecompress;
        OutputStream os, osDecompress;
        String filename = "file3MB.txt";
               
Path currentRelativePath = Paths.get("");
String s = currentRelativePath.toAbsolutePath().toString();
System.out.println("Current relative path is: " + s);

        String filePath = s+"/doc/"+filename;
        try {
            is = new FileInputStream(filePath);
            os = new FileOutputStream(new String(filePath + ".lz78"));
            lz78.compress(is, os);

            isDecompress = new FileInputStream(new String(filePath + ".lz78"));
            osDecompress = new FileOutputStream(new String(filePath + ".lz78.decompressed.txt"));
            lz78.decompress(isDecompress, osDecompress);

            System.out.println("Done");
            System.out.println(new String(filePath));
        } catch (Exception e) {
        }
    }
}
======================
package lz78ok;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

public class LZ78 implements Compression {
    boolean stopped = false;

    public class Code {
        Code(int code, int ch) {
            this.ch = ch;
            this.code = code;
        }

        int ch;
        int code;
    };

    Dictionary dict;

    byte[] buf;

    public final ByteArray emptyBA = new ByteArray();
    ByteArray w = emptyBA;

    public LZ78() {
        int numOfBits = 12;
        buf = new byte[numOfBits];
        dict = new LimitedSizeDictionary(1 << numOfBits);
        dict.add(emptyBA);
    }

    public int encodeOneChar(int n) {
        byte c = (byte) n;
        ByteArray nw = w.conc(c);
        int code = dict.numFromStr(nw);

        if (code != -1) {
            w = nw;
            return -1;
        } else {
            dict.add(nw);
            nw = w;
            w = emptyBA;
            return dict.numFromStr(nw);
        }
    }

    public Code encodeLast() {
        if (w.size() == 0)
            return null;
        byte bt = w.getLast();
        w = w.dropLast();
        return new Code(dict.numFromStr(w), (int) bt);
    }

    public final void writeCode(OutputStream os, Code c) throws IOException {
        writeCode(os, c.ch, 8);
        writeCode(os, c.code, 12);
    }

    public final void writeCode(OutputStream os, int num, int bits) throws IOException {
        for (int i = 0; i < bits; ++i) {
            os.write(num & 1);
            num = num / 2;
        }
    }

    public final Code readCode(InputStream is) throws IOException {
        int ch = readInt(is, 8);
        if (ch < 0)
            return null;
        int cd = readInt(is, 12);
        if (cd < 0)
            return null;
        return new Code(cd, ch);
    }

    public final int readInt(InputStream is, int bits) throws IOException {
        int num = 0;
        for (int i = 0; i < bits; ++i) {
            int next = is.read();
            if (next < 0)
                return -1;
            num += next << i;
        }
        return num;
    }

    public void compress(InputStream is, OutputStream os) throws IOException {
        os = new BitOutputStream(os);
        int next;
        int code;
        while ((next = is.read()) >= 0) {
            if (stopped) {
                break;
            }
            code = encodeOneChar(next);
            if (code >= 0) {
                writeCode(os, new Code(code, next));
            }
        }
        Code c = encodeLast();
        if (c != null) {
            writeCode(os, c);
        }
        os.flush();
    }

    public ByteArray decodeOne(Code c) {
        ByteArray str = dict.strFromNum(c.code);
        dict.add(str.conc((byte) c.ch));
        return str;
    }

    @SuppressWarnings("unused")
    public void decompress(InputStream is, OutputStream os) throws IOException {
        is = new BitInputStream(is);
        ByteArray str;
        Code c;
        while ((c = readCode(is)) != null) {
            if (stopped) {
                break;
            }
            if (c == null) {
                break;
            }
            str = decodeOne(c);
            os.write(str.getBytes());
            os.write(c.ch);
        }
    }

    public void stop() {
        stopped = true;
    }
}
=================
package lz78ok;

public class ByteArray {

    final byte[] arr;

    ByteArray(byte[] b) {
        arr = (byte[]) b.clone();
    }

    ByteArray() {
        arr = new byte[0];
    }

    ByteArray(byte b) {
        arr = new byte[] { b };
    }

    public boolean equals(Object o) {
        ByteArray ba = (ByteArray) o;
        return java.util.Arrays.equals(arr, ba.arr);
    }

    public int hashCode() {
        int code = 0;
        for (int i = 0; i < arr.length; ++i)
            code = code * 2 + arr[i];
        return code;
    }

    public int size() {
        return arr.length;
    }

    byte getAt(int i) {
        return arr[i];
    }

    public ByteArray conc(ByteArray b2) {
        int sz = size() + b2.size();
        byte[] b = new byte[sz];
        for (int i = 0; i < size(); ++i)
            b[i] = getAt(i);
        for (int i = 0; i < b2.size(); ++i)
            b[i + size()] = b2.getAt(i);
        return new ByteArray(b);
    }

    public ByteArray conc(byte b2) {
        return conc(new ByteArray(b2));
    }

    public byte[] getBytes() {
        return (byte[]) arr.clone();
    }

    public boolean isEmpty() {
        return size() == 0;
    }

    public byte getLast() {
        return arr[size() - 1];
    }

    public ByteArray dropLast() {
        byte[] newarr = new byte[size() - 1];
        for (int i = 0; i < newarr.length; ++i)
            newarr[i] = arr[i];
        return new ByteArray(newarr);
    }

    public String toString() {
        return new String(arr);
    }
}
=======================
package lz78ok;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

public interface Compression {
    public void compress(InputStream inp, OutputStream out) throws IOException;
    public void decompress(InputStream inp, OutputStream out) throws IOException;
}
=======================
package lz78ok;

import java.io.FilterInputStream;
import java.io.IOException;
import java.io.InputStream;

public class BitInputStream extends FilterInputStream {

    /**
     * Constructor creates a new instance of BitInputStream, A decarotor to
     * InputStream, via FilterInputStream
     */
    public BitInputStream(InputStream is) {
        super(is);
    }

    class BitManager {
        // Buffer to keep max of 7 bits (one byte)
        private int[] buf = new int[8];
        // Counter showing the bit number we are reading now
        private int cnt = -1;

        // If we are at the end of the stream
        boolean atTheEnd() {
            return ((buf[7] == 1) && (cnt < 0));
        }

        // Set the flag for the end of stream
        void setTheEnd() {
            buf[7] = 1;
            cnt = -1;
        }

        // No more buffer, means we need to read the next byte
        boolean noMoreBuffer() {
            return cnt < 0;
        }

        // set the buffer
        void setNext(int next) { // put the bits of the byte into the array
            for (cnt = 0; cnt < 8; ++cnt) {
                buf[cnt] = next % 2;
                next /= 2;
            }
            // if this was the last byte
            if (buf[7] == 1) {
                for (cnt = 7; cnt >= 0; cnt--)
                    if (buf[cnt] == 0)
                        break;
                cnt--;
            } else {
                cnt = 6;
            }
        }

        // get the next bit
        int getNext() {
            return buf[cnt--];
        }

        // how many left
        int left() {
            return cnt + 1;
        }

    };

    BitManager bitManager = new BitManager();

    byte[] tempBuf = null;
    int tempBufPtr = 0;
    int tempBufLen = 0;

    private int readNextByte() throws IOException {
        int val = -1;
        if (tempBufPtr == tempBufLen)
            val = super.read();
        else {
            byte b = tempBuf[tempBufPtr++];
            if ((b & 0x80) > 0)
                val = ((int) (b & 0x7F)) | 0x80;
            else
                val = b;
        }
        return val;
    }

    /**
     * Reads a single bit from the included stream. Returns either 1 or 0, and
     * at the end of stream returns -1.
     */
    public int read() throws IOException {
        // If we are already at the end, return -1
        if (bitManager.atTheEnd())
            return -1;
        // If we are in the last bit, then refill the buffer
        if (bitManager.noMoreBuffer()) {
            int i = readNextByte();
            if (i < 0)
                bitManager.setTheEnd();
            else
                bitManager.setNext(i);
            return read();
        }
        // Return the specific bit
        return bitManager.getNext();
    }

    /** Reads a list of bits given in the byte array as 0's and 1's */
    public int read(byte[] arr) throws IOException {
        return read(arr, 0, arr.length);
    }

    public int read(byte[] arr, int off, int len) throws IOException {
        int bytelen = ((len - bitManager.left()) / 7);
        tempBuf = new byte[bytelen];
        tempBufLen = in.read(tempBuf);
        tempBufPtr = 0;
        for (int i = 0; i < len; ++i) {
            int next = read();
            if (next < 0)
                return i;
            arr[off + i] = (byte) next;
        }
        return len;
    }
}
============================
package lz78ok;

import java.io.FilterOutputStream;
import java.io.IOException;
import java.io.OutputStream;

public class BitOutputStream extends FilterOutputStream {
    class BitManager {
        int buf = 0;
        int cnt = 0;

        int writeOne(int next) {
            int ret = -1;
            buf = buf * 2 + next;
            cnt++;
            if (cnt == 7) {
                cnt = 0;
                ret = buf;
                buf = 0;
            } else {
                ret = -1;
            }
            return ret;
        }

        //
        int writeLast() {
            int x = 0;
            for (int i = 0; i < 7 - cnt; ++i)
                x = x * 2 + 1;
            for (int i = 7 - cnt; i < 8; ++i)
                x = x * 2;
            return buf | x;
        }
    }

    BitManager bitManager = new BitManager();

    public BitOutputStream(OutputStream os) {
        super(os);
    }

    public void write(int i) throws IOException {
        int x = bitManager.writeOne(i >= 1 ? 1 : 0);
        if (x >= 0)
            out.write(x);
    }

    public void write(byte[] arr) throws IOException {
        write(arr, 0, arr.length);
    }

    public void write(byte[] arr, int off, int len) throws IOException {
        int clen = 0;
        for (int i = 0; i < len; ++i) {
            int x = bitManager.writeOne(arr[off + i]);
            if (x >= 0)
                arr[off + (clen++)] = (byte) x;
        }
        out.write(arr, off, clen);
    }

    public void flush() throws IOException {
        out.write(bitManager.writeLast());
        super.flush();
    }
}
==================================

Ayo Belajar Netbeans / Java /Eclipse IDE


Image result for java



Harga Kursus : Rp. 400.000,00 (Paket u Mhs)
Kategori : App Desktop
Durasi : Lama Belajar 15 jam
  
SILABUSMateri diajarkan al:
Hari1
Mengenal IDE (Form Design, Object Inspector,Unit,Tool Palette),
Pengenalan Tipe Data,Komponent Standard dan Latihan Pemrograman
Membuat Kalkulator via Button, Radio,CheckBox,ListBox

Hari2
Mengenal Struktur Menu, Manipulasi String (String dan regular expression),
Mendesain GUI Interface,
Tipe Data, Operator, iterator + Latihan program
Membuat Aplikasi kalkulator Toko Klontong

Hari3
Teknik Pemrograman,
Implementasi Pernyataan Kondisional.(If-Then-Else,Case of),
Implementasi Konsep Perulangan (Repeat ..Until,While ..Do)
Pembuatan Fungsi dan Procedure
Implementasi Data Array, Latihan Program.

Hari4
Mengakses Database,
Koneksi,CRUD(Create Read Update Delete)
Latihan Aplikasi ( Pendaftaran Siswa Baru)

Hari5
Database Lanjutan,
koneksi 2 tabel,Query,
Bonus Mempaketkan pustaka dalam pemrograman
Latihan Program & Evaluasi.

===============================================
Info lebih silakan Kami di

+ http://www.lp2maray.com

+ http://aplikasi-skripsi.com/



cp:Adi

+085279959498
+021-78889003
+021-92771708

Minggu, 26 April 2015

PHP INCLUDE Cryptograph

<?php

    $salt ='whatever_you_want';

    function simple_encrypt($text)
    {
        return trim(base64_encode(mcrypt_encrypt
(MCRYPT_RIJNDAEL_256, $salt, $text, MCRYPT_MODE_ECB, 
mcrypt_create_iv(mcrypt_get_iv_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_ECB), 
MCRYPT_RAND))));
    }

    function simple_decrypt($text)
    {
        return trim(mcrypt_decrypt(MCRYPT_RIJNDAEL_256, $salt, 
base64_decode($text), MCRYPT_MODE_ECB, 
mcrypt_create_iv(mcrypt_get_iv_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_ECB), 
MCRYPT_RAND)));
    }

?>
 
I'm using XAMPP 1.7.4 with PHP 5.3.5 as well, no problem here. It's 
configured "--with-mcrypt=static", Version 2.5.8 is enabled by default. 
No need to enable the extension (which I had to do for Fileinfo, though;
 just uncomment extension=php_fileinfo.dll in xampp/php/php.ini) 
 
 
Nice to try.... 

Krtiptografi Plugin Pada PHP


 Enkripsi adalah proses mengamankan suatu informasi dengan membuat 
informasi 
tersebut tidak dapat dibaca tanpa bantuan pengetahuan khusus
Plaintext adalah teks informasi yang merupakan masukan bagi suatu 
algoritma enkripsi
Ciphertext adalah teks tersandi atau teks sandi dari hasil 
enkripsiMcrypt 
merupakan suatu paket dari kumpulan program enkripsi data
Mcrypt mendukung berbagai macam algoritma enkripsi dan mode 
operasi yang 
dapat diimplementasikan untuk membuat suatu program enkripsi dan 
dekripsi data 
sesuai dengan kebutuhan kita.

Requirement Mcrypt
Beberapa persyaratan yang harus ada agar dapat menggunakan 
Mcrypt yaitu :
1. Webserver yang sudah terinstalasi dengan PHP 4.x atau PHP 5.x
2. Modul Mcrypt, baik yang sudah dikompile dalam PHP atau sebagai 
modul yang 
terpisah (dalam hal ini memerlukan libmcrypt)

Apa itu Libmcrypt?

Libmcrypt merupakan suatu library dalam PHP yang 
mengimplementasikan dan 
menyediakan mekanisme standar untuk mengakses semua algoritma 
dan mode 
operasi yang terdapat dalam mcrypt. Tidak seperti library 
enkripsi lainnya, 
library mcrypt hanya menyediakan fungsi bagaimana untuk 
mengakses/menggunakan 
algoritma enkripsi (encryption algorithm) dan mode operasi yang 
terdapat dalam 
mcrypt.

Tetapi didalam PHP sendiri selain mcrypt, terdapat tambahan fungsi 
kriptografi 
lainnya seperti cracklib (untuk menguji kekuatan suatu password), 
mhash (untuk 
menghasilkan/mengimlementasikan Cryptographic Checksums, 
Message Digest, Message 
Authentication Code/MAC) dan OpenSSL sehingga dalam pembuatan 
suatu program 
enkripsi/dekripsi kita dapat menggunakan semua fungsi tambahan 
tersebut sesuai 
dengan kebutuhan.

Sebagai penegasan, Library mcrypt menunjang penggunaan algoritma yang 
memang lazimnya digunakan untuk enkrpsi dan dekripsi data. Hal itu 
dikarenakan algoritma yang terdapat dalam mcrypt merupakan algoritma 
dua arah (two way algorithm) atau yang memiliki invers sehingga dapat 
dilakukan proses dekripsi.

Sedangkan mhash sesuai dengan fungsinya dalam menghasilkan 
Cryptographic 
Checksums, Message Digest, Message Authentication Code/MAC 
menunjang algoritma 
fungsi hash (hash function) yang sifatnya satu arah (one way), 
dimana tidak 
memiliki invers/tidak bisa dilakukan proses kebalikannya.

Sedangkan fungsi hash merupakan suatu fungsi untuk menghasilkan 
suatu output 
dengan panjang yang tetap (fixed lenght) dari berbagai 
macam panjang input 
yang berbeda. Oleh karena itu biasanya algoritma fungsi 
hash seperti MD5, SHA, 
RIPE-MD, HAVAL, SNEFRU, dan lain sebagainya dalam PHP digunakan 
untuk enkripsi 
data yang disimpan dalam database seperti password, nomor kartu 
kredit atau data 
yang dianggap penting lainnya/rahasia.

Dimana metodenya hanya dengan mencocokan/membandingkan nilai 
output dari hasil 
perhitungan input menggunakan algoritma fungsi hash dengan 
suatu nilai 
yang ada dalam database yang merupakan hasil perhitungan 
nilai yang sama 
dengan input menggunakan algoritma fungsi hash yang sama. 
Implementasinya 
biasanya dalam hal otentikasi.

Mengapa menggunakan Mcrypt ?
Mcrypt mendukung berbagai macam algoritma enkripsi yang sifatnya dua arah 
(two way) baik berupa algoritma block cipher maupun 
algoritma stream cipher 
dan berbagai mode operasi.

Algoritma yang didukung library mcrypt yaitu :

1. Algoritma Block Cipher
Blowfish, Cast (128 dan 256 bit), DES, Gost, IDEA, RC2, RC6, Loki97, Mars, 
Rijndael (128, 192, 256 bit), Crypt, Safer64, Safer 128, 
Saferplus, Serpent,
Twofish, TripleDes, XTEA.

2. Algoritma Stream Ciphers
Arcfour, Wake dan Enigma.

Untuk Algoritma Stream Cipher mode operasi yang digunakan yaitu 
mode stream, 
sedangkan untuk algoritma Block Cipher mode operasi yang digunakan 
diantaranya ECB, CTR, CBC, CFB, NCFB, OFB, NOFB.

Ada atau tidaknya algoritma dalam daftar algoritma di modul tergantung 
pada versi PHP yang digunakan.
Mode Operasi yang didukung library mcrypt yaitu :
1. ECB (Electronic Code Book)
2. CTR
3. CBC (Cipher Block Chaining)
4. CFB (Cipher Feedback)
5. NCFB (Non-CFB)
6. OFB (Output-Feedback)
7. NOFB (Non-OFB)
8. Stream
 
 
Reff:
http://arfianhidayat.com/enkripsi-dekripsi-mcrypt-php.html 
http://us2.php.net/manual/en/book.mcrypt.php
http://redjkibersama.blogspot.com/2011/04/
download-skripsi-komputer-lengkap-full.html


Sabtu, 27 September 2014

Algortima Chipper dalam java


import java.util.LinkedHashSet;
import java.util.Set;

public class Chiper {
  //baris alphabet acuan
  private  String  alp  =
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuv
wxyz0123456789 .,?!@()-_=+";//,./';[]!@#$%^&*()_+-=<>?\"{}`~\\ 
  //key  bawaan  aplikasi,  digunakan  di  inisialisasi  jika  key  yang digunakan bukan bawaan aplikasi
  private String key = "<oGHsoienJGDdop90?>";
  //panjang alphabet, digunakan untuk penggeseran dan modulus alphabet
  private int alen = this.alp.length();
  
  //constructor umum
  public Chiper(){
    this.adjustKeyWord();
  }
  
  public Chiper(String phone){
    if(!phone.equals(""))
      this.key = this.mixKeyword(phone);
    
    this.adjustKeyWord();
  }
  
  //constructor dengan keyword custom
  public Chiper(String phone,String keyword){
    if(!phone.equals(""))
      this.key = this.mixKeyword(phone);
    
    if(!keyword.equals(""))
      this.key = this.mixKeyword(keyword);
    
    this.adjustKeyWord();
  }
  
  //constructor dengan baris abjad custom dan keyword custom
  public Chiper(String phone,String keyword,String alphabet){
    this.alp = alphabet;
    this.alen = this.alp.length();
    
    if(!phone.equals(""))
      this.key = this.mixKeyword(phone);
    
    if(!keyword.equals(""))
      this.key = this.mixKeyword(keyword);
    
    this.adjustKeyWord();
  }
  //fungsi mixing 2 string keyword
  private String mixKeyword(String keyword) {
    String rkey = "";
    
    int lbk = this.key.length();
    int lik = keyword.length();
    
    int tnk = lbk>lik ? lbk : lik ;
    
    for(int i = 0;i<tnk;i++){
      if(i<lbk)
        rkey += this.key.charAt(i);
      if(i<lik)
        rkey += keyword.charAt(i);
    }
    
    return rkey;
    
  }
  
  private void adjustKeyWord(){
    this.key = adjustKeyWord(this.key);
  }
  
  //fungsi adjustment key memastikan 1 buah char/g ad yg sama
  private String adjustKeyWord(String keyword) {
    String kw = "";
    Set<Character>  keyChars  =  new
LinkedHashSet<Character>(keyword.length());
    for(char c : keyword.toCharArray()){
      if((alp.indexOf(c)  !=  -1)  &&
keyChars.add(c)){
        kw += String.valueOf(c);
      }
    }
    //Log.i("keyword",kw);
    
    return kw;

  }
  
  //fungsi fibonanci key
  private void getFibonanciKey(int llen,int klen,String line){
    //selisih panjang kalimat dengan panjang key
    int loss = llen - klen;
    //Log.i("loss",String.valueOf(loss));
    //rumus fibonanci
    int mt = 1;
    for (char c : this.key.toCharArray()){
      mt += this.alp.indexOf(c);
    }
    mt %= klen;
    //Log.i("loss",String.valueOf(mt));
    //END rumus fibonanci
    String temkey = this.key;
    while(temkey.length()<llen){
      temkey += this.key;
    }
    //Log.i("repeater",temkey);
    
    String holder = "";
    int tmp2;
    for(int i=0;i<loss;i++){
      
      tmp2  =  this.alp.indexOf(temkey.charAt(i))  + this.alp.indexOf(temkey.charAt(i+mt));
      tmp2 += this.alen;
      tmp2 %= this.alen;
      holder += this.alp.charAt(tmp2);
    }
    
    this.key = mixKeyword(holder);
    //Log.i("keywordFibo",this.key);
    //return this.key;
  }


Vigenere Chipper dalam Java

adalah : metode menyandikan teks alfabet
dengan menggunakan deretan sandi Caesar berdasarkan huruf-huruf pada kata kunci.

Sandi
Vigenère merupakan bentuk sederhana dari sandi substitusipolialfabetik.




Sebagai berikut coding di atas:

package lp2maray.com;

public class vc{

String enkripsi(String p,String k){
String l="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789!@#&%*()-_=:,.'?/$^ ";
    int pms=l.length();
    int pln=p.length();
    int ky=k.length();
   
        String     y =k;
        int m = pln%ky;
            for( int i=1; i<pln/ky ; i++){k=k+y;}
            k=k+k.substring(0,m);   
String c="";   
for (int j=0; j<pln; j++ ){
    char hsl=l.charAt((l.indexOf(k.charAt(j)) + l.indexOf(p.charAt(j)))%pms);
    c=c + l.charAt((l.indexOf(k.charAt(j)) + l.indexOf(p.charAt(j)))%pms);
    }
return c;
}
           
//==================================================================================
String dekripsi(String p,String k){
String l="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789!@#&%*()-_=:,.'?/$^ ";
    int pms=l.length();
    int cpr=p.length();
    int ky=k.length();
   
    String     y =k;
        int m = cpr%ky;
            for( int i=1; i<cpr/ky ; i++){k=k+y;}
            k=k+k.substring(0,m);   
String pl = "";       
for (int j=0; j<cpr; j++ ){
    char hsl=l.charAt(((l.indexOf(p.charAt(j)) - l.indexOf(k.charAt(j))) +pms )%pms);
    pl=pl + hsl;
    }   
return pl;
}
//==================================================================================   
}