Showing posts with label encryption. Show all posts
Showing posts with label encryption. Show all posts

Sunday, August 14, 2016

Best Application to learn Difference Programming Languages Fast


App Name: Programming Hub
Package Name: com.freeit.java
Category: Education
Developer : Nexino Labs Pvt Ltd
Version: 3.0.6
Publish Date: July 30, 2016
File Size: Undefined
Installs: 1,000,000 - 5,000,000
Requires Android: 4.1 and up
Content Rating: Everyone
Developer: Visit website Email contactus@prghub.com


This is the best Application for me to Learn 18+ Programming languages such as Python, Assembly, HTML, VB.NET, C, C++, C# (CSharp), JavaScript, PHP, Ruby, R Programming, CSS, Java programming and much more! The new UI is quite interesting with new Material Design include the built-in playground where you can test your code in one app :D

With this app, i think is fastest way to learn any programming language by referring ready made programs and theory created by programming experts. Just download the language you want to learn or just request to the developer on what language you want or solutions.

Have an exam tomorrow?? :D No worries! By this app, forget your 600 page textbooks! Simply read this app essential and very precise reference material to score awesome marks!

Below is the Screenshot of this lastest app





Thursday, December 31, 2015

Autokey Cipher

Autokey encryption and decryption

Plaint text = "FOLLOWDIRECTION"
Autokey = P

This Autokey is polyalphabet Substitution cipher. In this cipher, the key is a stream of subkeys which is each subkey is used to encrypt the corresponding character in the plaintext.

For example

Plaintext --> F O L L O W D I R E C T I O N
Key       --> P F O L L O W D I R E C T I O

As shown, the key is add the first of subkeys.

Lets Encrypt


              F O L L O W D I R E C T I O N
              P F O L L O W D I R E C T I O
              -----------------------------
          (+) U T Z W Z K Z L Z V G V B W B
              -----------------------------
  
 * can use vigenere table to calculate


Lets Decrypt


Put the key first

              P
              -----------------------------
              U T Z W Z K Z L Z V G V B W B
              -----------------------------
              
Do subtraction cipher - key. ex: U - P = F . Add F plaintext letter to the end of the keystream.

              F
              P F
              -----------------------------
              U T Z W Z K Z L Z V G V B W B
              -----------------------------

Do subtraction cipher - key. ex: T - F = O . Again add O plaintext letter to the end of the keystream.

              F O
              P F O
              -----------------------------
              U T Z W Z K Z L Z V G V B W B
              -----------------------------
 
              F O L
              P F O L
              -----------------------------
              U T Z W Z K Z L Z V G V B W B
              -----------------------------

              F O L L
              P F O L L
              -----------------------------
              U T Z W Z K Z L Z V G V B W B
              -----------------------------

continue subtraction until

              F O L L O W D I R E C T I O N
              P F O L L O W D I R E C T I O
              -----------------------------
              U T Z W Z K Z L Z V G V B W B
              -----------------------------



DONE!

Change Snippet Background Color

/*
   Autokey encryption and decryption
*/
import java.util.*;
import java.lang.*;
import java.math.*;

public class Autokey{
   private static String alpha = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
   
   public static void main(String[] args){
      String text = "FOLLOWDIRECTION";
      String key = "P";  //15 - P
      
      if(key.matches("[-+]?\\d*\\.?\\d+"))
         key = ""+alpha.charAt(Integer.parseInt(key));
         
      String enc = AutoEncryption(text,key);
      System.out.println("Plaintext : "+text);
      System.out.println("Encrypted : "+enc);
      System.out.println("Decrypted : "+AutoDecryption(enc,key));

   }
   
   public static String AutoEncryption(String text,String key){
      int len = text.length();
      
      String subkey = key + text;
      subkey = subkey.substring(0,subkey.length()-key.length());
      
      String sb = "";
      for(int x=0;x<len;x++){
         int get1 = alpha.indexOf(text.charAt(x));
         int get2 = alpha.indexOf(subkey.charAt(x));
         
         int total = (get1 + get2)%26;
         
         sb += alpha.charAt(total);
      }
     
      return sb;   
   }
   
   public static String AutoDecryption(String text,String key){
      int len = text.length();
      
      String current = key;
      String sb ="";
      
      for(int x=0;x<len;x++){
         int get1 = alpha.indexOf(text.charAt(x));
         int get2 = alpha.indexOf(current.charAt(x));
         
         int total = (get1 - get2)%26;
         total = (total<0)? total + 26 : total;
         sb += alpha.charAt(total);
         
         current += alpha.charAt(total);
      }
      return sb;
   }
}

