Sunday, August 17, 2014

Encryption and Decryption Using Elliptical curve cryptography(ECC)


                  The problem with using java's SunEC provider is that it is not properly implemented.While on other hand you can find various provider like bouncycastle,flexiprovider who implemented the Elliptical curve cryptography very well.Here I am using BouncyCastle provider package to implement this demo ECC encryption and Decryption algoritham.If you are interested to implement this in android then you should SpongyCastle provider package as it is android compiled version of BouncyCastle.

           Below is the code for generating the key pair and Storing it into a file like public key in public.key file and private key in private.key file.I am storing this file in my folder d:/rp/ folder.

/* Code for Generating key Pair */
import java.io.*;
import java.security.*;
import java.security.spec.*;

public class Rahul {

public static void main(String args[]) {
Rahul rahul = new rahul();
try {
String path = "D:\\rp";

KeyPairGenerator keyGen = KeyPairGenerator.getInstance("DSA");

keyGen.initialize(1024);
KeyPair generatedKeyPair = keyGen.genKeyPair();

System.out.println("Generated Key Pair");
rahul.dumpKeyPair(generatedKeyPair);
rahul.SaveKeyPair(path, generatedKeyPair);

KeyPair loadedKeyPair = rahul.LoadKeyPair(path, "DSA");
System.out.println("Loaded Key Pair");
rahul.dumpKeyPair(loadedKeyPair);
} catch (Exception e) {
e.printStackTrace();
return;
}
}

private void dumpKeyPair(KeyPair keyPair) {
PublicKey pub = keyPair.getPublic();
System.out.println("Public Key: " + getHexString(pub.getEncoded()));

PrivateKey priv = keyPair.getPrivate();
System.out.println("Private Key: " + getHexString(priv.getEncoded()));
}

private String getHexString(byte[] b) {
String result = "";
for (int i = 0; i < b.length; i++) {
result += Integer.toString((b[i] & 0xff) + 0x100, 16).substring(1);
}
return result;
}

public void SaveKeyPair(String path, KeyPair keyPair) throws IOException {
PrivateKey privateKey = keyPair.getPrivate();
PublicKey publicKey = keyPair.getPublic();

// Store Public Key.
X509EncodedKeySpec x509EncodedKeySpec = new X509EncodedKeySpec(
publicKey.getEncoded());
FileOutputStream fos = new FileOutputStream(path + "/public.key");
fos.write(x509EncodedKeySpec.getEncoded());
fos.close();

// Store Private Key.
PKCS8EncodedKeySpec pkcs8EncodedKeySpec = new PKCS8EncodedKeySpec(
privateKey.getEncoded());
fos = new FileOutputStream(path + "/private.key");
fos.write(pkcs8EncodedKeySpec.getEncoded());
fos.close();
}

public KeyPair LoadKeyPair(String path, String algorithm)
throws IOException, NoSuchAlgorithmException,
InvalidKeySpecException {
// Read Public Key.
File filePublicKey = new File(path + "/public.key");
FileInputStream fis = new FileInputStream(path + "/public.key");
byte[] encodedPublicKey = new byte[(int) filePublicKey.length()];
fis.read(encodedPublicKey);
fis.close();

// Read Private Key.
File filePrivateKey = new File(path + "/private.key");
fis = new FileInputStream(path + "/private.key");
byte[] encodedPrivateKey = new byte[(int) filePrivateKey.length()];
fis.read(encodedPrivateKey);
fis.close();

// Generate KeyPair.
KeyFactory keyFactory = KeyFactory.getInstance(algorithm);
X509EncodedKeySpec publicKeySpec = new X509EncodedKeySpec(
encodedPublicKey);
PublicKey publicKey = keyFactory.generatePublic(publicKeySpec);

PKCS8EncodedKeySpec privateKeySpec = new PKCS8EncodedKeySpec(
encodedPrivateKey);
PrivateKey privateKey = keyFactory.generatePrivate(privateKeySpec);

return new KeyPair(publicKey, privateKey);
}
}

