Modulasi Analog dan Modulasi Digital dengan Input .wav (Simulink)


Kali ini kita mendapat tugas, bagaimana mentransmisikan sinyal suara .wav menggunakan Modulasi Digital dan Modulasi Analog dalam simulink. Dengarkan hasil kualitas suaranya!

Screenshot from 2016-01-31 11:27:56

Skema simulink diatas adalah satu cara untuk mentransmisikan data menggunakan modulasi Analog dan Digital, bagian atas adalah modulasi Analog menggunakan SSB AM dan Bagian bawah adalah digital mengunakan DBPSK. Perlu diketahui untuk input modulasi digital data merupakan data diskrit atau data digital. Oleh sebab itu kita memerlukan konversi dari bentuk suara ke bentuk diskrit/digital.

Hal ini sering disebut ADC (analog to Digital Converter) namun saya tidak ingin menyebutkan di simulasi ini adalah ADC karena pada dasarnya file .wav ini sendiri sudah dalam bentuk digital/diskrit karena sudah tersimpan didalam disk berupa file digital berbentuk .wav. Sejenak kita lupakan tentang kontroversi ADC ini sendiri. kembali kedalam modulasi

Sebelum masuk ke dalam modulasi digital kita menambahkan blok Uniform Encoder dan integer to bit. Blok Uniform Encoder ini merupakan proses Kuantisasi yang menggunakan standart ITU-T Recommendation G.701. Hal ini lazim digunakan pada data file suara yang tidak terkompresi.

Setelah file terkuantisasi dalam bentuk diskrit, kita perlu merubah nilai nilai diskrit tersebut ke bentuk digital atau binary. Blok yang kita bisa gunakan adalah Blok Integer to Bit. Sebenarnya kurang tepat juga kita mengatakan blok tersebut adalah blok yang mengubah bentuk nilai integer kdealam bentuk binary karena hasil quantisasi bisa dalam bentuk floating point atau nilai angka berkoma, namun jangan terlalu pusing dengan intepretasi tipe variable Integer atau Floating sebab di dalam blok Uniform encoder dan Integer to Bit kita bisa mensetting berapa bit yang akan kita gunakan. yang kita gunakan dalam simulasi ini adalah 8 bit karena encoder yang digunakan dari file .wav itu sendiri 8 bit.

Dimana proses sampling? sebenarnya proses sampling ada didalam file itu sendiri yaitu 8Khz. Jika kita runut kembali proses sampling-Kuantisasi-Encoding adalah proses ADC, yang kita simulasikan kembali di Simulink, ya kita hanya mensimulasikan kembali tanpa sebenarnya melakukan proses dari ADC itu sendiri dikarenakan sebenarnya proses ADC itu sendiri sudah terjadi disaat kita merekam suara tersebut

File Simulink dapat didowload dilink berikut, run file simulink tersebut dan bandingkan suaranya, kita juga bisa bandigkan hasi dari grafik waktu ataupun grafik frequency disetiap stepnya menggunakan block spectrum dan time scope.

File Simulink
File .wav (sumber )

Respon Impuls Filter Digital Matlab Simullink


Sebagai contoh kita diberikan tugas, buat skema respon impuls filter digital (direct Form 1) dibawah ini pada simulink

vcxz

dengan spesifikasi sebagai berikut

Filter BPF (Wstop1 = 0.0625, Wstop2=0.0875, Wpass1=0.2625, Wpass2=0.2875), Rp = 1dB, Rs = 60dB

pada dasarnya kita dapat membuat implementasi dalam code matlab secara mudah dan langsung sebagai berikut:

Sebagai contoh kita menggunakan sepesifikasi filter Band Pass Filter BPF dengan spesifikasi diatas

clc, clear all
Ws = [0.0625 0.2875];
Wp = [0.0875 0.2625];
Rp = 1;
Rs = 60;
[n, Wn]= ellipord(Wp, Ws, Rp, Rs);
[b, a] = ellip(n, Rp, Rs,  Wn);
t=0:0.01:1;
X=1*sin(2*pi.*t);
y = filter(b,a,X);
figure,
freqz(b,a)
figure,
subplot(2,1,1)
plot(t,X)
subplot(2,1,2)
plot(t,y), grid on

hasil grafik yang kita dapatkan adalah, sebagai berikut
Screenshot from 2016-01-31 10:39:33
Respon Magnitude dan Fasa Filter yg ditampilkan melalui freqz(b,a)

Screenshot from 2016-01-31 10:40:43
grafik 1 dalah grafik sinyal input berupa sinusiodal dan grafik dibawahnya adalah grafik sinyal output yang telah terfilter menggunakan y = filter(b,a,X);

Nilai a (denumerator) dan b (numerator)

a =

1.0e+03 *

Columns 1 through 6

0.0010 -0.0114 0.0625 -0.2155 0.5241 -0.9507

Columns 7 through 12

1.3259 -1.4439 1.2337 -0.8231 0.4222 -0.1615

Columns 13 through 15

0.0436 -0.0074 0.0006

>> b

b =

Columns 1 through 6

0.0021 -0.0182 0.0758 -0.1945 0.3376 -0.3977

Columns 7 through 12

0.2769 0.0000 -0.2769 0.3977 -0.3376 0.1945

Columns 13 through 15

-0.0758 0.0182 -0.0021

hasil tersebut sudah cukup untuk kita mengetahui bagaimana membuat filter dan menggunakan filter tersebut dalam program matlab, namun bagaimana untuk di simulink
Disimulink setidaknya ada 3 cara yaitu menggunakan Filter FDA tools, Discrete filter block dan membuat response impluse sendiri. Namun dengan menggunakan Discrete filter block dan membuat response impluse sendiri kita harus mencari nilai a dan b terlebih dahulu bisa menggunakan code diatas ata FDA tools, berikut simulasi pada simulink:

Screenshot from 2016-01-31 10:51:25
simulink block

Screenshot from 2016-01-31 10:51:53
hasil input dan output

jika kita perhatikan file diatas mengapa hasil filter dari grafik ke 2 berbeda dengan grafik ke 3 & 4? hal tersebut terjadi karena perbedaan penggunaan direct form dalam implementasi tranformasi Z pada filter, Grafik 2 atau hasil Dari FDA tool box menggunakan direct form II sebagai mana ditampilkan ada screenshoot berikut:
Screenshot from 2016-01-31 11:06:25

Sedangkan pada grafik 3 dan 4 kita menggunakan Direct form I, tentunya kita dapat memodifikasi design kita menggunakan Direct form I atau Direct Form II sesuai dengan kebutuhan kita, selain perbedaan pada Direct form, juga terdapat perbedaan pada ordo yang digunakan pada FDA toolboox orde yang digunakan sebanyak 18 sedangkan pada grafik 3&4 menggunakan ordo sebanyak 15. Tentunya kita bisa mendalami lagi mengenai parameter parameter lainnya pada filter digital

file dapat didownload di link berikut:
File Simulink https://www.dropbox.com/s/wn5mo8bqbhgxuif/FilterBPFPro2x1.mdl?dl=0
File mfile https://www.dropbox.com/s/z9k5014zpcbahfy/Set_parameter.m?dl=0

Enkripsi Citra menggunakan javax.crypto bagian 2


Setelah kita mencoba membuat enkripsi citra http://wp.me/prw8r-1cR, namun hasil enkripsi tidak dapat dilihat dikarenakan perubahan pada header citra digital yang menyebabkan komputer tidak dapat mendeteksi type file dll.

setidaknya ada 2 alternatif untuk mengatasi masalah tersebut, alternatif pertama adalah enkripsi dilakukan hanya pada byte nilai pixel dan juga enkripsi tidak dilakukan pada file-file header. Cara tersebut sangat cocok bagi type file uncompressed seperti .bmp dikarenakan niai-nilai byte pada pixel berkisar antara 0-255 dan memiliki letak posisi yang jelas pada posisi format byte. sebagai contoh berikut

Screenshot from 2016-01-27 09:13:52

perhatikan pada posisi byte ke 10 dengan nilai 0x36 dalam format .bmp kita dapat mendapatkan posisi awal dari nilai pixel yaitu pada byte ke 36, detailnya bisa dilihat di https://en.wikipedia.org/wiki/BMP_file_format dengan begitu kita dapat mengenkripsi hanya pada nilai pixel nya tanpa mengenkripsi headernya atau informasi lainnya.


import imageEncryption.ImageBMP;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.KeyGenerator;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKey;
import javax.imageio.ImageIO;

	public class Des_imagebezheader {
		KeyGenerator keyGenerator = null;  
	    SecretKey secretKey = null;  
	    Cipher cipher = null;  
	  
	    public Des_imagebezheader() {  
	        try {   
	            keyGenerator = KeyGenerator.getInstance("DES");  
	            secretKey = keyGenerator.generateKey();  
	            
	            
	            cipher = Cipher.getInstance("DES/ECB/NoPadding");  
	        } catch (NoSuchPaddingException ex) {  
	            System.out.println(ex);  
	        } catch (NoSuchAlgorithmException ex) {  
	            System.out.println(ex);  
	        }  
	    }  
	    
	    public static void main(String[] args) throws InvalidKeyException, IllegalBlockSizeException, BadPaddingException, IOException {  
	        String fileToEncrypt = "XING_B24.BMP";  
	        String encryptedFile = "encryptXING_B24.bmp";  
	        String decryptedFile = "decryptXING_B24.bmp";    
	        String directoryPath = "/media/ratjoen/javaFiles/Izhobrazhenie_KriptografiyV3.0L/";  
	        Des_imagebezheader encryptFile = new Des_imagebezheader();  
	        System.out.println("Starting Encryption...");  
	        encryptFile.encrypt(directoryPath + fileToEncrypt,  
	                directoryPath + encryptedFile);  
	        System.out.println("Encryption completed...");   
	        
	        System.out.println("Starting Decryption...");  
	        encryptFile.decrypt(directoryPath + encryptedFile,  
	                directoryPath + decryptedFile);  
	        System.out.println("Decryption completed...");
	    }  
	    
	    private void encrypt(String srcPath, String destPath) throws InvalidKeyException, IOException, IllegalBlockSizeException, BadPaddingException {  
	        File rawFile = new File(srcPath);  
	        File encryptedFile = new File(destPath);  
	        InputStream inStream = null;  
	        OutputStream outStream = null;  
	     
	        cipher.init(Cipher.ENCRYPT_MODE, secretKey);  
	        
	        try {
	        inStream = new FileInputStream(rawFile);
	        outStream = new FileOutputStream(encryptedFile);  

	        int lengfile = (int) rawFile.length() ;
	       
	        byte[] buffer = new byte[lengfile]; 
	        inStream.read(buffer);
	        
	        System.out.println(buffer.length);
	        int startP = buffer[10];//for bmp format
	        System.out.println(startP);
	        
	        int lengthE = lengfile-startP;
	       
	        
	        byte[] bufferE = new byte[lengthE]; 
	       
	        for (int i = 0; i < bufferE.length ; i++){
	        	bufferE[i]=buffer[i+startP];
	        }
	        
	        byte[] bufferP = new byte[lengthE]; 
	        
	        cipher.update(bufferE, 0, lengthE , bufferP, 0);
	        cipher.doFinal(bufferP);  
	        
	        for (int i = 0; i < bufferE.length ; i++){
	        	buffer[i+startP]=bufferP[i];
	        }
	        
	        outStream.write(buffer);  
            outStream.flush();
	       
	        }catch(Exception e){
	        	e.printStackTrace();
	        }
	    }
	           	 
	          
	    private void decrypt(String srcPath, String destPath) throws InvalidKeyException, IOException, IllegalBlockSizeException, BadPaddingException {  
	        File rawFile = new File(srcPath);  
	        File encryptedFile = new File(destPath);  
	        InputStream inStream = null;  
	        OutputStream outStream = null;  
	     
	        cipher.init(Cipher.DECRYPT_MODE, secretKey);  
	        
	        try {
	        inStream = new FileInputStream(rawFile);
	        outStream = new FileOutputStream(encryptedFile);  

	        int lengfile = (int) rawFile.length() ;
	        String Format = rawFile.getName();
	        byte[] buffer = new byte[lengfile]; 
	        inStream.read(buffer);
	        
	        System.out.println(buffer.length);
	        int startP = buffer[10];//for bmp format
	        System.out.println(startP);
	        
	        int lengthE = lengfile-startP;
	       
	        
	        byte[] bufferE = new byte[lengthE]; 
	       
	        for (int i = 0; i < bufferE.length ; i++){
	        	bufferE[i]=buffer[i+startP];
	        }
	        
	        byte[] bufferP = new byte[lengthE]; 
	        
	        cipher.update(bufferE, 0, lengthE , bufferP, 0);
	        cipher.doFinal(bufferP);  
	        
	        for (int i = 0; i < bufferE.length ; i++){
	        	buffer[i+startP]=bufferP[i];
	        }
	        
	        outStream.write(buffer);  
            outStream.flush();
	       
	        }catch(Exception e){
	        	e.printStackTrace();
	        }
	    }        
	}