Wednesday, December 30, 2015

Polyalphabet Substitution Cipher with Period

This is poly lphabet substitution with period

Example:
Plaintext : IHATEYOU
Period : 3
          ALPHABET : A B C D E F G H I J K L M N O P Q R S T U V W X Y Z
          ----------------------------------------------------------------
          PERIOD 1 : B K L Y C P X F I Z J W D A H U R N G S T V Q M O E
          PERIOD 2 : Y U N S I D V T H L C K Q B P R Z M X O J G A W E F
          PERIOD 3 : I N T Q V E W F M G J B S Y U P Z H X C A L O K R D

Those period alphabet is can be done randomly without duplicate.

Let's start
Encryption:
For the first letter of plaintext is for period 1, second letter is for period 2 and third letter for period 3, then start over fourth letter for period 1 and so on.

For example:
 
          I letter of plain text, opposite of I at period 1 is I
          H letter of plain text, opposite of H at period 2 is T
          A letter of plain text, opposite of A at period 3 is I
          .
          .
          .

          Result
          I = I
          H = T
          A = I
          T = S
          E = I
          Y = R
          O = H
          U = J

Cipher text : ITISIRHJ

Lets do decryption
Decryption:
For the encryption part, the substitution from alphabet to period.
For the decryption part, we do reverse from period to alphabet.

As we know, the first of ciphertext is from period 1 and so on. Then, by doing reverse,

          Cipher text : ITISIRHJ

          I letter of plain text, opposite of I at alphabet from period 1 is I
          T letter of plain text, opposite of T at alphabet from period 2 is H
          I letter of plain text, opposite of I at alphabet from period 3 is A
          .
          .
          .
          Result
          I = I
          T = H
          I = A
          S = T
          I = E
          R = Y
          H = O
          J = U
 

Plain text : I HATE YOU


Change Snippet Background Color
          
            
/*
   Polyalphabet Subtitution
   Create by Hafiq
*/

import java.util.*;

public class PolyAlpahbetSub{
   
   private static String alpha = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
   private static ArrayList<String> list = new ArrayList<String>(); 
   
   public static void main(String[] args){
      
      String text = "IHATEYOU";
      int period = 3;
      Period(period);
      
      System.out.println("CT:   "+alpha);
      for(int x=0;x<list.size();x++){
         System.out.println("PT"+x+":  "+list.get(x));
      }
            
      String enc = PASEncryption(text,period);
      System.out.println("\nPlaintext : "+text);
      System.out.println("Encrypted : "+enc);
      System.out.println("Decrypted : "+PASDecryption(enc,period));
   }
   
   public static void Period(int period){
      Random r = new Random();
      
      for(int x=0;x<period;x++){
         String key = "";
         for (int i = 0; i < 26;) {
             char c = (char) (r.nextInt(26) + 'A');
             if(!key.toString().contains(""+c)){
                key = key + c;
                i++;
             }
         }  
         list.add(key);    
      }
   }
   
   public static String PASEncryption(String text,int period){
      int len = text.length();
      
      String sb = "";
      
      int p = 0;
      for(int x=0;x<len;x++){
         int get = alpha.indexOf(""+text.charAt(x));
        
         if (p == period)
            p = 0;
         
         String CT = list.get(p);
         
         sb = sb + CT.charAt(get);
            
         p++;
      }
      
      return sb;
   }
   
   public static String PASDecryption(String text,int period){
      int len = text.length();
      
      String sb = "";
      
      int p = 0;
      for(int x=0;x<len;x++){
         if (p == period)
            p = 0;
         
         int get = list.get(p).indexOf(""+text.charAt(x));
         
         sb = sb + alpha.charAt(get);
            
         p++;
      }
      
      return sb;
   }

}
            
          
        

OTP with random alphabet value

This is One Time Pad Cipher with random alphabet value as shown below

A-7    B-10    C-19    D-23    E-0    F-22    G-6    H-25   I-9    J-1 
K-15   L-4     M-21    N-20    O-16   P-8     Q-17   R-5    S-24   T-3
U-11   V-12    W-14    X-2     Y-13   Z-18

Plain text = COMPUTER
KEY = SOVIET