Once you execute above code you will get two file namely private,key and public.key in your given path, on my system it is in d:/rp/ folder.Now you got two keys let say this key is are for user ABC.Copy this keys in another folder called ABC.
Now again execute above code and copy generated two files in folder called XYZ this is for user XYZ.
Let think that ABC & XYZ exchanges there public key with each Other.To do this Make two folder "A" and "X".This two folder will contain following data

1.Folder "A" will contain public key of XYZ and Private key of ABC.

2.Folder "X" will contain public key of ABC and Private key of XYZ.




Once you get this file you can head to following encryption and decryption code.

Below is code for Encryption of your message.For encryption use the keys from Folder "A"
and we will decrypt this by using keys from folder "X" in next code.
  

/* Code for Encryption */
import java.io.File;
import java.io.FileInputStream;
import java.security.Key;
import java.security.KeyFactory;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.Security;
import java.security.spec.ECParameterSpec;
import java.security.spec.EllipticCurve;
import java.security.spec.KeySpec;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.Scanner;

import javax.crypto.Cipher;
import javax.crypto.KeyAgreement;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;

import org.apache.commons.codec.binary.Base64;
import org.bouncycastle.jce.provider.BouncyCastleProvider;





public class encryec {
KeyPairGenerator kpg;
EllipticCurve curve;
ECParameterSpec ecSpec;
KeyPair aKeyPair;
static KeyAgreement aKeyAgree;
KeyPair bKeyPair;
KeyAgreement bKeyAgree;
KeyFactory keyFac;
static String msg;
public static void main(String args[])
{
Security.addProvider(new BouncyCastleProvider());
Scanner ss=new Scanner(System.in);

try{
String path = "D:\\A";
File filePublicKey = new File(path+"\\public.key");
FileInputStream fis = new FileInputStream(path+"\\public.key");
byte[] encodedPublicKey = new byte[(int) filePublicKey.length()];
fis.read(encodedPublicKey);
fis.close();
 
// Read Private Key.
File filePrivateKey = new File(path+"\\private.key");
fis = new FileInputStream(path+"\\private.key");
byte[] encodedPrivateKey = new byte[(int) filePrivateKey.length()];
fis.read(encodedPrivateKey);
fis.close();
 
// Generate KeyPair.
KeyFactory keyFactory = KeyFactory.getInstance("ECDH");
X509EncodedKeySpec publicKeySpec = new X509EncodedKeySpec(
encodedPublicKey);
PublicKey publicKey = keyFactory.generatePublic(publicKeySpec);
 
PKCS8EncodedKeySpec privateKeySpec = new PKCS8EncodedKeySpec(
encodedPrivateKey);
PrivateKey privateKey = keyFactory.generatePrivate(privateKeySpec);
 
  aKeyAgree = KeyAgreement.getInstance("ECDH", "BC");
  aKeyAgree.init(privateKey);
  aKeyAgree.doPhase(publicKey, true);
  
  byte[] aBys = aKeyAgree.generateSecret(); 
  KeySpec aKeySpec = new DESKeySpec(aBys);
  SecretKeyFactory aFactory = SecretKeyFactory.getInstance("DES");
  Key aSecretKey = aFactory.generateSecret(aKeySpec);

  Cipher aCipher = Cipher.getInstance(aSecretKey.getAlgorithm());   
  aCipher.init(Cipher.ENCRYPT_MODE, aSecretKey);  
  byte[] encText = aCipher.doFinal("Its Rahul".getBytes());
  
  System.out.println(Base64.encodeBase64String(encText));
   
  System.out.println(encText);
  
}
catch(Exception e)
{
e.printStackTrace();
}
}
}

Take the output of above code and paste it at below line in code in place of yellow words
byte[]decText=aCipher.doFinal(Base64.decodeBase64("0wwerdjkHbVhYI+YPxUnmw==".getBytes()));

