Showing posts with label Security. Show all posts
Showing posts with label Security. Show all posts
Sunday, August 3, 2014
In an earlier post here , we have shown you how to sign data and generate a digital signature in Java. Generating the signature alone does not provide security, you will also have to verify the digital signature. So according to that today I am going to show you how to verify a Digital Signature in Java. Here in our example we will show how you can do it once you are provided with the original dta, the public key (whose corresponding private key was used to sign the data) and finally the signature bytes that were generated earlier.
In our previous article we have stored the public key in encided form in a file with an extension .pubkey and the signature bytes in a file with extension .dsa . So in order to verify first we will try to read the key bytes and pass them to X509EncodedKeySpec object. Then use the KeyFactory to reconstruct the public key. Next we have to create the Signature object with the same algorithm as earlier and initialize with the public key.
In our previous article we have stored the public key in encided form in a file with an extension .pubkey and the signature bytes in a file with extension .dsa . So in order to verify first we will try to read the key bytes and pass them to X509EncodedKeySpec object. Then use the KeyFactory to reconstruct the public key. Next we have to create the Signature object with the same algorithm as earlier and initialize with the public key.
Labels:Security | 1 comments
Sunday, June 29, 2014
Today in this tutorial I am going to show you how to generate and use Digital Signature to sign any data or document in Java. Digital Signatures are a very important part of security. It ensures authenticity and non-repudiation of any data. In order to prove authenticity, the sender of the data signs the data with a digital signature and the receiver verifies the signature. Here we will only consider about signing the data, while verifying digital signature will be discussed in another later tutorial.
How to sign data with digital signature ?
1. Form the message to be signed.
2. Generate a public-private key pair
3. Calculate hash of the message and encrypt it with sender's private key
4. Send the dugutally signed message with the signature along with the public key.
In this tutorial, we will be signing the data stored in a file. The file path will be taken as an input. The resulting output will be two file : a .dsa file containing the digital signature, and a .pubkey file containing the public key in encoded form.
How to sign data with digital signature ?
1. Form the message to be signed.
2. Generate a public-private key pair
3. Calculate hash of the message and encrypt it with sender's private key
4. Send the dugutally signed message with the signature along with the public key.
In this tutorial, we will be signing the data stored in a file. The file path will be taken as an input. The resulting output will be two file : a .dsa file containing the digital signature, and a .pubkey file containing the public key in encoded form.
Labels:Security | 0
comments
Friday, April 4, 2014
Today I will show you how to do 256bits AES encryption and decryption of a file in Java. You can write codes for AES - 128bits without doing any extra configuration but to use AES - 256bits first of all you have to carry out the following steps. This is because when you install JDK it has default strength which is Strong but you will have to increase it to Unlimited.
- Download the right version of Java Cryptography Extension (JCE) Unlimited Strength Jurisdiction Policy Files. For JDK7 download it from here
- Extract the archive and copy the two JAR files (local_policy.jar and US_export_policy.jar) and paste it in the directory JAVA_HOME/jre/lib/security for example C:/Program Files/Java/jdk1.7.0/jre/lib/security
In order to perform the encryption, first of all a KeYGenerator instance is created for AES key and the key length is set to 256 using init() method. Then the key is generated which is used for initializing Cipher instance. The generated key is saved to the output file(which will contain encrypted contents) to be used later. The cipher instance is used by the CipherOutputStream to encrypt and write the contents in encrypted format.
In order to decrypt the encrypted file, initially the key that was saved is read from the file. Then that key is used for initializing Cipher for decryption. The cipher instance is used by CipherInputStream to read encrypted contents and generate the original contents which are then written to file using FileOutputStream.
-------------------------------------------------------------------------------------------------------------------------
Java Source Code
-------------------------------------------------------------------------------------------------------------------------
package com.javaingrab.security.encrypt;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import javax.crypto.Cipher;
import javax.crypto.CipherInputStream;
import javax.crypto.CipherOutputStream;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
public class AESEncryptor {
public void encrypt(String fname) throws Exception{
KeyGenerator keyGen = KeyGenerator.getInstance("AES");
keyGen.init(256); //using AES-256
SecretKey key = keyGen.generateKey(); //generating key
Cipher aesCipher = Cipher.getInstance("AES"); //getting cipher for AES
aesCipher.init(Cipher.ENCRYPT_MODE, key); //initializing cipher for encryption with key
//creating file output stream to write to file
try(FileOutputStream fos = new FileOutputStream(fname+".aes")){
//creating object output stream to write objects to file
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(key); //saving key to file for use during decryption
//creating file input stream to read contents for encryption
try(FileInputStream fis = new FileInputStream(fname)){
//creating cipher output stream to write encrypted contents
try(CipherOutputStream cos = new CipherOutputStream(fos, aesCipher)){
int read;
byte buf[] = new byte[4096];
while((read = fis.read(buf)) != -1) //reading from file
cos.write(buf, 0, read); //encrypting and writing to file
}
}
}
}
public void decrypt(String fname)throws Exception{
SecretKey key =null;
//creating file input stream to read from file
try(FileInputStream fis = new FileInputStream(fname)){
//creating object input stream to read objects from file
ObjectInputStream ois = new ObjectInputStream(fis);
key = (SecretKey)ois.readObject(); //reading key used for encryption
Cipher aesCipher = Cipher.getInstance("AES"); //getting cipher for AES
aesCipher.init(Cipher.DECRYPT_MODE, key); //initializing cipher for decryption with key
//creating file output stream to write back original contents
try(FileOutputStream fos = new FileOutputStream(fname+".dec")){
//creating cipher input stream to read encrypted contents
try(CipherInputStream cis = new CipherInputStream(fis, aesCipher)){
int read;
byte buf[] = new byte[4096];
while((read = cis.read(buf)) != -1) //reading from file
fos.write(buf, 0, read); //decrypting and writing to file
}
}
}
}
public static void main(String[] args) throws Exception {
AESEncryptor obj = new AESEncryptor();
obj.encrypt("clear.txt");
obj.decrypt("clear.txt.aes");
}
}
NOTE : You will need the clear.txt file which is the file to be encrypted to execute the code. The encrypted file will be placed in the same directory with same name as original file but with an extension ".aes". The decrypted file will have the same name as the encrypted file but with extension ".dec", this is done deliverately for you people to check whether the original conetents are same as the decrypted one.-------------------------------------------------------------------------------------------------------------------------
Download Links
-------------------------------------------------------------------------------------------------------------------------DOWNLOAD the source from Mediafire
Labels:Files,Security | 6
comments
Sunday, March 31, 2013
-------------------------UPDATE-------------------------
I have updated the code on request of some followers so that they can directly use this code for their project without requiring to make any changes.Following changes have been made
- A copy method has been introduced to copy the streams. I reduces unnecessary duplicate codes for copying files.
- Another important update added is that the file decrypted will have the same name it had before encryption along with its extension.
- The last feature added is try with resources. This reduces extra bit of coding to flush and close the streams.
--------------------------------------------------
Today I am going to discuss how you can encrypt any file in Java.For encryption we need a key based on which the encryption will be done. Not only that, I will also show how you can decrypt that file and get back the original one. The encryption algorithm can be chosen by the user. Here we will use some classes Cipher,CipherInputStream,CipherOutputStream,SecretKeySpec. One thing you have to always remember is that the same key must be used both for encryption and decryption. We will use Cipher stream classes as only one function call is required for both either reading/writing and encryption/decryption. Otherwise we would have to call update() method for encryption/decryption and then write() for writing to file.
SecretKeySpec class : This class specifies a secret key in a provider-independent fashion and is only useful for raw secret keys that can be represented as a byte array and have no key parameters associated with them, e.g., DES or Triple DES keys.
Cipher class : This class provides the functionality of a cryptographic cipher for encryption and decryption. It forms the core of the Java Cryptographic Extension (JCE) framework. Its getInstance() method is called to get the object based on algorithm. Then the init() method is called for initializing the object with encryption mode and key.
CipherInputStream class : It is composed of an InputStream and a Cipher so that read() methods return data that are read in from the underlying InputStream but have been additionally processed by the Cipher. The Cipher must be fully initialized before being used by a CipherInputStream. It is used for decryption and does read and then update operation.
CipherOutputStream class : Just like above it is also composed of a stream and cipher and the cipher must be fully initialised before using this stream. It is used for encryption purpose.
So below is the code which solves your question how to encrypt a file in Java and also how to decrypt a file. This code actually shows you how to encrypt and decrypt a file using DES or Triple DES in Java.
--------------------------------------------------------------------------------------------------------------------------
Java Source Code
--------------------------------------------------------------------------------------------------------------------------The code after update applied
import java.io.InputStream;
import java.io.OutputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import javax.crypto.Cipher;
import javax.crypto.CipherInputStream;
import javax.crypto.CipherOutputStream;
import javax.crypto.spec.SecretKeySpec;
public class FileEncryptor{
private String algo;
private String path;
public FileEncryptor(String algo,String path) {
this.algo = algo; //setting algo
this.path = path;//setting file path
}
public void encrypt() throws Exception{
//generating key
byte k[] = "HignDlPs".getBytes();
SecretKeySpec key = new SecretKeySpec(k,algo.split("/")[0]);
//creating and initialising cipher and cipher streams
Cipher encrypt = Cipher.getInstance(algo);
encrypt.init(Cipher.ENCRYPT_MODE, key);
//opening streams
FileOutputStream fos =new FileOutputStream(path+".enc");
try(FileInputStream fis =new FileInputStream(path)){
try(CipherOutputStream cout=new CipherOutputStream(fos, encrypt)){
copy(fis,cout);
}
}
}
public void decrypt() throws Exception{
//generating same key
byte k[] = "HignDlPs".getBytes();
SecretKeySpec key = new SecretKeySpec(k,algo.split("/")[0]);
//creating and initialising cipher and cipher streams
Cipher decrypt = Cipher.getInstance(algo);
decrypt.init(Cipher.DECRYPT_MODE, key);
//opening streams
FileInputStream fis = new FileInputStream(path);
try(CipherInputStream cin=new CipherInputStream(fis, decrypt)){
try(FileOutputStream fos =new FileOutputStream(path.substring(0,path.lastIndexOf(".")))){
copy(cin,fos);
}
}
}
private void copy(InputStream is,OutputStream os) throws Exception{
byte buf[] = new byte[4096]; //4K buffer set
int read = 0;
while((read = is.read(buf)) != -1) //reading
os.write(buf,0,read); //writing
}
public static void main (String[] args)throws Exception {
new FileEncryptor("DES/ECB/PKCS5Padding","sample.txt").encrypt();
new FileEncryptor("DES/ECB/PKCS5Padding","sample.txt.enc").decrypt();
}
}
The original code before updateimport java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import javax.crypto.Cipher;
import javax.crypto.CipherInputStream;
import javax.crypto.CipherOutputStream;
import javax.crypto.spec.SecretKeySpec;
public class FileEncryptor{
private String algo;
private File file;
public FileEncryptor(String algo,String path) {
this.algo=algo; //setting algo
this.file=new File(path); //settong file
}
public void encrypt() throws Exception{
//opening streams
FileInputStream fis =new FileInputStream(file);
file=new File(file.getAbsolutePath()+".enc");
FileOutputStream fos =new FileOutputStream(file);
//generating key
byte k[] = "HignDlPs".getBytes();
SecretKeySpec key = new SecretKeySpec(k,algo.split("/")[0]);
//creating and initialising cipher and cipher streams
Cipher encrypt = Cipher.getInstance(algo);
encrypt.init(Cipher.ENCRYPT_MODE, key);
CipherOutputStream cout=new CipherOutputStream(fos, encrypt);
byte[] buf = new byte[1024];
int read;
while((read=fis.read(buf))!=-1) //reading data
cout.write(buf,0,read); //writing encrypted data
//closing streams
fis.close();
cout.flush();
cout.close();
}
public void decrypt() throws Exception{
//opening streams
FileInputStream fis =new FileInputStream(file);
file=new File(file.getAbsolutePath()+".dec");
FileOutputStream fos =new FileOutputStream(file);
//generating same key
byte k[] = "HignDlPs".getBytes();
SecretKeySpec key = new SecretKeySpec(k,algo.split("/")[0]);
//creating and initialising cipher and cipher streams
Cipher decrypt = Cipher.getInstance(algo);
decrypt.init(Cipher.DECRYPT_MODE, key);
CipherInputStream cin=new CipherInputStream(fis, decrypt);
byte[] buf = new byte[1024];
int read=0;
while((read=cin.read(buf))!=-1) //reading encrypted data
fos.write(buf,0,read); //writing decrypted data
//closing streams
cin.close();
fos.flush();
fos.close();
}
public static void main (String[] args)throws Exception {
new FileEncryptor("DES/ECB/PKCS5Padding","sample.txt").encrypt();
new FileEncryptor("DES/ECB/PKCS5Padding","sample.txt.enc").decrypt();
}
}
NOTE : The generated decrypted file name is not the same as that of original so that you can check whether same contents have been generated or not. You can change this part.--------------------------------------------------------------------------------------------------------------------------
Download Links
--------------------------------------------------------------------------------------------------------------------------DOWNLOAD the source from Mediafire
DOWNLOAD the complete file encryptor project from Mediafire
NOTE : the project archive contains the java source file, the sample file for encryption and the encrypted file produced after encryption of sample file.
--------------------------------------------------------------------------------------------------------------------------
Related Posts
--------------------------------------------------------------------------------------------------------------------------Search keywords : how to, encrypt, decrypt, files, using DES, for encryption and decryption, java
Happy coding :)
Labels:Files,Security | 32
comments
Wednesday, January 30, 2013
Many of you must have seen that a MD5/SHA-1/SHA-256/SHA-512 hash is given for every file that you download from internet. This is necessary to check whether the file downloaded has the same hash as that of original file and there is no error while downloading. This is also used in case of copyrighted objects. You must have thought how can you generate this hash. Today I am going to describe how you can very easily generate hash of a file. Here I will use java.security.MessageDigest and java.security.DigestInputStream class.
MessageDigest class : A MessageDigest object starts out initialized with defined hash algorithm. The data is processed through it using the update methods. At any point reset can be called to reset the digest. Once all the data to be updated has been updated, one of the digest methods should be called to complete the hash computation. The digest method can be called once for a given number of updates. After digest has been called, the MessageDigest object is reset to its initialized state.
DigestInputStream class : A transparent stream that updates the associated message digest using the bits going through the stream. To complete the message digest computation, call one of the digest methods on the associated message digest after your calls to one of this digest input stream's read methods.
--------------------------------------------------------------------------------------------------------------------------
NOTE ; Very soon I will be posting a GUI version of this. So stay connected.
--------------------------------------------------------------------------------------------------------------------------
The input file contained text abcdefghi. The algorithm used here is Md5. To use any other algorithm, pass either SHA-1/SHA-256/SHA-512 as a command-line argument instead of Md5.
--------------------------------------------------------------------------------------------------------------------------
DOWNLOAD the source from Mediafire
MessageDigest class : A MessageDigest object starts out initialized with defined hash algorithm. The data is processed through it using the update methods. At any point reset can be called to reset the digest. Once all the data to be updated has been updated, one of the digest methods should be called to complete the hash computation. The digest method can be called once for a given number of updates. After digest has been called, the MessageDigest object is reset to its initialized state.
DigestInputStream class : A transparent stream that updates the associated message digest using the bits going through the stream. To complete the message digest computation, call one of the digest methods on the associated message digest after your calls to one of this digest input stream's read methods.
--------------------------------------------------------------------------------------------------------------------------
Java Source Code
--------------------------------------------------------------------------------------------------------------------------import java.io.InputStream;
import java.io.IOException;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.DigestInputStream;
import java.security.NoSuchAlgorithmException;
public class HashFile {
private String fname;
private DigestInputStream dis;
private MessageDigest md;
public HashFile(String fname,String hashAlgo) {
try{
md=MessageDigest.getInstance(hashAlgo); //initializing
InputStream fis=getClass().getResourceAsStream(fname);
dis=new DigestInputStream(fis,md); //getting stream
}catch(NoSuchAlgorithmException e){
e.printStackTrace();
}
}
public String generateHash()throws IOException{
byte[] buf=new byte[4096]; //setting buffer
while (dis.read()!=-1); //reading and updating message digest
byte[] output=md.digest(); //getting hash data in bytes
BigInteger bi=new BigInteger(1,output);
String hashText=bi.toString(16); //getting hex value of hash
dis.close(); //closing stream
return hashText;
}
public static void main(String[] args) throws Exception{
if(args.length<2){
System.out.println("INVALID INPUT");
System.exit(1);
}
HashFile obj=new HashFile(args[0],args[1]);
System.out.println (obj.generateHash()); //printing hash
}
}
NOTE ; Very soon I will be posting a GUI version of this. So stay connected.
--------------------------------------------------------------------------------------------------------------------------
Output
--------------------------------------------------------------------------------------------------------------------------The input file contained text abcdefghi. The algorithm used here is Md5. To use any other algorithm, pass either SHA-1/SHA-256/SHA-512 as a command-line argument instead of Md5.
--------------------------------------------------------------------------------------------------------------------------
Download Links
--------------------------------------------------------------------------------------------------------------------------DOWNLOAD the source from Mediafire
Labels:Security | 0
comments
Wednesday, January 9, 2013
In my last post I have mentioned about working differences between hashing and encryption. Based on their working, today I am going to post when and where we should use this processes for security.
The probability of a collision is astronomical for small input sizes. That's why it's recommended for passwords. For passwords up to 32 characters, MD5 has 4 times the output space. SHA-1 has about 6 times the output space. SHA-512 has about 16 times the output space. You must have seen that in many sites if you forgot your password then you are provided with a page to enter new password and old password is never recovered.
HASHING
It should be used a hash function when we want to compare but can't store the plain value. Passwords should always be hashed . This is because we don't want recover the stored password rather we would compare betwwen stored and input data. We also use hashing to check for pirated files. It is also used to verify whether two files are identical. This is helpful when we download a file from internet and can check successfully whether the downloaded file and file on server are same. Hash functions are also great for signing data. For example, if we are using HMAC, you sign a piece of data by taking a hash of the data concatenated with a known but not transmitted value (a secret value). So we send the plain-text and the HMAC hash. Then, the receiver simply hashes the submitted data with the known value and checks to see if it matches the transmitted HMAC. If it is the same, we know it wasn't tampered by a party without the secret value. This is commonly used in secure cookie systems by HTTP networks, as well as in message transmission of data over HTTP where we want some validity to the data.The probability of a collision is astronomical for small input sizes. That's why it's recommended for passwords. For passwords up to 32 characters, MD5 has 4 times the output space. SHA-1 has about 6 times the output space. SHA-512 has about 16 times the output space. You must have seen that in many sites if you forgot your password then you are provided with a page to enter new password and old password is never recovered.
ENCRYPTION
Encryption should be used whenever we need to get the input data back out. If we are storing credit card numbers, we need to get them back out at some point of time, but don't want to store the plain text. So instead, store the encrypted version and keep the key as safe as possible. This key is important as if someone gets this key then the value can be decrypted very easily.
Labels:Security | 0
comments
Saturday, January 5, 2013
Today I am going to post about security. Many of people has a misconception about hashing and encryption. Not only that many cannot understand when to use hashing and when to use encryption. So here we will discuss differences of hashing and encryption.
HASHING
They provide a mapping between an arbitrary length input, and usually fixed or smaller length output. It can be anything like simple CRC32, to a full blown cryptographic hash function such as MD5 , SHA-1/SHA-2/SHA-256/SHA-512. A one-way mapping is carried out. It's always a many:one mapping (there will always be collisions) since every function produces a smaller output than it's capable of inputting.The reason they are hard and practically impossible to reverse is because of their algorithms. Most hash functions iterate over the input many times to produce the output. At each fixed length input (which is algorithm dependent), the hash function will call it its current state. It will then iterate over this state and change to a new one and use the result as feedback (MD5 do this 64 times for each of 512bits of data). It then combines the resultant states from all the iterations back together to form the resultant hash of the input.
Now, if we want to decode the hash, you'd first need to figure out how to split the given hash into its iterated states. Then we need to reverse the iteration for each state. Now, to explain why this is VERY HARD, think of trying to deduce x and y from : x + y=10. There are 10 positive combinations of x and y that can work. Now iterate over that a number of times: tmp = x + y; x = y; y = tmp. For 64 iterations, we will have 10^64 possibilities. Real hash functions do a lot more than one operation (MD5 does 15 operations on 4 state variables). And since the next iteration depends on the state of the previous and the previous is destroyed in creating the current state, it's all but impossible to determine the input state that led to a given output state. Brute-force is a better choice than decoding if the length of input is known.
ENCRYPTION
They provide a 1:1 mapping between an arbitrary length input and and output and are always reversible. It is always 1:1 for a given key. Now, there are multiple input:key pairs that might generate the same output. Good encrypted data is indistinguishable from random noise. This is different from a hash output which is always of a consistent format.
Labels:Security | 0
comments
Subscribe to:
Posts
(Atom)
Total Pageviews
Followers
Labels
- Algorithms (7)
- Annotation (3)
- Files (6)
- Generics (3)
- Graphics2D (5)
- Graphics2D-Images (7)
- Inheritance (2)
- J2EE (9)
- Java 8 (4)
- Java FAQs (19)
- JDBC (3)
- Networking (2)
- Packages (1)
- Reflection (4)
- Security (7)
- Sorting (2)
- Swing (3)
- Threads (3)
- Utils (3)
Popular Posts
-
Today I will show you how you can implement Bankers algorithm in Java. The Banker's algorithm is a resource allocation and deadlock a...
-
------------------------- UPDATE ------------------------- I have updated the code on request of some followers so that they can directly...
-
Today I am going to show how to convert a postfix expression to an infix expression using stack in Java. In an earlier post here we ...
-
Today in this article I will tell you how to convert an infix expression to postfix expression using stack. This is an important applicat...
-
--------------------UPDATE------------------- I have updated my post so that now it can detect IE 11. This modification was necessary as t...
-
Today I am going to show you how you can generate and validate captcha. A CAPTCHA (an acronym for "Completely Automated Public Turin...
-
Today I am going to post a program that will be able to produce all the mColorings of a given graph G. What is mColoring : The problem st...
-
Today in this article I will show you how to create or develop a Tower of Hanoi game in Java. The Tower of Hanoi is a famous problem tha...