Encryption

 FORMULA (cipher + key) % 26

        C    O    M    P    U   T   E   R
        S    O    V    I    E   T   S   O
        -----------------------------------
  (%26) 17   6    7    17   11  6   24  21
        -----------------------------------
        Q    G    A    Q    U   G   S   M


Decryption

 FORMULA = ((cipher + 26) - key) % 26
 
        Q    G    A    Q    U   G   S   M
        ------------------------------------
        17   6    7    17   11  6   24  21
  (+26) 43   32   33   43   37  32  50  47
        ------------------------------------
        S    O    V    I    E   T   S   O
        24   16   12   9    0   3   24  16
 (-KEY) 19   16   21   34   37  29  26  31
        ------------------------------------
  (%26) 19   16   21   8    11  3   0   5
        ------------------------------------
        C    O    M    P    U   T   E   R



Change Snippet Background Color
          
            
/*

*/
import java.util.*;

public class OTPCipher2{
                                //  A B  C  D  E  F G H  I J K  L M  N  O  P Q  R S  T U  V  W  X Y  Z
   private static Integer[] list = {7,10,19,23,0,22,6,25,9,1,15,4,21,20,16,8,17,5,24,3,11,12,14,2,13,18};
   private static String alpha = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
   
   public static void main(String[] args){
      String text = "REPEAT ATTACK TONIGHT";
      String key = "SOVIET";
      String k = "";
      int len = text.length();
      if(key.length()<len){
         int count = 0;
         for(int x=0;x<len;x++){  
            if(count == key.length()) 
               count = 0;
               
            k = k+key.charAt(count);
            count++;
         }
         key = k;
      }
      
      String enc = OTPEncryption(text,key);
      System.out.println("Plaintext : "+text);
      System.out.println("Encrypted : "+enc);
      System.out.println("Decrypted : "+OTPDecryption(enc,key));
   }
   
   public static String RandomAlpha(int len){
      Random r = new Random();
      String key = "";
      for(int x=0;x<len;x++)
         key = key + (char) (r.nextInt(26) + 'A');
      return key;
   }
   
   public static String OTPEncryption(String text,String key){
      int len = text.length();
      String sb= "";
      for(int x=0;x<len;x++){
         char get = text.charAt(x);
         char keyget = key.charAt(x);
         if(Character.isUpperCase(get)){
            int index = list[alpha.indexOf(get)];
            int keydex = list[alpha.indexOf(keyget)];
            
            int total = (index + keydex) % 26;
            
            sb = sb + alpha.charAt(Arrays.asList(list).indexOf(total));
         }
         else{
            sb = sb + get;
         }
      }
      
      return sb;
   }
   public static String OTPDecryption(String text,String key){
      int len = text.length();
      
      String sb = "";
      for(int x=0;x<len;x++){
         char get = text.charAt(x);
         char keyget = key.charAt(x);
         if(Character.isUpperCase(get)){
            int index = list[alpha.indexOf(get)];
            int keydex = list[alpha.indexOf(keyget)];

            int total = (index + 26) - keydex;
            total = total % 26;
            
            sb = sb + alpha.charAt(Arrays.asList(list).indexOf(total));
         }
         else{
            sb = sb + get;
         }
      }
      return sb;
   }   
}      
          
        

Tuesday, December 15, 2015

Affine Cipher

Remember: 
Formula to encrypt : ax + b % 26
Formual to decrypt : IN * (x - b) mod 26


There are 2 key:
for example : 17 , 20

Text = TWENTYFIFTEEN

A B C D E F G H I J K  L  M  N  O  P  Q  R  S  T  U  V  W  X  Y  Z
-------------------------------------------------------------------
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25

To encrypt :

T  W  E  N  T  Y  F  I  F  T  E  E  N
19 22 4  13 19 24 5  8  5  19 4  4  13

By using formula encryption ax+b % 26.
a = first key
b = second key
x = is the each letter



--------------------------------------
T  W  E  N  T  Y  F  I  F  T  E  E  N
--------------------------------------
19 22 4  13 19 24 5  8  5  19 4  4  13
5  4  10 7  5  12 1  0  1  5  10 10 7   <== ax+b % 26
--------------------------------------
F  E  K  H  F  M  B  A  B  F  K  K  H 
--------------------------------------

To decrypt :
 
F  E  K  H  F  M  B  A  B  F  K  K  H 
5  4  10 7  5  12 1  0  1  5  10 10 7