Below is code for Decryption of your output.For encryption we have used the keys from Folder "A"
and now we will decrypt this by using keys from folder "X" in below code.

/* code for Decryption */
import java.io.File;
import java.io.FileInputStream;
import java.security.Key;
import java.security.KeyFactory;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.Security;
import java.security.spec.ECParameterSpec;
import java.security.spec.EllipticCurve;
import java.security.spec.KeySpec;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;

import javax.crypto.Cipher;
import javax.crypto.KeyAgreement;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;

import org.apache.commons.codec.binary.Base64;
import org.bouncycastle.jce.provider.BouncyCastleProvider;



public class decryec {
KeyPairGenerator kpg;
EllipticCurve curve;
ECParameterSpec ecSpec;
KeyPair aKeyPair;
static KeyAgreement aKeyAgree;
KeyPair bKeyPair;
KeyAgreement bKeyAgree;
KeyFactory keyFac;
public static void main(String args[])
{
Security.addProvider(new BouncyCastleProvider());
try{
String path = "D:\\X";
File filePublicKey = new File(path +"\\public.key");
FileInputStream fis = new FileInputStream(path + "\\public.key");
byte[] encodedPublicKey = new byte[(int) filePublicKey.length()];
fis.read(encodedPublicKey);
fis.close();
 
// Read Private Key.
File filePrivateKey = new File(path + "\\private.key");
fis = new FileInputStream(path + "\\private.key");
byte[] encodedPrivateKey = new byte[(int) filePrivateKey.length()];
fis.read(encodedPrivateKey);
fis.close();
 
// Generate KeyPair.
KeyFactory keyFactory = KeyFactory.getInstance("ECDH");
X509EncodedKeySpec publicKeySpec = new X509EncodedKeySpec(
encodedPublicKey);
PublicKey publicKey = keyFactory.generatePublic(publicKeySpec);
 
PKCS8EncodedKeySpec privateKeySpec = new PKCS8EncodedKeySpec(
encodedPrivateKey);
PrivateKey privateKey = keyFactory.generatePrivate(privateKeySpec);
  aKeyAgree = KeyAgreement.getInstance("ECDH", "BC");
  aKeyAgree.init(privateKey);
  aKeyAgree.doPhase(publicKey, true);    
  byte[] aBys = aKeyAgree.generateSecret(); 
  KeySpec aKeySpec = new DESKeySpec(aBys);
  SecretKeyFactory aFactory = SecretKeyFactory.getInstance("DES");
  Key aSecretKey = aFactory.generateSecret(aKeySpec);

  Cipher aCipher = Cipher.getInstance(aSecretKey.getAlgorithm());   
  aCipher.init(Cipher.DECRYPT_MODE, aSecretKey);  
  byte[] decText = aCipher.doFinal(Base64.decodeBase64("0wwerdjkHbVhYI+YPxUnmw==".getBytes()));
  String text = new String(decText);
  
  System.out.println("Decoded="+text);
  
}
catch(Exception e)
{
e.printStackTrace();
}
}
}



Thanks for reading feel free to comment....................

Sunday, February 9, 2014

Elliptical curve cryptography in java

Elliptical curve Cryptography


                 Elliptic curve cryptography (ECC) is an approach to public-key cryptography based on the algebraic structure of elliptic curves over finite fields. Elliptic curves are also used in several integer factorization algorithms that have applications in cryptography, such as Lenstra elliptic curve factorization.
                 The primary benefit promised by ECC is a smaller key size, reducing storage and transmission requirements, i.e. that an elliptic curve group could provide the same level of security afforded by an RSA-based system with a large modulus and correspondingly larger key – e.g., a 256-bit ECC public key should provide comparable security to a 3072-bit RSA public key.


Implimentation:


Key Generation

Key generation is an important part where we have to generate both public key and private key. The sender will be encrypting the message with receiver’s public key and the receiver will decrypt its private key.
Now, we have to select a number ‘d’ within the range of ‘n’.
Using the following equation we can generate the public key