Screenshot from 2016-01-27 09:34:08

Screenshot from 2016-01-27 09:34:00

Menggambar kurva 2D, kurva 3D dan menghitung integral pada matlab


contoh soal sebagai berikut (sumber https://www.facebook.com/groups/570918222980206/)
12645270_1218062701556010_5345357511037463031_n

clear, close all, clc
%No1 http://www.mathworks.com/help/matlab/ref/plot.html
x=-10:0.1:10;
y1=sqrt(49+4.*x.^2);
y2=sqrt(64+3.*x.^2);
plot(x,y1),hold on, grid on
plot(x,y2,'r')
%No2 http://www.mathworks.com/help/matlab/ref/plot3.html
t=0:0.1:2*pi;
x=1+cos(t);
y=2+sin(t);
z=1-cos(2.*t);
figure
plot3(x,y,z), grid on
%No3a http://www.mathworks.com/help/symbolic/int.html
syms x y
pretty(int(2*x*y*exp(2*y),y))
%No3b http://www.mathworks.com/help/matlab/ref/integral.html
fun = @(x,y) 10-2.*x.^2-y.^2
q = integral2(fun,-4,5,-5,5)
%No3c http://www.mathworks.com/help/symbolic/diff.html
syms x
diff((1/2)*x*y*exp(2*y),y)
%No3d http://www.mathworks.com/help/symbolic/diff.html
syms x y
diff(diff(exp(-x^3-y)))

Enkripsi Citra menggunakan javax.crypto


kali ini kita akan mencoba mengenkripsi citra menggunakan javax.crypto, beberapa library lainnya juga kita gunakan untuk menunjanng agar data berupa image dapat di enkripsi. Salah satu source code yang tersedia di internet adalah sebagai berikut http://www.theinsanetechie.in/2011/09/java-data-encryption-standard-des.html

package dataencryptionstandart;

import java.io.File;  
import java.io.FileInputStream;  
import java.io.FileNotFoundException;  
import java.io.FileOutputStream;  
import java.io.IOException;  
import java.io.InputStream;  
import java.io.OutputStream;  
import java.security.InvalidKeyException;  
import java.security.NoSuchAlgorithmException;  
import javax.crypto.BadPaddingException;  
import javax.crypto.Cipher;  
import javax.crypto.IllegalBlockSizeException;  
import javax.crypto.KeyGenerator;  
import javax.crypto.NoSuchPaddingException;  
import javax.crypto.SecretKey;  
  
/** 
 * 
 * @author dhanoopbhaskar 
 */  
public class desimage {  
  
    KeyGenerator keyGenerator = null;  
    SecretKey secretKey = null;  
    Cipher cipher = null;  
  
    public desimage() {  
        try {   
            keyGenerator = KeyGenerator.getInstance("DES");  
            secretKey = keyGenerator.generateKey();  
            cipher = Cipher.getInstance("DES");  
        } catch (NoSuchPaddingException ex) {  
            System.out.println(ex);  
        } catch (NoSuchAlgorithmException ex) {  
            System.out.println(ex);  
        }  
    }  
  
    public static void main(String[] args) {  
        String fileToEncrypt = "5.png";  
        String encryptedFile = "encryptedFile.png";  
        String decryptedFile = "decryptedFile.png";  
        String directoryPath = "/media/ratjoen/javaFiles/Izhobrazhenie_KriptografiyV3.0L/";  
        desimage encryptFile = new desimage();  
        System.out.println("Starting Encryption...");  
        encryptFile.encrypt(directoryPath + fileToEncrypt,  
                directoryPath + encryptedFile);  
        System.out.println("Encryption completed...");  
        System.out.println("Starting Decryption...");  
        encryptFile.decrypt(directoryPath + encryptedFile,  
                directoryPath + decryptedFile);  
        System.out.println("Decryption completed...");  
    }  
  
    /** 
     *  
     * @param srcPath 
     * @param destPath 
     * 
     * Encrypts the file in srcPath and creates a file in destPath 
     */  
    private void encrypt(String srcPath, String destPath) {  
        File rawFile = new File(srcPath);  
        File encryptedFile = new File(destPath);  
        InputStream inStream = null;  
        OutputStream outStream = null;  
        try {  
            /** 
             * Initialize the cipher for encryption 
             */  
            cipher.init(Cipher.ENCRYPT_MODE, secretKey);  
            /** 
             * Initialize input and output streams 
             */  
            inStream = new FileInputStream(rawFile);  
            outStream = new FileOutputStream(encryptedFile);  
            byte[] buffer = new byte[1024];  
            int len;  
            while ((len = inStream.read(buffer)) > 0) {  
                outStream.write(cipher.update(buffer, 0, len));  
                outStream.flush();  
            }  
            outStream.write(cipher.doFinal());  
            inStream.close();  
            outStream.close();  
        } catch (IllegalBlockSizeException ex) {  
            System.out.println(ex);  
        } catch (BadPaddingException ex) {  
            System.out.println(ex);  
        } catch (InvalidKeyException ex) {  
            System.out.println(ex);  
        } catch (FileNotFoundException ex) {  
            System.out.println(ex);  
        } catch (IOException ex) {  
            System.out.println(ex);  
        }  
    }  
  
    /** 
     *  
     * @param srcPath 
     * @param destPath 
     * 
     * Decrypts the file in srcPath and creates a file in destPath 
     */  
    private void decrypt(String srcPath, String destPath) {  
        File encryptedFile = new File(srcPath);  
        File decryptedFile = new File(destPath);  
        InputStream inStream = null;  
        OutputStream outStream = null;  
        try {  
            /** 
             * Initialize the cipher for decryption 
             */  
            cipher.init(Cipher.DECRYPT_MODE, secretKey);  
            /** 
             * Initialize input and output streams 
             */  
            inStream = new FileInputStream(encryptedFile);  
            outStream = new FileOutputStream(decryptedFile);  
            byte[] buffer = new byte[1024];  
            int len;  
            while ((len = inStream.read(buffer)) > 0) {  
                outStream.write(cipher.update(buffer, 0, len));  
                outStream.flush();  
            }  
            outStream.write(cipher.doFinal());  
            inStream.close();  
            outStream.close();  
        } catch (IllegalBlockSizeException ex) {  
            System.out.println(ex);  
        } catch (BadPaddingException ex) {  
            System.out.println(ex);  
        } catch (InvalidKeyException ex) {  
            System.out.println(ex);  
        } catch (FileNotFoundException ex) {  
            System.out.println(ex);  
        } catch (IOException ex) {  
            System.out.println(ex);  
        }  
    }  
}  

namun hasil yang diharapkan kurang sesuai dengan yang saya inginkan dikarenakan hasil enkripsi tidak dapat dibuka
Screenshot from 2016-01-21 15:55:16

mengapa hal tersebut terjadi, kita bisa lihat detailnya dalam hex menggunakan xxd pada linux command

File asli:
Screenshot from 2016-01-21 15:56:37

File terenkripsi
Screenshot from 2016-01-21 15:58:09

dari capture hex tersebut kita bisa lihat di baris pertama bahwa 8950 yang merupakan extensi dari .PNG juga ikut terenkripsi menjadi 0eda hal tersebut menyebabkan tidak dapat nya komputer mendisplay citra yang telah terenkripsi. namun saat sudah file yang telah terdekripsi dapat terdisplay karena hex kembali seperti semula

bagaimana caranya agar kita tidak mengenkripsi file format header, tetapi hanya nilai pixel nya?

How Do You Know the Policy Files Really Behave as Sun Says They Do?


When you look at the history behind the JCE, it is easy to see why some people would be inclined to feel it is all a conspiracy by Sun, the U.S. government, the UN, the Illuminati, the Greys, or some other “organization” and that anything running under the JCE should not be trusted, as you cannot see the code that deals with key strength and various other control mechanisms that the policy files allow you to turn on or off. If this is a concern for you, remember, just as you would test a hardware cryptography adapter by comparing its outputs for given inputs against the outputs produced by an alternative implementation for the same set of outputs, you can also treat the JCE and the underlying provider as a black box and perform the same tests. As it happens the Bouncy Castle provider was first developed as a lightweight library for MIDP, so if you are feeling really enthused, you can start by verifying that the Bouncy Castle provider and the JCE is producing the same output as its lightweight equivalent. It is true that in matters like these you should not take what people tell you at face value, but always remember you can test and investigate the truth of other people’s claims yourself.

David Hook-Beginning Cryptography with Java-Wrox (2005)

Buku Cryptography for Internet and Database Applications


salah satu buku tentang kriptografi yang recommended Cryptography for Internet and Database Applications Developing Secret and Public Key Techniques with JavaTM oleh Nick Galbreath,

berikut daftar isi dari buku tersebut

Chapter 1 Bits and Bytes
General Operations
Number Bases
Bits and Bytes
Signed Bytes
Bitwise Operators
Complementation or Bitwise NOT
Bitwise AND
Bitwise OR
Bitwise Exclusive OR (XOR)
Left-Shift
Right-Shift
Special Operations and Abbreviations
Packed Words
Integers and Endian Notation
Java Numerics
Basic Types
Type Conversion
Unsigned to Signed Conversions
Overflow
Arrays
Numeric Classes
Booleans and BitFields
Chars
Working with Bytes
Sign Problems
Conversion of Integral Types to Byte Arrays
Converting to Hex Strings
BigInteger
Creating and Converting
BigInteger and Cryptography
Secret Methods in BigInteger

Chapter 2 Secret Key Cryptography
Symmetric Block Ciphers
Cipher Properties
Security Properties
Brute-Force Attacks
Other Attacks
Common Block Ciphers
Data Encryption Standard (DES)
Triple DES
Blowfish
IDEA
RC5
Rijndael and the Advanced Encryption Standard (AES)
Twofish
RC6
Ciphers You Shouldn’t Use
Password XOR Schemes
Classical Cryptography
ROT 13
Padding
Fixed-Value Padding
Random Padding
PKCS Padding
Modes of Operations
Initialization Vectors
Electronic Codebook Mode (ECB)
Cipher Block Chaining Mode (CBC)
Cipher Feedback Mode (CFB)
Output Feedback Mode (OFB)
Counter Mode (CTR)
Propagating CBC (PCBC) Mode
Key Wrapping
Triple DES KEY Wrapping
AES Key Wrapping
Turning Passwords into Keys
Elliptic Curves
Underlying Mathematics: Elliptic Curves
The Algorithm
Standards and Practice
Other Public Key Cryptographic Systems
Rabin Cryptosystem
NTRU

Chapter 4
Summary
Random Numbers
Randomness and Security
Testing for Randomness
FIPS 140-2 Requirements
Pseudorandom Number Generators
Cryptographic PRNG
SHA-1 PRNG
Cipher-CBC or ANSI X9.17
FIPS 186
Blum-Blum-Shub
Stream Ciphers
One-Time Pads
RC4 or ArcFour
Using Randomness
Generating Random Numbers for Gaming
Generating Random Numbers in a Range
Shuffling
Generating Random Permutations
Small Permutations
Large Fixed Permutations
Random Sampling
Accessing Entropy
OS Services
Win32 CryptoAPI CryptGenRandom
/dev/random and friends
Userland Services
Entropy Generating Daemon (EGD)
PRNGD
Yarrow and EGADS
TrueRand Library
Remote Services
RAND Corporation
HotBits
Random.org
LavaRnd
Java and Random Numbers
Random and SecureRandom
java.util.random
java.security.SecureRandom
Developer Issues
Reseeding
Collecting Entropy
An Entropy Pool Implementation
Basic System State
Thread Schemes
Reading External Sources
Application Events
User Events

Chapter 5 Java Cryptography
Organization
Providers and Engine Classes
Parameters, Keys, and Certificates
Error Handling
Providers
Standard Names
Standard Sun and SunJCE Providers
Other Providers
Initializing Providers
Writing Your Own Provider
Core Engine Classes
MessageDigest
Digest Streams
MAC
SecureRandom
Ciphers
Additional Cipher-Related Objects
Signatures
SignedObject
Key Agreement Protocols
Parameters, Keys, and Certificates
Algorithm Parameters
AlgorithmParameters
AlgorithmParameterGenerators
Keys
Secret Keys
Public/Private Keys
Encoding and Encrypting Keys
Summary 202

Chapter 6 Small Message Encoding and Encryption
Preprocessing 203
Converting Digits into Bytes
7-bit to 8-bit Compression
General Compression and java.util.zip.Deflate
Adding Check and Parity Bits
Small Message Encryption
Single-Block Encryption
n-Block Encryption
Very Small Message Encryption
XOR Tables
Small Codebooks
RC5-16/16
Small Message Encoding
Encoding for Customer-Usable Data
Capacity and Range
Selecting a Base Representation
Selecting Base Alphabets
Mixed Bases and Alphabets
Adding Check Digits
Encoding for Machines and Customer-Visible Applications
Base 64
Base 85
Base 128 and Java Source Encoding

Chapter 7 Application and Data Architecture
Database Architecture for Encrypted Data
Selecting a Cipher
Secret or Public?
Cipher Selection
Data
Passwords
Challenges and Responses
Payment, Credit Card, and Other Account Numbers
Social Security Number (U.S.)
Birthdates and Birthdays
Last Name
Searching, Indexing, and Constraints
Removing Randomness
Deterministic Key Selection
Indexing and Hashing
Uniqueness Constraints
Asymmetric Data Usages
Null Values and Database Applications
Secure Memory Management in Java
Smart Array Classes
Char Arrays
Using SecureRandom
Secret Key Management
Secret Key Data
Key Generation
Key Encryption
Storage
Key Access and Distribution
Using Keys with Ciphers and MACs
Passwords
Startup Passwords
Member Names and Passwords
Selecting Passwords
Member Login, Success and Failure
Changing Passwords and Challenges
Web-Based Password Entry
Generating New Passwords
Member Names
Logging
Embedded-Encryption Logging
Fully Encrypted Log Files
Public Key Logging
Split Log Files
Network-Based Logs
Cryptographic Tokens and Applications
Token Design
Expirations and Time Quantization
Creating the Security Bits
URL Tokens
Tamper-Evident URLs
Protecting Static Content
A Simple URL MAC Implementation
Fast Query String Parsing
URL Encryption
Very Short URLs
Cookie Tokens
Detecting Cookie Capability
Cookies and Authentication
Tokens for Access Control
Buy-on-Demand Systems
Multiple Key Systems
Trials and Expirations
Decimal and Monetary Computations
Doubles and Floats
BigDecimal
Rounding
BigDecimal and Mathematics
BigDecimal Alternatives and Wrappers
Usage and Storage

List Algorithm Java Security


Setelah di postingan sebelum nya kita telah mencoba membuat beberapa algortima seperti DES, RC5 dan GOST, sekarang kita akan mencoba menelaah lebih lanjut tentang java class security. algoritma apa saya yang sudah disediakan oleh class tersebut kita dapat melihat dalam script sebagai berikut:

package support_class;   
import java.security.Provider;
import java.security.Security;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;

public class ListAlgorithm {
  public static void printSet(String setName, Set algorithms) {
    System.out.println(setName + &quot;:&quot;);
    if (algorithms.isEmpty()) {
      System.out.println(&quot;            None available.&quot;);
    } else {
      Iterator it = algorithms.iterator();
      while (it.hasNext()) {
        String name = (String) it.next();

        System.out.println(&quot;            &quot; + name);
      }
    }
  }

  public static void main(String[] args) {
    Provider[] providers = Security.getProviders();
    Set&lt;String&gt; ciphers = new HashSet&lt;String&gt;();
    Set&lt;String&gt; keyAgreements = new HashSet&lt;String&gt;();
    Set&lt;String&gt; macs = new HashSet&lt;String&gt;();
    Set&lt;String&gt; messageDigests = new HashSet&lt;String&gt;();
    Set&lt;String&gt; signatures = new HashSet&lt;String&gt;();

    for (int i = 0; i != providers.length; i++) {
      Iterator it = providers[i].keySet().iterator();

      while (it.hasNext()) {
        String entry = (String) it.next();

        if (entry.startsWith(&quot;Alg.Alias.&quot;)) {
          entry = entry.substring(&quot;Alg.Alias.&quot;.length());
        }

        if (entry.startsWith(&quot;Cipher.&quot;)) {
          ciphers.add(entry.substring(&quot;Cipher.&quot;.length()));
        } else if (entry.startsWith(&quot;KeyAgreement.&quot;)) {
          keyAgreements.add(entry.substring(&quot;KeyAgreement.&quot;.length()));
        } else if (entry.startsWith(&quot;Mac.&quot;)) {
          macs.add(entry.substring(&quot;Mac.&quot;.length()));
        } else if (entry.startsWith(&quot;MessageDigest.&quot;)) {
          messageDigests.add(entry.substring(&quot;MessageDigest.&quot;.length()));
        } else if (entry.startsWith(&quot;Signature.&quot;)) {
          signatures.add(entry.substring(&quot;Signature.&quot;.length()));
        }
      }
    }

    printSet(&quot;Ciphers&quot;, ciphers);
    printSet(&quot;KeyAgreeents&quot;, keyAgreements);
    printSet(&quot;Macs&quot;, macs);
    printSet(&quot;MessageDigests&quot;, messageDigests);
    printSet(&quot;Signatures&quot;, signatures);
  }
}

hasil yang didapatkan sebagai berikut:
Ciphers:
PBEWithMD5AndDES
AESWrap SupportedPaddings
PBEWithHmacSHA512AndAES_128
AES_192/CFB/NoPadding
OID.2.16.840.1.101.3.4.1.5
OID.2.16.840.1.101.3.4.1.4
PBEWithSHA1AndRC4_128
OID.2.16.840.1.101.3.4.1.3
PBEWithMD5AndTripleDES
OID.2.16.840.1.101.3.4.1.2
OID.2.16.840.1.101.3.4.1.1
AES SupportedPaddings
OID.2.16.840.1.101.3.4.1.6
RC2
RSA
RC4
PBEWithHmacSHA512AndAES_256
RC2 SupportedPaddings
DES SupportedModes
AES_192/OFB/NoPadding
RC2 SupportedKeyFormats
OID.2.16.840.1.101.3.4.1.46
2.16.840.1.101.3.4.1.21
OID.2.16.840.1.101.3.4.1.41
2.16.840.1.101.3.4.1.23
2.16.840.1.101.3.4.1.22
DES SupportedPaddings
2.16.840.1.101.3.4.1.25
OID.2.16.840.1.101.3.4.1.44
PBEWithSHA1AndRC2_128
2.16.840.1.101.3.4.1.24
OID.2.16.840.1.101.3.4.1.45
OID.2.16.840.1.101.3.4.1.42
2.16.840.1.101.3.4.1.26
OID.2.16.840.1.101.3.4.1.43
AES_128/CFB/NoPadding
DESedeWrap SupportedModes
PBEWithHmacSHA1AndAES_256
ARCFOUR SupportedModes
AES_256/CBC/NoPadding
DESede SupportedKeyFormats
DESede SupportedModes
AESWrap_256
RSA SupportedModes
AES_192/GCM/NoPadding
AES_128/CBC/NoPadding
AESWrap SupportedModes
AES_128/OFB/NoPadding
AESWrap_128
OID.2.16.840.1.101.3.4.1.26
OID.2.16.840.1.101.3.4.1.24
ARCFOUR
OID.2.16.840.1.101.3.4.1.25
ARCFOUR SupportedPaddings
DES SupportedKeyFormats
OID.2.16.840.1.101.3.4.1.22
OID.2.16.840.1.101.3.4.1.23
AESWrap
OID.2.16.840.1.101.3.4.1.21
1.2.840.113549.1.5.3
AES_192/ECB/NoPadding
Blowfish
PBEWithHmacSHA224AndAES_128
Blowfish SupportedKeyFormats
PBEWithHmacSHA384AndAES_128
DESede
PBEWithSHA1AndDESede
PBEWithSHA1AndRC4_40
1.2.840.113549.1.12.1.3
AESWrap_192
1.2.840.113549.1.12.1.2
Rijndael
1.2.840.113549.1.12.1.1
PBEWithHmacSHA224AndAES_256
1.2.840.113549.1.12.1.6
1.2.840.113549.1.12.1.5
OID.1.2.840.113549.1.5.3
DESede SupportedPaddings
AES_256/ECB/NoPadding
AES_128/GCM/NoPadding
2.16.840.1.101.3.4.1.6
2.16.840.1.101.3.4.1.3
2.16.840.1.101.3.4.1.2
2.16.840.1.101.3.4.1.5
AES
AES_256/OFB/NoPadding
2.16.840.1.101.3.4.1.4
AES SupportedModes
Blowfish SupportedModes
AES SupportedKeyFormats
PBEWithSHA1AndRC2_40
RC2 SupportedModes
2.16.840.1.101.3.4.1.1
PBEWithHmacSHA256AndAES_256
ARCFOUR SupportedKeyFormats
TripleDES
RSA SupportedPaddings
DESedeWrap SupportedPaddings
PBEWithHmacSHA1AndAES_128
AES_192/CBC/NoPadding
RSA SupportedKeyClasses
AESWrap SupportedKeyFormats
AES_128/ECB/NoPadding
2.16.840.1.101.3.4.1.41
AES_256/GCM/NoPadding
OID.1.2.840.113549.1.12.1.1
2.16.840.1.101.3.4.1.43
OID.1.2.840.113549.1.12.1.2
2.16.840.1.101.3.4.1.42
PBEWithHmacSHA256AndAES_128
OID.1.2.840.113549.1.12.1.3
2.16.840.1.101.3.4.1.45
DES
2.16.840.1.101.3.4.1.44
2.16.840.1.101.3.4.1.46
DESedeWrap
DESedeWrap SupportedKeyFormats
PBEWithHmacSHA384AndAES_256
Blowfish SupportedPaddings
OID.1.2.840.113549.1.12.1.5
OID.1.2.840.113549.1.12.1.6
AES_256/CFB/NoPadding
KeyAgreeents:
ECDH SupportedKeyClasses
ECDH
ECDH ImplementedIn
DH
1.2.840.113549.1.3.1
OID.1.2.840.113549.1.3.1
DiffieHellman SupportedKeyClasses
DiffieHellman
Macs:
SslMacMD5 SupportedKeyFormats
SslMacSHA1
PBEWithHmacSHA384 SupportedKeyFormats
OID.1.2.840.113549.2.10
PBEWithHmacSHA256 SupportedKeyFormats
HmacSHA512
1.2.840.113549.2.11
HmacPBESHA1
HmacSHA512 SupportedKeyFormats
OID.1.2.840.113549.2.11
HmacSHA224 SupportedKeyFormats
HmacMD5
HmacSHA256
1.2.840.113549.2.10
PBEWithHmacSHA384
HmacSHA1
SslMacSHA1 SupportedKeyFormats
PBEWithHmacSHA224
1.2.840.113549.2.8
HmacSHA256 SupportedKeyFormats
1.2.840.113549.2.9
PBEWithHmacSHA224 SupportedKeyFormats
PBEWithHmacSHA512 SupportedKeyFormats
OID.1.2.840.113549.2.9
PBEWithHmacSHA1
OID.1.2.840.113549.2.8
OID.1.2.840.113549.2.7
1.2.840.113549.2.7
HmacPBESHA1 SupportedKeyFormats
PBEWithHmacSHA256
HmacSHA1 SupportedKeyFormats
HmacSHA224
HmacSHA384
HmacMD5 SupportedKeyFormats
SslMacMD5
PBEWithHmacSHA1 SupportedKeyFormatS
HmacSHA384 SupportedKeyFormats
PBEWithHmacSHA512
MessageDigests:
SHA-1
SHA1
SHA-384
MD5 ImplementedIn
OID.1.3.14.3.2.26
2.16.840.1.101.3.4.2.2
SHA
2.16.840.1.101.3.4.2.1
2.16.840.1.101.3.4.2.4
2.16.840.1.101.3.4.2.3
OID.2.16.840.1.101.3.4.2.4
OID.2.16.840.1.101.3.4.2.3
OID.2.16.840.1.101.3.4.2.2
1.3.14.3.2.26
OID.2.16.840.1.101.3.4.2.1
SHA-224
SHA-256
MD2
SHA ImplementedIn
SHA-512
MD5
Signatures:
SHAwithDSA
NONEwithECDSA SupportedKeyClasses
SHA1withDSA KeySize
SHA224withRSA
OID.1.2.840.10045.4.1
SHA256withDSA SupportedKeyClasses
OID.2.16.840.1.101.3.4.3.2
OID.2.16.840.1.101.3.4.3.1
SHA1withDSA ImplementedIn
SHA1withDSA SupportedKeyClasses
OID.1.2.840.10045.4.3.4
DSA
OID.1.2.840.10045.4.3.2
OID.1.2.840.10045.4.3.3
SHA384withECDSA ImplementedIn
OID.1.2.840.10045.4.3.1
MD5andSHA1withRSA
OID.1.2.840.113549.1.1.4
SHA1withECDSA ImplementedIn
OID.1.2.840.113549.1.1.5
OID.1.2.840.113549.1.1.2
SHA1withECDSA SupportedKeyClasses
SHA224withDSA
SHA256withRSA SupportedKeyClasses
SHA/DSA
SHA224withECDSA ImplementedIn
DSS
NONEwithDSA KeySize
SHA256withECDSA SupportedKeyClasses
1.2.840.10045.4.3.4
SHA512withECDSA ImplementedIn
NONEwithECDSA ImplementedIn
DSAWithSHA1
SHA384withECDSA
2.16.840.1.101.3.4.3.1
1.2.840.113549.1.1.13
SHA256withDSA
2.16.840.1.101.3.4.3.2
1.2.840.113549.1.1.14
1.2.840.113549.1.1.11
1.2.840.10040.4.3
1.3.14.3.2.13
1.2.840.113549.1.1.12
SHA224withECDSA
1.2.840.10045.4.3.1
1.2.840.10045.4.3.2
NONEwithDSA SupportedKeyClasses
1.2.840.10045.4.3.3
SHA256withRSA
SHA224withDSA KeySize
MD2withRSA
SHA224withECDSA SupportedKeyClasses
SHA-1/DSA
SHA512withRSA
OID.1.2.840.113549.1.1.13
OID.1.2.840.113549.1.1.14
OID.1.2.840.113549.1.1.11
OID.1.2.840.10040.4.3
OID.1.2.840.113549.1.1.12
SHA512withRSA SupportedKeyClasses
SHA384withRSA
SHA384withRSA SupportedKeyClasses
SHA1withDSA
1.3.14.3.2.29
SHA384withECDSA SupportedKeyClasses
OID.1.3.14.3.2.29
SHA512withECDSA SupportedKeyClasses
1.3.14.3.2.27
SHA1withRSA
SHA256withDSA KeySize
SHA1withECDSA
SHA224withDSA SupportedKeyClasses
SHA1/DSA
SHA224withRSA SupportedKeyClasses
MD5withRSA SupportedKeyClasses
SHA1withRSA SupportedKeyClasses
NONEwithECDSA
RawDSA
1.2.840.10045.4.1
SHA256withECDSA ImplementedIn
MD5withRSA
SHA256withECDSA
SHA512withECDSA
1.2.840.113549.1.1.2
SHA1withECDSA KeySize
1.2.840.113549.1.1.5
1.2.840.113549.1.1.4
MD2withRSA SupportedKeyClasses
NONEwithDSA

 

sumber: http://www.java2s.com/Code/Java/Security/Listtheavailablealgorithmnamesforcipherskeyagreementmacsmessagedigestsandsignatures.htm

Ron Code 5 RC5 [java]


berdasarkan link berikut https://community.oracle.com/thread/2606350?start=0&tstart=0 kita dapat memanfaatkan script java untuk kriptografi block RC5 sebagai berikut:

script berikut memiliki panjang ukuran block 64 bit, round sebanyak 12 kali dan panjang kunci 128 bit

package roncode5;

/*************************RC5 2 bytes Encryption Decryption**********************************/  
 
class Main_RC5{  
  public static final int w = 32;  //ukuran blok = 64
  public static final int r = 12;  //jumlah putaran
  public static final int b = 16;  //panjang kunci external 16 bytes = 128 bit
  public static final int c = 4;  
  public static final int t = 26;  
  
  public int[] S = new int[t]; // expanded key table  
  public int P = (int)0xb7e15163; // magic constants  
  public int Q = (int)0x9e3779b9;  
  
  void RC5_ENCRYPT(int[] pt, int[] ct){ // 2 WORD input pt/output ct  
  int i;  
  int A = pt[0] + S[0];  
  int B = pt[1] + S[1];  
  for (i = 1; i <= r; i++){  
  A = (((A ^ B) << (B & (w - 1))) | ((A ^ B)>>>(w - (B & (w - 1))))) + S[2 * i];  
  B = (((B ^ A) << (A & (w - 1))) | ((B ^ A)>>>(w - (A & (w - 1))))) + S[2 * i + 1];  
  }  
  ct[0] = A;  
  ct[1] = B;  
  }  
  
  
  void RC5_DECRYPT(int[] ct, int[] pt){ // 2 WORD input ct/output pt  
  int i;  
  int B = ct[1];  
  int A = ct[0];  
  for (i = r; i > 0; i--){  
  B = (((B - S[2 * i + 1])>>>(A & (w - 1))) | ((B - S[2 * i + 1]) << (w - (A & (w - 1))))) ^ A;  
  A = (((A - S[2 * i])>>>(B & (w - 1))) | ((A - S[2 * i]) << (w - (B & (w - 1))))) ^ B;  
  }  
  pt[1] = B - S[1];  
  pt[0] = A - S[0];  
  }  
  
  
  void RC5_SETUP(byte[] K){ // secret input key K[0...b-1]  
  int i;  
  int j;  
  int k;  
  int u = w / 8;  
  int A;  
  int B;  
  int[] L = new int[c];  
  /* Initialize L, then S, then mix key into S */  
  for (i = b - 1,L[c - 1] = 0; i != -1; i--){  
  L[i / u] = (L[i / u] << 8) + K[i];  
  }  
  for (S[0] = P,i = 1; i < t; i++) {  
  S[i] = S[i - 1] + Q;  
  }  
  for (A = B = i = j = k = 0; k < 3 * t; k++,i = (i + 1) % t,j = (j + 1) % c) {// 3*t > 3*c  
  A = S[i] = (((S[i] + (A + B)) << (3 & (w - 1))) | ((S[i] + (A + B))>>>(w - (3 & (w - 1)))));  
  B = L[j] = (((L[j] + (A + B)) << ((A + B) & (w - 1))) | ((L[j] + (A + B))>>>(w - ((A + B) & (w - 1)))));  
  }  
  }  
  
  public static String hex(int n) {  
     // call toUpperCase() if that's required  
     //return String.format("0x%8s", Integer.toHexString(n)).replace(' ', '0');  
   return String.format("0x%s", Integer.toHexString(n)).replace(' ', '0');  
  }  
  
  
  public static void main(String[] args){  
  int i;  
  int j;  
  int[] pt1 = new int[2];  
  int[] pt2 = new int[2];  
  int[] ct = {9,7};  
  byte[] key = new byte[b];  
  
  //time_t t0, t1;  
  Main_RC5 h=new  Main_RC5();  
  
  System.out.print("RC5-32/12/16 examples:\n");  
  for (i = 1;i < 6;i++){ // Initialize pt1 and key pseudorandomly based on previous ct  
   pt1[0] = ct[0];  
   pt1[1] = ct[1];  
  
  
   for (j = 0;j < b;j++){  
   key[j] = (byte) (ct[0] % (255 - j));  
   }  
   /* Setup, encrypt, and decrypt */  
   h.RC5_SETUP(key);  
   h.RC5_ENCRYPT(pt1, ct);  
   h.RC5_DECRYPT(ct, pt2);  
  
  
   /* Print out results, checking for decryption failure */  
   System.out.printf("\n%d. key = ",i);  
   for (j = 0; j < b; j++){  
   System.out.print((key[j])+" ");  
   }  
   System.out.println("\n   Plaintext:"  + pt1[0]  + pt1[1] +   " --->" +  "ciphertext:" + ct[0]+ct[1]);  
   System.out.println("   Decypted:"  + pt2[0]  + pt2[1] );  
  
  
   if (pt1[0] != pt2[0] || pt1[1] != pt2[1]){  
   System.out.print("Decryption Error!");  
   }  
  }  
  }  
}  


Data Encryption Standart [ Java]


Data Encryption Standart adalah algortima kriptografi block yang mempunyai panjang blok 64 bit dan kunci 56 bit. Walaupun sudah usang algoritma ini menjadi awal yang sangat baik untuk memelajari kriptografi khususnya dalam kriptografi digital. Dipostingan saya sebelumnya saya sudah mengupload implementasi DES menggunakan matlab, namun file tersebut sudah dihapus di mathworks. Kali ini saya akan mencoba membagi Implementasi DES menggunakan Java, code ini ditulis oleh David Simmons berikut link nya http://cafbit.com/resource/DES.java, namun tidak ditulis class untuk dekripsi, berikut sudah ditambahkan kelas dekripsi, namun beberapa kelas saya telah hapus dikarenakan kebutuhan saya, berikut scriptnya:

package DataEncryptionStandart;

public class DESenchancment {

	private static final byte[] IP = {
        58, 50, 42, 34, 26, 18, 10, 2,
        60, 52, 44, 36, 28, 20, 12, 4,
        62, 54, 46, 38, 30, 22, 14, 6,
        64, 56, 48, 40, 32, 24, 16, 8,
        57, 49, 41, 33, 25, 17, 9,  1,
        59, 51, 43, 35, 27, 19, 11, 3,
        61, 53, 45, 37, 29, 21, 13, 5,
        63, 55, 47, 39, 31, 23, 15, 7
    };

	private static final byte[] FP = {
        40, 8, 48, 16, 56, 24, 64, 32,
        39, 7, 47, 15, 55, 23, 63, 31,
        38, 6, 46, 14, 54, 22, 62, 30,
        37, 5, 45, 13, 53, 21, 61, 29,
        36, 4, 44, 12, 52, 20, 60, 28,
        35, 3, 43, 11, 51, 19, 59, 27,
        34, 2, 42, 10, 50, 18, 58, 26,
        33, 1, 41, 9, 49, 17, 57, 25
    };

	 private static final byte[] E = {
	        32, 1,  2,  3,  4,  5,
	        4,  5,  6,  7,  8,  9,
	        8,  9,  10, 11, 12, 13,
	        12, 13, 14, 15, 16, 17,
	        16, 17, 18, 19, 20, 21,
	        20, 21, 22, 23, 24, 25,
	        24, 25, 26, 27, 28, 29,
	        28, 29, 30, 31, 32, 1
	    };

	 private static final byte[][] S = { {
	        14, 4,  13, 1,  2,  15, 11, 8,  3,  10, 6,  12, 5,  9,  0,  7,
	        0,  15, 7,  4,  14, 2,  13, 1,  10, 6,  12, 11, 9,  5,  3,  8,
	        4,  1,  14, 8,  13, 6,  2,  11, 15, 12, 9,  7,  3,  10, 5,  0,
	        15, 12, 8,  2,  4,  9,  1,  7,  5,  11, 3,  14, 10, 0,  6,  13
	    }, {
	        15, 1,  8,  14, 6,  11, 3,  4,  9,  7,  2,  13, 12, 0,  5,  10,
	        3,  13, 4,  7,  15, 2,  8,  14, 12, 0,  1,  10, 6,  9,  11, 5,
	        0,  14, 7,  11, 10, 4,  13, 1,  5,  8,  12, 6,  9,  3,  2,  15,
	        13, 8,  10, 1,  3,  15, 4,  2,  11, 6,  7,  12, 0,  5,  14, 9
	    }, {
	        10, 0,  9,  14, 6,  3,  15, 5,  1,  13, 12, 7,  11, 4,  2,  8,
	        13, 7,  0,  9,  3,  4,  6,  10, 2,  8,  5,  14, 12, 11, 15, 1,
	        13, 6,  4,  9,  8,  15, 3,  0,  11, 1,  2,  12, 5,  10, 14, 7,
	        1,  10, 13, 0,  6,  9,  8,  7,  4,  15, 14, 3,  11, 5,  2,  12
	    }, {
	        7,  13, 14, 3,  0,  6,  9,  10, 1,  2,  8,  5,  11, 12, 4,  15,
	        13, 8,  11, 5,  6,  15, 0,  3,  4,  7,  2,  12, 1,  10, 14, 9,
	        10, 6,  9,  0,  12, 11, 7,  13, 15, 1,  3,  14, 5,  2,  8,  4,
	        3,  15, 0,  6,  10, 1,  13, 8,  9,  4,  5,  11, 12, 7,  2,  14
	    }, {
	        2,  12, 4,  1,  7,  10, 11, 6,  8,  5,  3,  15, 13, 0,  14, 9,
	        14, 11, 2,  12, 4,  7,  13, 1,  5,  0,  15, 10, 3,  9,  8,  6,
	        4,  2,  1,  11, 10, 13, 7,  8,  15, 9,  12, 5,  6,  3,  0,  14,
	        11, 8,  12, 7,  1,  14, 2,  13, 6,  15, 0,  9,  10, 4,  5,  3
	    }, {
	        12, 1,  10, 15, 9,  2,  6,  8,  0,  13, 3,  4,  14, 7,  5,  11,
	        10, 15, 4,  2,  7,  12, 9,  5,  6,  1,  13, 14, 0,  11, 3,  8,
	        9,  14, 15, 5,  2,  8,  12, 3,  7,  0,  4,  10, 1,  13, 11, 6,
	        4,  3,  2,  12, 9,  5,  15, 10, 11, 14, 1,  7,  6,  0,  8,  13
	    }, {
	        4,  11, 2,  14, 15, 0,  8,  13, 3,  12, 9,  7,  5,  10, 6,  1,
	        13, 0,  11, 7,  4,  9,  1,  10, 14, 3,  5,  12, 2,  15, 8,  6,
	        1,  4,  11, 13, 12, 3,  7,  14, 10, 15, 6,  8,  0,  5,  9,  2,
	        6,  11, 13, 8,  1,  4,  10, 7,  9,  5,  0,  15, 14, 2,  3,  12
	    }, {
	        13, 2,  8,  4,  6,  15, 11, 1,  10, 9,  3,  14, 5,  0,  12, 7,
	        1,  15, 13, 8,  10, 3,  7,  4,  12, 5,  6,  11, 0,  14, 9,  2,
	        7,  11, 4,  1,  9,  12, 14, 2,  0,  6,  10, 13, 15, 3,  5,  8,
	        2,  1,  14, 7,  4,  10, 8,  13, 15, 12, 9,  0,  3,  5,  6,  11
	    } };

	 private static final byte[] P = {
	        16, 7,  20, 21,
	        29, 12, 28, 17,
	        1,  15, 23, 26,
	        5,  18, 31, 10,
	        2,  8,  24, 14,
	        32, 27, 3,  9,
	        19, 13, 30, 6,
	        22, 11, 4,  25
	    };

	 private static final byte[] PC1 = {
	        57, 49, 41, 33, 25, 17, 9,
	        1,  58, 50, 42, 34, 26, 18,
	        10, 2,  59, 51, 43, 35, 27,
	        19, 11, 3,  60, 52, 44, 36,
	        63, 55, 47, 39, 31, 23, 15,
	        7,  62, 54, 46, 38, 30, 22,
	        14, 6,  61, 53, 45, 37, 29,
	        21, 13, 5,  28, 20, 12, 4
	    };

	    private static final byte[] PC2 = {
	        14, 17, 11, 24, 1,  5,
	        3,  28, 15, 6,  21, 10,
	        23, 19, 12, 4,  26, 8,
	        16, 7,  27, 20, 13, 2,
	        41, 52, 31, 37, 47, 55,
	        30, 40, 51, 45, 33, 48,
	        44, 49, 39, 56, 34, 53,
	        46, 42, 50, 36, 29, 32
	    };

	    private static final byte[] rotations = {
	        1, 1, 2, 2, 2, 2, 2, 2, 1, 2, 2, 2, 2, 2, 2, 1
	    };

	    private static long IP(long src)  { return permute(IP, 64, src);                 } // 64-bit output
	    private static long FP(long src)  { return permute(FP, 64, src);                 } // 64-bit output
	    private static long E(int src)    { return permute(E, 32, src&amp;0xFFFFFFFFL);      } // 48-bit output
	    private static int  P(int src)    { return (int)permute(P, 32, src&amp;0xFFFFFFFFL); } // 32-bit output
	    private static long PC1(long src) { return permute(PC1, 64, src);                } // 56-bit output
	    private static long PC2(long src) { return permute(PC2, 56, src);                } // 48-bit output

	    private static long permute(byte[] table, int srcWidth, long src) {
	        long dst = 0;
	        for (int i=0; i&lt;table.length; i++) {
	            int srcPos = srcWidth - table[i];
	            dst = (dst&lt;&lt;1) | (src&gt;&gt;srcPos &amp; 0x01);
	        }
	        return dst;
	    }

	    private static byte S(int boxNumber, byte src) {
	        // The first and last bits determine which 16-value row to
	        // reference, so we transform the 6-bit input into an
	        // absolute index based on the following bit shuffle:
	        // abcdef =&gt; afbcde
	        src = (byte) (src&amp;0x20 | ((src&amp;0x01)&lt;&lt;4) | ((src&amp;0x1E)&gt;&gt;1));
	        return S[boxNumber-1][src];
	    }

	    private static long getLongFromBytes(byte[] ba, int offset) {
	        long l = 0;
	        for (int i=0; i&lt;8; i++) {
	            byte value;
	            if ((offset+i) &lt; ba.length) {
	                value = ba[offset+i];
	            } else {
	                value = 0;
	            }
	            l = l&lt;&lt;8 | (value &amp; 0xFFL);
	        }
	        return l;
	    }

	    private static void getBytesFromLong(byte[] ba, int offset, long l) {
	        for (int i=7; i&gt;=0; i--) {
	            if ((offset+i) &lt; ba.length) {
	                ba[offset+i] = (byte) (l &amp; 0xFF);
	                l = l &gt;&gt; 8;
	            } else {
	                break;
	            }
	        }
	    }

	    private static int feistel(int r, /* 48 bits */ long subkey) {
	        // 1. expansion
	        long e = E(r);
	        // 2. key mixing
	        long x = e ^ subkey;
	        // 3. substitution
	        int dst = 0;
	        for (int i=0; i&lt;8; i++) {
	            dst&gt;&gt;&gt;=4;
	            int s = S(8-i, (byte)(x&amp;0x3F));
	            dst |= s &lt;&lt; 28;
	            x&gt;&gt;=6;
	        }
	        // 4. permutation
	        return P(dst);
	    }

	    /**
	     * Generate 16 48-bit subkeys based on the provided 64-bit key
	     * value.
	     */
	    private static long[] createSubkeys(/* 64 bits */ long key) {
	        long subkeys[] = new long[16];

	        // perform the PC1 permutation
	        key = PC1(key);

	        // split into 28-bit left and right (c and d) pairs.
	        int c = (int) (key&gt;&gt;28);
	        int d = (int) (key&amp;0x0FFFFFFF);

	        // for each of the 16 needed subkeys, perform a bit
	        // rotation on each 28-bit keystuff half, then join
	        // the halves together and permute to generate the
	        // subkey.
	        for (int i=0; i&lt;16; i++) {
	            // rotate the 28-bit values
	            if (rotations[i] == 1) {
	                // rotate by 1 bit
	                c = ((c&lt;&lt;1) &amp; 0x0FFFFFFF) | (c&gt;&gt;27);
	                d = ((d&lt;&lt;1) &amp; 0x0FFFFFFF) | (d&gt;&gt;27);
	            } else {
	                // rotate by 2 bits
	                c = ((c&lt;&lt;2) &amp; 0x0FFFFFFF) | (c&gt;&gt;26);
	                d = ((d&lt;&lt;2) &amp; 0x0FFFFFFF) | (d&gt;&gt;26);
	            }

	            // join the two keystuff halves together.
	            long cd = (c&amp;0xFFFFFFFFL)&lt;&lt;28 | (d&amp;0xFFFFFFFFL);

	            // perform the PC2 permutation
	            subkeys[i] = PC2(cd);
	        }

	        return subkeys; /* 48-bit values */
	    }

	    private static long encryptBlock(long m, /* 64 bits */ long key) {
	        // generate the 16 subkeys
	        long subkeys[] = createSubkeys(key);

	        // perform the initial permutation
	        long ip = IP(m);

	        // split the 32-bit value into 16-bit left and right halves.
	        int l = (int) (ip&gt;&gt;32);
	        int r = (int) (ip&amp;0xFFFFFFFFL);

	        // perform 16 rounds
	        for (int i=0; i&lt;16; i++) {
	            int previous_l = l;
	            // the right half becomes the new left half.
	            l = r;
	            // the Feistel function is applied to the old left half
	            // and the resulting value is stored in the right half.
	            r = previous_l ^ feistel(r, subkeys[i]);
	        }

	        // reverse the two 32-bit segments (left to right; right to left)
	        long rl = (r&amp;0xFFFFFFFFL)&lt;&lt;32 | (l&amp;0xFFFFFFFFL);

	        // apply the final permutation
	        long fp = FP(rl);

	        // return the ciphertext
	        return fp;
	    }

	    private static void encryptBlock(
	            byte[] message,
	            int messageOffset,
	            byte[] ciphertext,
	            int ciphertextOffset,
	            byte[] key
	        ) {
	            long m = getLongFromBytes(message, messageOffset);
	            long k = getLongFromBytes(key, 0);
	            long c = encryptBlock(m, k);
	            getBytesFromLong(ciphertext, ciphertextOffset, c);
	        }

	    private static byte[] encrypt(byte[] message, byte[] key) {
	        byte[] ciphertext = new byte[message.length];

	        // encrypt each 8-byte (64-bit) block of the message.
	        for (int i=0; i&lt;message.length; i+=8) {
	            encryptBlock(message, i, ciphertext, i, key);
	        }

	        return ciphertext;
	    }

	    private static long decryptBlock(long m, /* 64 bits */ long key) {
	        // generate the 16 subkeys
	        long subkeys[] = createSubkeys(key);

	        // perform the initial permutation
	        long ip = IP(m);

	        // split the 32-bit value into 16-bit left and right halves.
	        int l = (int) (ip&gt;&gt;32);
	        int r = (int) (ip&amp;0xFFFFFFFFL);

	        // perform 16 rounds
	        for (int i=0; i&lt;16; i++) {
	            int previous_l = l;
	            // the right half becomes the new left half.
	            l = r;
	            // the Feistel function is applied to the old left half
	            // and the resulting value is stored in the right half.
	            r = previous_l ^ feistel(r, subkeys[15-i]);
	        }

	        // reverse the two 32-bit segments (left to right; right to left)
	        long rl = (r&amp;0xFFFFFFFFL)&lt;&lt;32 | (l&amp;0xFFFFFFFFL);

	        // apply the final permutation
	        long fp = FP(rl);

	        // return the ciphertext
	        return fp;
	    }

	    private static void decryptBlock(
	            byte[] message,
	            int messageOffset,
	            byte[] plaintext,
	            int plaintextOffset,
	            byte[] key
	        ) {
	            long m = getLongFromBytes(message, messageOffset);
	            long k = getLongFromBytes(key, 0);
	            long c = decryptBlock(m, k);
	            getBytesFromLong(plaintext, plaintextOffset, c);
	        }

	    private static byte[] decrypt(byte[] message, byte[] key) {
	        byte[] plaintext = new byte[message.length];

	        // encrypt each 8-byte (64-bit) block of the message.
	        for (int i=0; i&lt;message.length; i+=8) {
	            decryptBlock(message, i, plaintext, i, key);
	        }

	        return plaintext;
	    }

	 public static int[] encrypt_bit( int input [], int [] key) {
		 byte [] keybyte = ArraytoByte(key,8);
		 byte [] inputbyte = ArraytoByte(input,8);
		 byte [] ciphertext = encrypt(inputbyte, keybyte);

		 int [] ciphertextbyte = new int [8];
		 int [] ciphertextabit = new int [64];
		 int kk=0;
			for (int i = 0; i &lt; 8 ; i++){
				ciphertextbyte [i] = (int) ciphertext[i] &amp; 0xFF;
				Convert_to8bit ConverterB = new Convert_to8bit (ciphertextbyte [i]);
				int[] buufB = ConverterB.outputbit();

				for (int j = 0; j &lt; 8 ; j++){
					ciphertextabit [kk]= buufB [j];
					kk=kk+1;
				}
			}
			return ciphertextabit;
	 }

	 public static int[] decrypt_bit( int input [], int [] key) {
		 byte [] keybyte = ArraytoByte(key,8);
		 byte [] inputbyte = ArraytoByte(input,8);
		 byte [] plaintext = decrypt(inputbyte, keybyte);

		 int [] plaintextbyte = new int [8];
		 int [] plaintextabit = new int [64];
		 int kk=0;
			for (int i = 0; i &lt; 8 ; i++){
				plaintextbyte [i] = (int) plaintext[i] &amp; 0xFF;
				Convert_to8bit ConverterB = new Convert_to8bit (plaintextbyte [i]);
				int[] buufB = ConverterB.outputbit();

				for (int j = 0; j &lt; 8 ; j++){
					plaintextabit [kk]= buufB [j];
					kk=kk+1;
				}
			}
			return plaintextabit;
	 }

	public static void main (String[] args) {

		byte [] keybyte ={3,0,0,0,0,0,0,0};
		byte [] inputbyte={4,-127,0,127,4,0,8,0};

		byte [] ciphertext = encrypt(inputbyte, keybyte);
		byte [] plaintext = decrypt(ciphertext , keybyte);

		for (int i =0 ; i&lt;inputbyte.length ; i++){
			System.out.print(inputbyte  [i]);
			System.out.print(&quot;,&quot;);
		}
		System.out.println();
		for (int i =0 ; i&lt;ciphertext.length ; i++){
			System.out.print(ciphertext  [i]);
			System.out.print(&quot;,&quot;);
		}
		System.out.println();
		for (int i =0 ; i&lt;plaintext.length ; i++){
			System.out.print(plaintext  [i]);
			System.out.print(&quot;,&quot;);
		}

	}
}

catatan: code ini belum ditest kebenarannya namun untuk enkripsi dan dekripsi dilakukan dengan baik

Menghitung Korelasi Horizontal Vertical dan Diagonal pada Citra Digital


Korelasi pixel tetangga pada citra digital adalah suatu cara untuk menemukan hubungan nilai antara 2 pixel. Dalam hal ini kita bisa katakan hubungan antara Horizontal Vertical dan Diagonal. Salah satu artikel yang membahas hal tersebut Tang Hongmei; Han Liying; He Yu; Wang Xia, “An improved compound image encryption scheme,” in Computer and Communication Technologies in Agriculture Engineering (CCTAE), 2010 International Conference On , vol.3, no., pp.128-131, 12-13 June 2010
Di artikel tersebut di bagian C Correlation coefficient analysis disebutkan sebagai berikut

Screenshot from 2016-01-18 18:33:34
Screenshot from 2016-01-18 18:37:15

berangkat dari formula dan grafik tersebut, kita dapat menghitung nilai korelasi dan menampilkan nilai korelasi mengggunakan matlab sebagai berikut
sebagai contoh: saya mempunyai 2 images (image original dan image yang sudah terenkripsi) kita ingin mendapatkan nilai korelasi dari image original dan encrypted image (variable r dan r2) serta memplot korelasi antar tetangga tersebut, berikut scriptnya

%horizontal
clear all, close all
imrgb_o=double(imread('kodim23.png'));
imrgb_r=double(imread('Encrypt_DES_kodim23.png'));
imgray_o=sum(imrgb_o,3)/3; 
imgray_r=sum(imrgb_r,3)/3; 
[As Bs]=size(imgray_o);
x=imgray_o;
L=As*Bs;
x_r=reshape(x',1,L)';
y_r=circshift(x_r,-1);
figure4 = figure;
axes4 = axes('Parent',figure4)
hold(axes4,'all');
for i=1:L
    plot(x_r(i),y_r(i)), hold on
end
title('Horizontal Correlation Original Image')
saveas(figure4,'Horizontal Correlation Original Image.png') 
close (figure4)
x_mean=mean(x_r);
y_mean=mean(y_r);
for i=1:L
    A(i,1)=(x_r(i,1)-x_mean)*(y_r(i,1)-y_mean);
end
ConvA=sum(A)/L;
for i=1:L
    DA_x(i,1)=(x_r(i,1)-x_mean).^2;
end
for i=1:L
    DA_y(i,1)=(y_r(i,1)-y_mean).^2;
end
D_x=sum(DA_x)/L;
D_y=sum(DA_y)/L
r=ConvA/(sqrt(D_x*D_y))
%%%%%%%%%%%%%%%%%%%%%%%%%%%
x2=imgray_r;
x2_r=reshape(x2',1,L)';
y2_r=circshift(x2_r,-1);
y2_r(1,1)=0;
figure5 = figure;
axes5 = axes('Parent',figure5)
hold(axes5,'all');
for i=1:L
    plot(x2_r(i),y2_r(i)), hold on
end
title('Horizontal Correlation Encrypted Image by DES')
saveas(figure5,'Horizontal Correlation Encrypted Image by DES.png') 
close (figure5)
x2_mean=mean(x2_r);
y2_mean=mean(y2_r);
for i=1:L
    A2(i,1)=(x2_r(i,1)-x2_mean)*(y2_r(i,1)-y2_mean);
end
ConvA2=sum(A2)/L;
for i=1:L
    DA2_x(i,1)=(x2_r(i,1)-x2_mean).^2;
end
for i=1:L
    DA2_y(i,1)=(y2_r(i,1)-y2_mean).^2;
end
D_x2=sum(DA2_x)/L;
D_y2=sum(DA2_y)/L;
r2=ConvA2/(sqrt(D_x2*D_y2))
save('Konv_horzontal.mat','r','r2')

Vertical Correlation Encrypted Image by DES

Vertical Correlation Original Image

%Vertikal
clear all
imrgb_o=double(imread('kodim23.png'));
imrgb_r=double(imread('Encrypt_DES_kodim23.png'));
imgray_o=sum(imrgb_o,3)/3; 
imgray_r=sum(imrgb_r,3)/3; 
[As Bs]=size(imgray_o);
x=imgray_o;
L=As*Bs;
x_r=reshape(x',1,L)';
y_r=circshift(x_r,-Bs);
figure7 = figure;
axes7 = axes('Parent',figure7)
hold(axes7,'all');
for i=1:L
    plot(x_r(i),y_r(i)), hold on
end
title('Vertical Correlation Original Image')
saveas(figure7,'Vertical Correlation Original Image.png') 
close (figure7)
x_mean=mean(x_r);
y_mean=mean(y_r);
for i=1:L
    A(i,1)=(x_r(i,1)-x_mean)*(y_r(i,1)-y_mean);
end
ConvA=sum(A)/L;
for i=1:L
    DA_x(i,1)=(x_r(i,1)-x_mean).^2;
end
for i=1:L
    DA_y(i,1)=(y_r(i,1)-y_mean).^2;
end
D_x=sum(DA_x)/L;
D_y=sum(DA_y)/L
r=ConvA/(sqrt(D_x*D_y))
%%%%%%%%%%%%%%%%%%%%%%%%%%%
x2=imgray_r;
% x2_r=reshape(x2',1,L)';
% y2_r=circshift(x2_r,-1);
% y2_r(1,1)=0;
x2_r=reshape(x2',1,L)';
y2_r=circshift(x2_r,-Bs);
figure8 = figure;
axes8 = axes('Parent',figure8)
hold(axes8,'all');
for i=1:L
    plot(x2_r(i),y2_r(i)), hold on
end
title('Vertical Correlation Encrypted Image by DES')
saveas(figure8,'Vertical Correlation Encrypted Image by DES.png') 
close (figure8)
x2_mean=mean(x2_r);
y2_mean=mean(y2_r);
for i=1:L
    A2(i,1)=(x2_r(i,1)-x2_mean)*(y2_r(i,1)-y2_mean);
end
ConvA2=sum(A2)/L;
for i=1:L
    DA2_x(i,1)=(x2_r(i,1)-x2_mean).^2;
end
for i=1:L
    DA2_y(i,1)=(y2_r(i,1)-y2_mean).^2;
end
D_x2=sum(DA2_x)/L;
D_y2=sum(DA2_y)/L;
r2=ConvA2/(sqrt(D_x2*D_y2))
save('Konv_vertikal.mat','r','r2')

Horizontal Correlation Encrypted Image by DES

Horizontal Correlation Original Image

%diagonal
clear all
imrgb_o=double(imread('kodim23.png'));
imrgb_r=double(imread('Encrypt_DES_kodim23.png'));
imgray_o=sum(imrgb_o,3)/3; 
imgray_r=sum(imrgb_r,3)/3; 
[As Bs]=size(imgray_o);
x=imgray_o;
L=As*Bs;
x_p=[x(:,:) x(:,1)];
x_p2=[x_p(:,:) ; [x(1,:) x(1,1)] ];
for i=1:As
    for j=1:Bs
    y(i,j)=x_p2(i+1,j+1);
    end
end
x_r=reshape(x',1,L)';
y_r=reshape(y',1,L)';
figure1 = figure;
axes1 = axes('Parent',figure1)
hold(axes1,'all');
for i=1:L
    plot(x_r(i),y_r(i)), hold on
end
title('Diagonal Correlation Original Image')
saveas(figure1,'Diagonal Correlation Original Image.png') 
close (figure1)
x_mean=mean(x_r);
y_mean=mean(y_r);
for i=1:L
    A(i,1)=(x_r(i,1)-x_mean)*(y_r(i,1)-y_mean);
end
ConvA=sum(A)/L;
for i=1:L
    DA_x(i,1)=(x_r(i,1)-x_mean).^2;
end
for i=1:L
    DA_y(i,1)=(y_r(i,1)-y_mean).^2;
end
D_x=sum(DA_x)/L;
D_y=sum(DA_y)/L
r=ConvA/(sqrt(D_x*D_y))
%%%%%%%%%%%%%%%%%%%%%%%%%%%
x2=imgray_r;
x2_p=[x2(:,:) x2(:,1)]
x2_p2=[x2_p(:,:) ; [x2(1,:) x2(1,1)] ]
for i=1:As
    for j=1:Bs
    y2(i,j)=x2_p2(i+1,j+1);
    end
end
x2_r=reshape(x2',1,L)';
y2_r=reshape(y2',1,L)';
figure2 = figure;
axes2 = axes('Parent',figure2)
hold(axes2,'all');
for i=1:L
    plot(x2_r(i),y2_r(i)), hold on
end
title('Diagonal Correlation Encrypted Image by DES')
saveas(figure2,'Diagonal Correlation Encrypted Image by DES.png') 
close (figure2)
x2_mean=mean(x2_r);
y2_mean=mean(y2_r);
for i=1:L
    A2(i,1)=(x2_r(i,1)-x2_mean)*(y2_r(i,1)-y2_mean);
end
ConvA2=sum(A2)/L;
for i=1:L
    DA2_x(i,1)=(x2_r(i,1)-x2_mean).^2;
end
for i=1:L
    DA2_y(i,1)=(y2_r(i,1)-y2_mean).^2;
end
D_x2=sum(DA2_x)/L;
D_y2=sum(DA2_y)/L;
r2=ConvA2/(sqrt(D_x2*D_y2))
save('Konv_diagonal.mat','r','r2')

Diagonal Correlation Encrypted Image by DES

Diagonal Correlation Original Image

gosudarstvennyy standart 28147-8 Fast [java]


GOST gosudarstvennyy standart 28147-8 adalah algoritma kriptografi blok cipher yang dikembangkan oleh Unisovyet dan sampai sekarang masih digunakan oleh Rusia dalam standart kriptografi
GOST memiliki panjang kunci 256 bit dan panjang blok 64 bit. Selain itu Sbox juga dapat menjadi secret yang menyebabkan sulitnya crack pada brute force attack pada algoritma tersebut. berikut implementasi pada java

package GOST;
//2016
//Ridho Bustami
//Adapted from C++ by Colin Plumb,
//The Soviet GOST algorithm (without the correct S-boxes). https://www.schneier.com/sccd/GOST-PLU.ZIP

public class gost {

	private static int k8 [] ={
		14,  4, 13,  1,  2, 15, 11,  8,  3, 10,  6, 12,  5,  9,  0,  7 };
	private static int k7 [] = {
		15,  1,  8, 14,  6, 11,  3,  4,  9,  7,  2, 13, 12,  0,  5, 10 };
	private static int  k6 [] = {
		10,  0,  9, 14,  6,  3, 15,  5,  1, 13, 12,  7, 11,  4,  2,  8 };
	private static int  k5[] = {
		 7, 13, 14,  3,  0,  6,  9, 10,  1,  2,  8,  5, 11, 12,  4, 15 };
	private static int  k4[] = {
		 2, 12,  4,  1,  7, 10, 11,  6,  8,  5,  3, 15, 13,  0, 14,  9 };
	private static int k3[] = {
		12,  1, 10, 15,  9,  2,  6,  8,  0, 13,  3,  4, 14,  7,  5, 11 };
	private static int  k2[] = {
		 4, 11,  2, 14, 15,  0,  8, 13,  3, 12,  9,  7,  5, 10,  6,  1 };
	private static int  k1[] = {
		13,  2,  8,  4,  6, 15, 11,  1, 10,  9,  3, 14,  5,  0, 12,  7 };

	static int[] k87 = new int  [256];
	static int[] k65 = new int  [256];
	static int[] k43 = new int  [256];
	static int[] k21 = new int  [256];

	public static void kboxinit() {
		 for (int i = 0; i &lt; 256; i++) {
				k87[i] = (int) (k8[i &gt;&gt; 4] &lt;&lt; 4 | k7[i &amp; 15]);
				k65[i] = (int) (k6[i &gt;&gt; 4] &lt;&lt; 4 | k5[i &amp; 15]);
				k43[i] = (int) (k4[i &gt;&gt; 4] &lt;&lt; 4 | k3[i &amp; 15]);
				k21[i] = (int) (k2[i &gt;&gt; 4] &lt;&lt; 4 | k1[i &amp; 15]);
			}
	 }

	 private static int f(int x){
		 x = (int) (k87[(int) (x&gt;&gt;24 &amp; 255)] &lt;&lt; 24 | k65[(int) (x&gt;&gt;16 &amp; 255)] &lt;&lt; 16 |
				    k43[(int) (x&gt;&gt; 8 &amp; 255)] &lt;&lt;  8 | k21[(int) (x &amp; 255)]);
		 return (int) (x&lt;&lt;11 | x&gt;&gt;(32-11));
	 }

	 public static void encrypt(int[] in, int[] out, int[] key) {
		 	int n1 = in[0];
		 	int n2 = in[1];
			n2 ^= f((int) (n1+key[0]));
			n1 ^= f((int) (n2+key[1]));
			n2 ^= f((int) (n1+key[2]));
			n1 ^= f((int) (n2+key[3]));
			n2 ^= f((int) (n1+key[4]));
			n1 ^= f((int) (n2+key[5]));
			n2 ^= f((int) (n1+key[6]));
			n1 ^= f((int) (n2+key[7]));

			n2 ^= f((int) (n1+key[0]));
			n1 ^= f((int) (n2+key[1]));
			n2 ^= f((int) (n1+key[2]));
			n1 ^= f((int) (n2+key[3]));
			n2 ^= f((int) (n1+key[4]));
			n1 ^= f((int) (n2+key[5]));
			n2 ^= f((int) (n1+key[6]));
			n1 ^= f((int) (n2+key[7]));

			n2 ^= f((int) (n1+key[0]));
			n1 ^= f((int) (n2+key[1]));
			n2 ^= f((int) (n1+key[2]));
			n1 ^= f((int) (n2+key[3]));
			n2 ^= f((int) (n1+key[4]));
			n1 ^= f((int) (n2+key[5]));
			n2 ^= f((int) (n1+key[6]));
			n1 ^= f((int) (n2+key[7]));

			n2 ^= f((int) (n1+key[7]));
			n1 ^= f((int) (n2+key[6]));
			n2 ^= f((int) (n1+key[5]));
			n1 ^= f((int) (n2+key[4]));
			n2 ^= f((int) (n1+key[3]));
			n1 ^= f((int) (n2+key[2]));
			n2 ^= f((int) (n1+key[1]));
			n1 ^= f((int) (n2+key[0]));

			/* There is no swap after the last round */
			out[0] = n2;
			out[1] = n1;

	 }

	 public static void decrypt(int[] in, int[] out, int[] key) {
			int n1 = in[0];
			int n2 = in[1];

			n2 ^= f((int) (n1+key[0]));
			n1 ^= f((int) (n2+key[1]));
			n2 ^= f((int) (n1+key[2]));
			n1 ^= f((int) (n2+key[3]));
			n2 ^= f((int) (n1+key[4]));
			n1 ^= f((int) (n2+key[5]));
			n2 ^= f((int) (n1+key[6]));
			n1 ^= f((int) (n2+key[7]));

			n2 ^= f((int) (n1+key[7]));
			n1 ^= f((int) (n2+key[6]));
			n2 ^= f((int) (n1+key[5]));
			n1 ^= f((int) (n2+key[4]));
			n2 ^= f((int) (n1+key[3]));
			n1 ^= f((int) (n2+key[2]));
			n2 ^= f((int) (n1+key[1]));
			n1 ^= f((int) (n2+key[0]));

			n2 ^= f((int) (n1+key[7]));
			n1 ^= f((int) (n2+key[6]));
			n2 ^= f((int) (n1+key[5]));
			n1 ^= f((int) (n2+key[4]));
			n2 ^= f((int) (n1+key[3]));
			n1 ^= f((int) (n2+key[2]));
			n2 ^= f((int) (n1+key[1]));
			n1 ^= f((int) (n2+key[0]));

			n2 ^= f((int) (n1+key[7]));
			n1 ^= f((int) (n2+key[6]));
			n2 ^= f((int) (n1+key[5]));
			n1 ^= f((int) (n2+key[4]));
			n2 ^= f((int) (n1+key[3]));
			n1 ^= f((int) (n2+key[2]));
			n2 ^= f((int) (n1+key[1]));
			n1 ^= f((int) (n2+key[0]));

			out[0] = n2;
			out[1] = n1;

	 }

	   public static void main (String[] args) {
		 //test
		 int [] key = {1,2, 3, 7, 5, 200, 7, 8};
		 int[] plain = {-200,89};
		 int[] cipher= {0,0};
		 int[] plain2 = {0,0};

		 kboxinit();
		 encrypt(plain, cipher, key);
		 decrypt(cipher, plain2, key);

		 System.out.print(plain[0]);
		 System.out.print(&quot;,&quot;);
		 System.out.print(plain[1]);
		 System.out.println();
		 System.out.print(plain2[0]);
		 System.out.print(&quot;,&quot;);
		 System.out.print(plain2[1]);

	 }
}

Install OpenCV raspberry pi


#step 1
update&upgrade , Update firmwire
$ sudo apt-get update
$ sudo apt-get upgrade
$ sudo rpi-update

reboot
$ sudo reboot

install beberapa developer tools
$ sudo apt-get install build-essential git cmake pkg-config

install image I/O packages
$ sudo apt-get install libjpeg-dev libtiff5-dev libjasper-dev libpng12-dev

install video I/O packages
$ sudo apt-get install libavcodec-dev libavformat-dev libswscale-dev libv4l-dev
$ sudo apt-get install libxvidcore-dev libx264-dev

install GTK development library yang merupakan sub-module dari OpenCV yang dapat menampilkan images kedalam layar kita dan membuat GUI yang sederhana
$ sudo apt-get install libgtk2.0-dev

install beberapa dependecies
$ sudo apt-get install libatlas-base-dev gfortran

install Python 2.7 dan Python 3 header file sehingga dapat mengkompile openCV + python
$ sudo apt-get install python2.7-dev python3-dev

#step 2
$ cd ~
$ wget -O opencv.zip https://github.com/Itseez/opencv/archive/3.0.0.zip
$ unzip opencv.zip

$ wget -O opencv_contrib.zip https://github.com/Itseez/opencv_contrib/archive/3.0.0.zip
$ unzip opencv_contrib.zip

#sampai sini dulu

#step 3
$ wget https://bootstrap.pypa.io/get-pip.py
$ sudo python get-pip.py

 

install numpy, cukup memakan waktu sekitar 15 menit, harap bersabar
$ pip install numpy

$ cd ~/opencv-3.0.0/
jika anda ingin menginstall di usb atau drive lain anda dapat mengubah direktory seperti yang saya lakukan dikarenakan keterbatasan sdcard yang saya punya sebagai berikut, namun sebelumnya pastikan usb sudah termount

$ cd /media/usb/opencv-3.0.0/

$ cd build
$ cmake -D CMAKE_BUILD_TYPE=RELEASE \
-D CMAKE_INSTALL_PREFIX=/usr/local \
-D INSTALL_C_EXAMPLES=ON \
-D INSTALL_PYTHON_EXAMPLES=ON \
-D OPENCV_EXTRA_MODULES_PATH=~/opencv_contrib-3.0.0/modules \
-D BUILD_EXAMPLES=ON \
-D BUILD_SHARED_LIBS=OFF ..

-D BUILD_SHARED_LIBS=OFF .. ditambahkan untuk membuat OpenCV dapat berjalan di java, jika java missing library dapat di install
sudo apt-get install openjdk-7-jdk
dan
sudo apt-get install ant

setelah itu
export JAVA_HOME=/usr/lib/jvm/jdk-8-oracle-arm-vfp-hflt

setelah itu jalan kan cmake kembali, pastikan configurasi cmake seperti yang anda inginkan, sebagai contoh berikut

— Detected version of GNU GCC: 49 (409)
— Found ZLIB: /usr/lib/arm-linux-gnueabihf/libz.so (found suitable version “1.2.8”, minimum required is “1.2.3”)
— Found ZLIB: /usr/lib/arm-linux-gnueabihf/libz.so (found version “1.2.8”)
— checking for module ‘gtk+-3.0’
— package ‘gtk+-3.0’ not found
— checking for module ‘gtk+-2.0’
— package ‘gtk+-2.0’ not found
— checking for module ‘gthread-2.0’
— package ‘gthread-2.0’ not found
— checking for module ‘gstreamer-base-1.0’
— package ‘gstreamer-base-1.0’ not found
— checking for module ‘gstreamer-video-1.0’
— package ‘gstreamer-video-1.0’ not found
— checking for module ‘gstreamer-app-1.0’
— package ‘gstreamer-app-1.0’ not found
— checking for module ‘gstreamer-riff-1.0’
— package ‘gstreamer-riff-1.0’ not found
— checking for module ‘gstreamer-pbutils-1.0’
— package ‘gstreamer-pbutils-1.0’ not found
— checking for module ‘gstreamer-base-0.10’
— package ‘gstreamer-base-0.10’ not found
— checking for module ‘gstreamer-video-0.10’
— package ‘gstreamer-video-0.10’ not found
— checking for module ‘gstreamer-app-0.10’
— package ‘gstreamer-app-0.10’ not found
— checking for module ‘gstreamer-riff-0.10’
— package ‘gstreamer-riff-0.10’ not found
— checking for module ‘gstreamer-pbutils-0.10’
— package ‘gstreamer-pbutils-0.10’ not found
— checking for module ‘libdc1394-2’
— package ‘libdc1394-2’ not found
— checking for module ‘libdc1394’
— package ‘libdc1394’ not found
— Looking for linux/videodev.h
— Looking for linux/videodev.h – not found
— Looking for linux/videodev2.h
— Looking for linux/videodev2.h – found
— Looking for sys/videoio.h
— Looking for sys/videoio.h – not found
— Looking for libavformat/avformat.h
— Looking for libavformat/avformat.h – found
— Looking for ffmpeg/avformat.h
— Looking for ffmpeg/avformat.h – not found
— checking for module ‘libgphoto2’
— package ‘libgphoto2’ not found
— Could NOT find Doxygen (missing: DOXYGEN_EXECUTABLE)
— To enable PlantUML support, set PLANTUML_JAR environment variable or pass -DPLANTUML_JAR= option to cmake
— Found PythonInterp: /usr/bin/python2.7 (found suitable version “2.7.9”, minimum required is “2.7”)
— Found PythonLibs: /usr/lib/arm-linux-gnueabihf/libpython2.7.so (found suitable exact version “2.7.9”)
— Found PythonInterp: /usr/bin/python3.4 (found suitable version “3.4.2”, minimum required is “3.4”)
— Found PythonLibs: /usr/lib/arm-linux-gnueabihf/libpython3.4m.so (found suitable exact version “3.4.2”)
— Found apache ant 1.9.4: /usr/bin/ant
— Could NOT find Matlab (missing: MATLAB_MEX_SCRIPT MATLAB_INCLUDE_DIRS MATLAB_ROOT_DIR MATLAB_LIBRARIES MATLAB_LIBRARY_DIRS MATLAB_MEXEXT MATLAB_ARCH MATLAB_BIN)
— VTK is not found. Please set -DVTK_DIR in CMake to VTK build directory, or to VTK install subdirectory with VTKConfig.cmake file
— videoio: Removing WinRT API headers by default

— General configuration for OpenCV 3.0.0 =====================================
— Version control: unknown

— Platform:
— Host: Linux 4.1.15-v7+ armv7l
— CMake: 3.0.2
— CMake generator: Unix Makefiles
— CMake build tool: /usr/bin/make
— Configuration: RELEASE

— C/C++:
— Built as dynamic libs?: NO
— C++ Compiler: /usr/bin/c++ (ver 4.9.2)
— C++ flags (Release): -fPIC -fsigned-char -W -Wall -Werror=return-type -Werror=non-virtual-dtor -Werror=address -Werror=sequence-point -Wformat -Werror=format-security -Wmissing-declarations -Wundef -Winit-self -Wpointer-arith -Wshadow -Wsign-promo -Wno-narrowing -Wno-delete-non-virtual-dtor -fdiagnostics-show-option -pthread -fomit-frame-pointer -ffunction-sections -fvisibility=hidden -fvisibility-inlines-hidden -O3 -DNDEBUG -DNDEBUG
— C++ flags (Debug): -fPIC -fsigned-char -W -Wall -Werror=return-type -Werror=non-virtual-dtor -Werror=address -Werror=sequence-point -Wformat -Werror=format-security -Wmissing-declarations -Wundef -Winit-self -Wpointer-arith -Wshadow -Wsign-promo -Wno-narrowing -Wno-delete-non-virtual-dtor -fdiagnostics-show-option -pthread -fomit-frame-pointer -ffunction-sections -fvisibility=hidden -fvisibility-inlines-hidden -g -O0 -DDEBUG -D_DEBUG
— C Compiler: /usr/bin/cc
— C flags (Release): -fPIC -fsigned-char -W -Wall -Werror=return-type -Werror=non-virtual-dtor -Werror=address -Werror=sequence-point -Wformat -Werror=format-security -Wmissing-declarations -Wmissing-prototypes -Wstrict-prototypes -Wundef -Winit-self -Wpointer-arith -Wshadow -Wno-narrowing -fdiagnostics-show-option -pthread -fomit-frame-pointer -ffunction-sections -fvisibility=hidden -O3 -DNDEBUG -DNDEBUG
— C flags (Debug): -fPIC -fsigned-char -W -Wall -Werror=return-type -Werror=non-virtual-dtor -Werror=address -Werror=sequence-point -Wformat -Werror=format-security -Wmissing-declarations -Wmissing-prototypes -Wstrict-prototypes -Wundef -Winit-self -Wpointer-arith -Wshadow -Wno-narrowing -fdiagnostics-show-option -pthread -fomit-frame-pointer -ffunction-sections -fvisibility=hidden -g -O0 -DDEBUG -D_DEBUG
— Linker flags (Release):
— Linker flags (Debug):
— Precompiled headers: YES
— Extra dependencies: /usr/lib/arm-linux-gnueabihf/libpng.so /usr/lib/arm-linux-gnueabihf/libz.so /usr/lib/arm-linux-gnueabihf/libtiff.so /usr/lib/arm-linux-gnueabihf/libjasper.so /usr/lib/arm-linux-gnueabihf/libjpeg.so v4l1 v4l2 avcodec avformat avutil swscale avresample stdc++ dl m pthread rt
— 3rdparty dependencies: libwebp IlmImf

— OpenCV modules:
— To be built: hal core flann imgproc ml photo video imgcodecs shape videoio highgui objdetect superres ts features2d calib3d java stitching videostab python2 python3
— Disabled: world
— Disabled by dependency: –
— Unavailable: cudaarithm cudabgsegm cudacodec cudafeatures2d cudafilters cudaimgproc cudalegacy cudaobjdetect cudaoptflow cudastereo cudawarping cudev viz

— GUI:
— QT: NO
— GTK+: NO
— GThread : NO
— GtkGlExt: NO
— OpenGL support: NO
— VTK support: NO

— Media I/O:
— ZLib: /usr/lib/arm-linux-gnueabihf/libz.so (ver 1.2.8)
— JPEG: /usr/lib/arm-linux-gnueabihf/libjpeg.so (ver )
— WEBP: build (ver 0.3.1)
— PNG: /usr/lib/arm-linux-gnueabihf/libpng.so (ver 1.2.50)
— TIFF: /usr/lib/arm-linux-gnueabihf/libtiff.so (ver 42 – 4.0.3)
— JPEG 2000: /usr/lib/arm-linux-gnueabihf/libjasper.so (ver 1.900.1)
— OpenEXR: build (ver 1.7.1)
— GDAL: NO

— Video I/O:
— DC1394 1.x: NO
— DC1394 2.x: NO
— FFMPEG: YES
— codec: YES (ver 56.1.0)
— format: YES (ver 56.1.0)
— util: YES (ver 54.3.0)
— swscale: YES (ver 3.0.0)
— resample: YES (ver 2.1.0)
— gentoo-style: YES
— GStreamer: NO
— OpenNI: NO
— OpenNI PrimeSensor Modules: NO
— OpenNI2: NO
— PvAPI: NO
— GigEVisionSDK: NO
— UniCap: NO
— UniCap ucil: NO
— V4L/V4L2: Using libv4l1 (ver 1.6.0) / libv4l2 (ver 1.6.0)
— XIMEA: NO
— Xine: NO
— gPhoto2: NO

— Other third-party libraries:
— Use IPP: NO
— Use Eigen: NO
— Use TBB: NO
— Use OpenMP: NO
— Use GCD NO
— Use Concurrency NO
— Use C=: NO
— Use pthreads for parallel for:
— YES
— Use Cuda: NO
— Use OpenCL: YES

— OpenCL:
— Version: dynamic
— Include path: /media/usb/opencv-3.0.0/3rdparty/include/opencl/1.2
— Use AMDFFT: NO
— Use AMDBLAS: NO

— Python 2:
— Interpreter: /usr/bin/python2.7 (ver 2.7.9)
— Libraries: /usr/lib/arm-linux-gnueabihf/libpython2.7.so (ver 2.7.9)
— numpy: /usr/lib/python2.7/dist-packages/numpy/core/include (ver 1.8.2)
— packages path: lib/python2.7/dist-packages

— Python 3:
— Interpreter: /usr/bin/python3.4 (ver 3.4.2)
— Libraries: /usr/lib/arm-linux-gnueabihf/libpython3.4m.so (ver 3.4.2)
— numpy: /usr/lib/python3/dist-packages/numpy/core/include (ver 1.8.2)
— packages path: lib/python3.4/dist-packages

— Python (for build): /usr/bin/python2.7

— Java:
— ant: /usr/bin/ant (ver 1.9.4)
— JNI: /usr/lib/jvm/java-1.7.0-openjdk-armhf/include /usr/lib/jvm/java-1.7.0-openjdk-armhf/include /usr/lib/jvm/java-1.7.0-openjdk-armhf/include
— Java wrappers: YES
— Java tests: YES

— Matlab:
— mex: NO

— Documentation:
— Doxygen: NO
— PlantUML: NO

— Tests and samples:
— Tests: YES
— Performance tests: YES
— C/C++ Examples: YES

— Install path: /usr/local

— cvconfig.h is in: /media/usb/opencv-3.0.0/build
— —————————————————————–

— Configuring done
— Generating done
— Build files have been written to: /media/usb/opencv-3.0.0/build
pi@raspberrypi /media/usb/opencv-3.0.0/build $

setelah semuanya sudah sesuai dengan keinginan anda jalankan
$ make -j4
waktu make cukup memakan waktu yang lama, harap bersabar….

jika tidak ada error, lakukan perintah install
$ sudo make install
$ sudo ldconfig

Step terakhir Finishing

check opencv
ls -l /usr/local/lib/python2.7/dist-packages/
total 12428
-rw-r–r– 1 root staff 10372 Nov 28 08:16 clonevirtualenv.py
-rw-r–r– 1 root staff 10905 Nov 28 08:16 clonevirtualenv.pyc
-rw-r–r– 1 root staff 12600608 Jan 12 21:12 cv2.so

jika tidak menemukan cv2.so check di /site-packages/

step verifiy
$ python
Python 2.7.9 (default, Mar 8 2015, 00:52:26)
[GCC 4.9.2] on linux2
Type “help”, “copyright”, “credits” or “license” for more information.
>>> import cv2
>>> cv2.__version__
‘3.0.0’
>>>

terlihat import cv2 sukses dan versinya

sumber:

http://www.pyimagesearch.com/2015/10/26/how-to-install-opencv-3-on-raspbian-jessie/

https://dvsaraiva.wordpress.com/2015/06/13/build-opencv-3-0-gold-edition/