By using formula decryption.
a = first key
b = second key
x = 0 - infiniti

by using first key, find the inverse modular which firstkey * x mod 26 must equal to 1.


17 * 0 mod 26 != 1
17 * 1 mod 26 != 1
.
.
.
17 * 23 mod 26 == 1  <--- 23 is the modular inverse

by using 23,
b = second key
x = is the each letter encrypted letter

23 *(x-b) mod 26
--------------------------------------
F  E  K  H  F  M  B  A  B  F  K  K  H 
--------------------------------------
5  4  10 7  5  12 1  0  1  5  10 10 7
19 22 4  13 19 24 5  8  5  19 4  4  13 <== 23 *(x-b) mod 26
--------------------------------------
T  W  E  N  T  Y  F  I  F  T  E  E  N
--------------------------------------


Done!

Here the source code


Change Snippet Background Color
          
            
import java.util.*;
import java.lang.*;
import java.math.*;

public class Test{
   public static void main(String[] args) {
       String input = "TWENTYFIFTEEN";
       int x = 17;
       int y = 20;
       String enc = encrypt(input,x,y);
       String dec = decrypt(enc,x,y);
       System.out.println("Input:     " + input);
       System.out.println("Decrypted: " + enc);
       System.out.println("Decrypted: " + dec);
   }
   
   public static String encrypt(String input,int FK,int SK) {
       String str = "";
       for (int in = 0; in < input.length(); in++) {
           char get = input.charAt(in);
           if (Character.isLetter(get)) {
               // ax + b % 26
               get = (char) ((FK * (int)(get + 'A') + SK) % 26 + 'A');
           }
           str +=get;
       }
       return str;
   }
   
   public static String decrypt(String input,int FK,int SK) {
       String str = "";
       int x = 0;
       int inverse = 0;
       
       // find 1 by using modular inverse
       // 17 * IN mod 26 == 1
       // IN is 0 - infiniti
       // if total == 1, then IN is the inverse modular
       while(true){
         inverse = FK * x % 26;
            if(inverse == 1)
               break;
         x++;
       }
       
       for (int in = 0; in < input.length(); in++) {
           char get = input.charAt(in);
           if (Character.isLetter(get)) {
               // IN *(x-b) mod 26
               get = (char)(x * ((get + 'A') - SK) % 26 + 'A');
           }
           str +=get;
       }
       return str;
   }
}

          
        

Saturday, November 7, 2015

Odd Even Caesar Cipher

Same concept as Caesar cipher but we do alternating even and odd shifting. For even, shift to the right and for the odd, shift it the left.

For example: SAYA MAKAN NASI

Cipher     : XVDV HFFFI IFNN


To decrypt it just start from odd shift. For decrypt without key, try from 1-26 shifting method. :)



  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
import java.util.*;
import java.io.*;

public class OddEvenCaesar{
    
    public static void main(String[] args){
      System.out.print(Encode("Saya makan nasi",5));
      System.out.print(Decode("Xvdv hfffi ifnn",5));
      DecodeNoKey("Xvdv hfffi ifnn");
    }
    
    public static String Encode(String enc, int offset) {
        offset = offset % 26;
        StringBuilder encoded = new StringBuilder();
        
        int count =0;
        
        for (char i : enc.toCharArray()) {
            if(count%2 == 0){
               if (Character.isLetter(i)) {
                   if (Character.isUpperCase(i)) {
                       encoded.append((char) ('A' + (i - 'A' + offset) % 26 ));
                   } else {
                       encoded.append((char) ('a' + (i - 'a' + offset) % 26 ));
                   }
               } else {
                   encoded.append(i);
               }
            }
            else if(count%2 == 1){
               if (Character.isLetter(i)) {
                   if (Character.isUpperCase(i)) {
                       encoded.append((char) ('A' + (i - 'A' + 26-offset) % 26 ));
                   } else {
                       encoded.append((char) ('a' + (i - 'a' + 26-offset) % 26 ));
                   }
               } else {
                   encoded.append(i);
               }
            }
            
            count++;
        }
        return encoded.toString();
    }
    