Q = d * P

d = The random number that we have selected within the range of ( 1 to n-1 ). Pis the point on the curve.
‘Q’ is the public key and ‘d’ is the private key.

Encryption

Let ‘m’ be the message that we are sending. We have to represent this message on the curve. This have in-depth implementation details. All the advance research on ECC is done by a company called certicom.
Conside ‘m’ has the point ‘M’ on the curve ‘E’. Randomly select ‘k’ from [1 - (n-1)].
Two cipher texts will be generated let it be C1 and C2.

C1 = k*P

C2 = M + k*Q

C1 and C2 will be send.

Decryption

We have to get back the message ‘m’ that was send to us,

M = C2 – d * C1

M is the original message that we have send.
How does we get back the message,
M = C2 – d * C1
‘M’ can be represented as ‘C2 – d * C1′
C2 – d * C1 = (M + k * Q) – d * ( k * P )          ( C2 = M + k * Q and C1 = k * P )
=  M + k  * d * P – d * k *P          ( canceling out k * d * P )
= M  ( Original Message )

_______________________________________________________
In java there is implemetation of ECC Algorithm we need to use those packages to implement the Ecc to provide security...
SOURCE CODE:
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.PrivateKey;
import java.security.Provider;
import java.security.PublicKey;
import java.security.Security;
import java.security.spec.ECGenParameterSpec;
import javax.crypto.Cipher;
import javax.crypto.CipherInputStream;
import javax.crypto.CipherOutputStream;

public class TestECC {
    public static void main(String args[]) {
        try {
            Provider p[] = Security.getProviders();
            Provider p1 = Security.getProvider("SunEC");
            System.out.println(p1.getName());
            
            KeyPairGenerator kpg = KeyPairGenerator.getInstance("EC", "SunEC");
            //kpg.initialize(128);
            System.out.println(kpg.getAlgorithm());
            //Cipher cipher = Cipher.getInstance("EC", "SunEC");
            Cipher cipher = Cipher.getInstance("DES");
            System.out.println("provider=" + cipher.getProvider());

            ECGenParameterSpec ecsp = new ECGenParameterSpec("sect163r2");   //sect163r2
            kpg.initialize(256);   //ecsp
            KeyPair kyp = kpg.genKeyPair();
            
            
            //PublicKey pubKey = kyp
            PublicKey pubKey = kyp.getPublic();
            
            //pubKey.toString()
            int zz=pubKey.toString().length();
            System.out.println("Size of key"+zz+"and key is "+pubKey.toString());

            PrivateKey privKey = kyp.getPrivate();
            int pp=pubKey.toString().length();
            System.out.println("Size of key"+pp+"and key is "+privKey.toString());
            
            //System.out.println(cipher.getProvider());
            System.out.println("/n/n");
        
            cipher.init(Cipher.ENCRYPT_MODE, pubKey);
            //cipher.init(Cipher.ENCRYPT_MODE, pubKey);

            String cleartextFile = "cleartext.txt";
            String ciphertextFile = "ciphertextECIES.txt";

            byte[] block = new byte[64];
            FileInputStream fis = new FileInputStream(cleartextFile);
            FileOutputStream fos = new FileOutputStream(ciphertextFile);
            CipherOutputStream cos = new CipherOutputStream(fos, cipher);

            int i;
            while ((i = fis.read(block)) != -1) {
                cos.write(block, 0, i);
            }
            cos.close();

            // Decrypt
            String cleartextAgainFile = "cleartextAgainECIES.txt";
            cipher.init(Cipher.DECRYPT_MODE, privKey, ecsp);
            fis = new FileInputStream(ciphertextFile);
            CipherInputStream cis = new CipherInputStream(fis, cipher);
            fos = new FileOutputStream(cleartextAgainFile);
            while ((i = cis.read(block)) != -1) {
                fos.write(block, 0, i);
            }
            fos.close();
        } 
catch (Exception e) {            System.out.print(e); }
    }
}