    public static String Decode(String enc, int offset) {
        offset = offset % 26;
        StringBuilder decoded = new StringBuilder();
        
        int count =0;
        
        for (char i : enc.toCharArray()) {
            if(count%2 == 1){
               if (Character.isLetter(i)) {
                   if (Character.isUpperCase(i)) {
                       decoded.append((char) ('A' + (i - 'A' + offset) % 26 ));
                   } else {
                       decoded.append((char) ('a' + (i - 'a' + offset) % 26 ));
                   }
               } else {
                   decoded.append(i);
               }
            }
            else if(count%2 == 0){
               if (Character.isLetter(i)) {
                   if (Character.isUpperCase(i)) {
                       decoded.append((char) ('A' + (i - 'A' + 26-offset) % 26 ));
                   } else {
                       decoded.append((char) ('a' + (i - 'a' + 26-offset) % 26 ));
                   }
               } else {
                   decoded.append(i);
               }
            }
            
            count++;
        }
        return decoded.toString();
    }
    
    public static void DecodeNoKey(String enc) {
        
        for(int x=0;x<26;x++){
           int offset = x % 26;
           StringBuilder decoded = new StringBuilder();
           
           int count =0;
           
           for (char i : enc.toCharArray()) {
               if(count%2 == 1){
                  if (Character.isLetter(i)) {
                      if (Character.isUpperCase(i)) {
                          decoded.append((char) ('A' + (i - 'A' + offset) % 26 ));
                      } else {
                          decoded.append((char) ('a' + (i - 'a' + offset) % 26 ));
                      }
                  } else {
                      decoded.append(i);
                  }
               }
               else if(count%2 == 0){
                  if (Character.isLetter(i)) {
                      if (Character.isUpperCase(i)) {
                          decoded.append((char) ('A' + (i - 'A' + 26-offset) % 26 ));
                      } else {
                          decoded.append((char) ('a' + (i - 'a' + 26-offset) % 26 ));
                      }
                  } else {
                      decoded.append(i);
                  }
               }
               
               count++;
           }
           System.out.println(decoded.toString());
       }
    }

}

Friday, October 16, 2015

Railfence Columnar Cipher

This is the combination of Rail fence Cipher with Columnar implementation..



  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
import java.util.*;

public class RFwithColumnar {
    public static void main(String[] args) {

        String text = "IF YOU CAN READ THIS YOU ARE GENIUS";
        String key = "HACK";

        String enc = RFCEncryption(text, key);

        System.out.println(enc);
    }

    public static String RFCEncryption(String text, String keytext) {
        int[] arrange = arrangeKey(keytext);

        int key = arrange.length;
        int lentext = text.length();

        int move = 1;
        int count = 0;
        String[][] rfp = new String[key][lentext];

        // arrange dot fence
        for (int x = 0; x < rfp.length; x++) {
            for (int y = 0; y < rfp[x].length; y++) {
                rfp[x][y] = ".";
            }
        }

        // formatting according fence rails
        for (int i = 0; i < lentext; i++) {
            if ((move % 2) != 0) {
                rfp[count][i] = "" + text.charAt(i);
                if (count == (key - 1)) {
                    move = 2;
                    count = (key - 2);
                } else
                    count++;
            } else if ((move % 2) == 0) {
                rfp[count][i] = "" + text.charAt(i);
                if (count == 0) {
                    move = 1;
                    count = 1;
                } else
                    count--;
            }
        }

        //replace any white space with X or random
        for (int x = 0; x < rfp.length; x++) {
            for (int y = 0; y < rfp[x].length; y++) {
                if (rfp[x][y].equals(" "))
                    rfp[x][y] = ""+Character.toUpperCase(RandomAlpha());
            }
        }

        // display
        System.out.println();
        for (int i = 0; i < rfp.length; i++) {
            for (int u = 0; u < rfp[i].length; u++) {
                System.out.print(rfp[i][u] + " ");
            }
            System.out.println();
        }
        System.out.println();


        StringBuilder cb = new StringBuilder();
        //encode string from fence
        for (int x = 0; x < key; x++) {
            for (int y = 0; y < key; y++) {
                if (x == arrange[y]) {
                    for (int u = 0; u < lentext; u++) {
                        if (!".".equals(rfp[y][u])) {
                            cb.append(rfp[y][u]);
                        }
                    }
                }
            }
        }
        return "" + cb;
    }
    
    public static int[] arrangeKey(String key) {
        //arrange position of grid
        String[] keys = key.split("");
        Arrays.sort(keys);
        int[] num = new int[key.length()];
        for (int x = 0; x < keys.length; x++) {
            for (int y = 0; y < key.length(); y++) {
                if (keys[x].equals(key.charAt(y) + "")) {
                    num[y] = x;
                    break;
                }
            }
        }
        System.out.println(Arrays.toString(num));
        return num;
    }
    
    public static char RandomAlpha() {
        //generate random alpha for null space
        Random r = new Random();
        return (char)(r.nextInt(26) + 'a');
    }
}

Thursday, October 8, 2015

Kamasutra Cipher

One of the earliest descriptions of encryption by substitution appears in the Kama-sutra, a text written in the 4th century AD by the Brahmin scholar Vatsyayana, but based on manuscripts dating back to the 4th century BC. The Kama-sutra recommends that women should study 64 arts, including cooking, dressing, massage and the preparation of perfumes. The list also includes some less obvious arts, including conjuring, chess, bookbinding and carpentry. Number 45 on the list is mlecchita-vikalpa, the art of secret writing, advocated in order to help women conceal the details of their liaisons. One of the recommended techniques involves randomly pairing letters of the alphabet, and then substituting each letter in the original message with its partner.4

How it work
The kamasutra generate list of 26 alphabet with no duplicate. Then divide by 2 row. Find for each letter of message text in table and choose the opposite of the letter

for example:
Key = G H A J R I O B E S Q C L F V Z T Y K M X W N U D P

divide by 2 rows

G H A J R I O B E S Q C L
F V Z T Y K M X W N U D P

Given String = KAMASUTRA

K is at 2nd row and 5th column. Get the opposite of K that is I. Do each letter until the end

Cipher : IZOZNQJYZ

To decyrpt the cipher, use the table with same random list of 26 alphabet. Without the key is difficult to decrypt because of  26! = 403,291,461,000,000,000,000,000,000 = 403 septilion of combination of key can be produce uniquely.




 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
/*
   authors by hafiq
   
   Kamasutra Cipher and decrytion
      
   any expert can advise me to improve this code...tq..
*/
import java.util.*;

public class KSCipher{
   public static void main(String[] args){
      String text = "KAMA SUTRA CIPHER";
      String key  = RandomAlphaNoDuplicate(26);
      
      String enc = KSutra(text,key);
      System.out.println("Encryption: "+ enc);
      String dec = KSutra(enc,key);
      System.out.println("Decryption: "+ dec);
   }
   
   public static String RandomAlphaNoDuplicate(int len){
      Random r = new Random();
      String key = "";
      for (int i = 0; i < len;) {
          char c = (char) (r.nextInt(26) + 'A');
          if(!key.toString().contains(""+c)){
             key = key + c;
             i++;
          }
      }      
      return key;
   }
   
   public static String KSutra(String text,String key){
      int keyLen = key.length()/2;
      
      // arrange random key
      char[][] keyRow = new char[2][keyLen];
      int count=0;
      for(int x=0;x<2;x++){
         for(int y=0;y<keyLen;y++){
            keyRow[x][y] = key.charAt(count);
            System.out.print(keyRow[x][y]+" ");
            count++;
         }
         System.out.println();
      }
      
      String sb = "";
      
      count=0;
      for(int x=0;x<text.length();x++){
         for(int y=0;y<2;y++){
            for(int z=0;z<keyLen;z++){
               if(y == 0){
                  if(text.charAt(x) == keyRow[y][z])
                     sb += keyRow[y+1][z];
               }
               else if (y == 1){
                  if(text.charAt(x) == keyRow[y][z])
                     sb += keyRow[y-1][z];
               }
            }
         }
         if(text.charAt(x) == ' ')
            sb += text.charAt(x);
      }
      
      return sb;
   }
}

One-Time Pad Cipher

In cryptography, the one-time pad (OTP) is an encryption technique that cannot be cracked if used correctly. It was invented near the end of WWI by Gilbert Vernam and Joseph Mauborgne in the US. It was mathematically proven unbreakable by Claude Shannon, probably during WWII, his work was first published in the late 1940s.

How it work

In this technique, a plaintext is paired with a random secret key (also referred to as a one-time pad). Then, each bit or character of the plaintext is encrypted by combining it with the corresponding bit or character from the pad using modular addition. If the key is truly random, is at least as long as the plaintext, is never reused in whole or in part, and is kept completely secret, then the resulting ciphertext will be impossible to decrypt or break.

Are one-time pads really unbreakable?

Yes. But only if used properly. A one-time pad must be truly random data and must be kept secure in order to be unbreakable. Consider if the one-time pad is used to encode the word "otter." If an attacker tries to brute force "guess" the contents of the pad, the message will "decrypt" into every possible combination of 6 characters (e.g.: "lemur." "badger" etc..) Since the pad is truly random there are no statistical methods that the attacker can hope to use to infer which combination is correct.

Below is the example of one time cipher work



In this example, the technique is to combine the key and the message using modular addition. The numerical values of corresponding message and key letters are added together, modulo 26 (%26). So, if key randomly begins with "XMCKL" and the message is "HELLO", then the coding would be done as follows:

Calculation:

A B C D E F G H I J K  L  M  N  O  P  Q  R  S  T  U  V  W  X  Y  Z
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25

H + X = E because 7 + 23 = 30 % 26 = 4 is E
E + M = Q because 4 + 12 = 16 % 26 = 16 is Q
so on..


      H       E       L       L       O  message
   7 (H)   4 (E)  11 (L)  11 (L)  14 (O) message
+ 23 (X)  12 (M)   2 (C)  10 (K)  11 (L) key
= 30      16      13      21      25     message + key
=  4 (E)  16 (Q)  13 (N)  21 (V)  25 (Z) message + key (mod 26)
      E       Q       N       V       Z  → ciphertext


Ciphertext = EQNVZ
This is similar with caesar cipher. This simply means that if the computations "go past" Z, the sequence starts again at A.

Now, Let's Decrypt

The ciphertext is "EQNVZ". Use the matching key and the same process but in reverse to obtain the plaintext. Here the key is subtracted from the ciphertext again using modular arithmetic:

       E       Q       N       V       Z  ciphertext
    4 (E)  16 (Q)  13 (N)  21 (V)  25 (Z) ciphertext
-  23 (X)  12 (M)   2 (C)  10 (K)  11 (L) key
= -19       4      11      11      14     ciphertext – key
=   7 (H)   4 (E)  11 (L)  11 (L)  14 (O) ciphertext – key (mod 26)
       H       E       L       L       O  → message

Text = HELLO

However, it is difficult to ensure that the key is actually random is used only once, never becomes known to the opposition and is completely destroyed after use. The auxiliary parts of a software one-time pad implementation present real challenges: secure handling/transmission of plaintext truly random keys and one-time-only use of the key.

Wednesday, October 7, 2015

Vigenere cipher

The Vigenère cipher is a method of encrypting alphabetic text by using a series of different Caesar ciphers based on the letters of a keyword. It is a simple form of polyalphabetic substitution.

This cipher is similar with caesar cipher but different in term of shifting. The Vigenère cipher consists of several Caesar ciphers in sequence with different shift values. To encrypt, a table of alphabets can be used called Vigenère table. It consists of the alphabet written out 26 times in different rows, each alphabet shifted cyclically to the left compared to the previous alphabet, corresponding to the 26 possible Caesar ciphers.

Vigenere table
For example, suppose that the plaintext to be encrypted is:

Let Encrypt the text

Given string : ATTACKATDAWN

For the key, for example "LEMON". Repeat the word "LEMON" until the length of key is the same of the text length.

Key : LEMONLEMONLE

Then, compare the text and key using vigenere table.

Plaintext: ATTACKATDAWN
Key:         LEMONLEMONLE

Key is the row and plaintext is the column. for example, ROW L and COLUMN A is L. ROW E and COLUMN T is X and so on.

Cipher:    LXFOPVEFRNHR

Note: just ignore the null or replace with other alphabet


Let Decrypt the cipher

Cipher:    LXFOPVEFRNHR
Key:        LEMONLEMONLE

Key is the column. at L column find the letter Cipher L and the row letter is A. at E column find the letter Cipher X and the row letter is T and so on until you get

Plaintext: ATTACKATDAWN

To decrypt Vigenere cipeher without Key is difficult..This cipher was so strong because by swapping between all 26 possible Caesar ciphers it reduced the effectiveness of frequency analysis.

But during the Crimean War of the 1850s, Charles Babbage, under pressure of the British government, broke this cipher. The steps are :-
  1. Look for sequences of letters that appear more than once in the ciphertext.
  2. Then used vigenere table to find the most common spacing factor to identify the length of the keyword.
  3. Having established the length of the keyword and performed a frequency analysis of the portion of the ciphertext corresponding to that letter.
  4. Then, matched the frequency analysis data to the frequency in normal english to find that letter of the keyword.
  5. Repeated this for every letter in the keyword.