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); }
    }
}

14 comments:

  1. Sir
    Their is an error in your code at line
    cipher.init(Cipher.ENCRYPT_MODE, pubKey);

    ReplyDelete
  2. Rajat Bansal check this page then http://rahulatjava.blogspot.in/2014/08/encryption-and-decryption-using.html

    ReplyDelete
  3. can anyone can explain how to encrypt and decrypt an image using ECC algorithm

    ReplyDelete
    Replies
    1. image is rectangular array of m rows and N column,
      toatal M*N pixels
      each having grayscale value
      ranging from 0-255
      each pixel can be repressented as point on EC over finite fiels
      consider x co-ordinate
      or y co-ordinate
      same logic is repeated for
      for i=0;i<m;i++
      { for j=0;j<n;j++
      {
      }
      }
      }

      Delete
  4. Convert image in to base64 encoding data and then operate on it as strong of data.
    On the receiving end get the base64 data and convert again in to the image. It's proven solution.

    ReplyDelete
  5. Hello, Can you please explain how to use the private key to sign the mesage i mean :
    In the encryption we use the following (C1 = k*P
    C2 = M + k*Q)

    How we use the private key to sign the message

    --thnx

    ReplyDelete
  6. hello, i need source code to encrypt and decrypt image using ECC please can you help me.

    ReplyDelete
  7. i need java source code of elliptic curve key exchange using socket programming

    ReplyDelete
  8. Hello sir , what dataset is suitable for ECC. Please let me know.

    ReplyDelete
  9. can u tell me in this code where is the input?

    ReplyDelete
  10. The code does not work? here is the output of the console. Any idea what's wrong?

    SunEC
    EC
    provider=SunJCE version 1.8
    Size of key297and key is Sun EC public key, 256 bits
    public x coord: 108991203032435859729847554097937630869032505245523529858438274042894755924893
    public y coord: 19461663076586868687511977395852427306826701647772217263069680280215593206876
    parameters: secp256r1 [NIST P-256, X9.62 prime256v1] (1.2.840.10045.3.1.7)
    Size of key297and key is sun.security.ec.ECPrivateKeyImpl@ffffe62a
    /n/n
    java.security.InvalidKeyException: Wrong format: RAW bytes needed

    ReplyDelete
  11. The code does not work? here is the output of the console. Any idea what's wrong?

    SunEC
    EC
    provider=SunJCE version 1.8
    Size of key297and key is Sun EC public key, 256 bits
    public x coord: 108991203032435859729847554097937630869032505245523529858438274042894755924893
    public y coord: 19461663076586868687511977395852427306826701647772217263069680280215593206876
    parameters: secp256r1 [NIST P-256, X9.62 prime256v1] (1.2.840.10045.3.1.7)
    Size of key297and key is sun.security.ec.ECPrivateKeyImpl@ffffe62a
    /n/n
    java.security.InvalidKeyException: Wrong format: RAW bytes needed

    How to solve it...

    ReplyDelete
  12. The code does not work? here is the output of the console. Any idea what's wrong?

    SunEC
    EC
    provider=SunJCE version 1.8
    Size of key297and key is Sun EC public key, 256 bits
    public x coord: 108991203032435859729847554097937630869032505245523529858438274042894755924893
    public y coord: 19461663076586868687511977395852427306826701647772217263069680280215593206876
    parameters: secp256r1 [NIST P-256, X9.62 prime256v1] (1.2.840.10045.3.1.7)
    Size of key297and key is sun.security.ec.ECPrivateKeyImpl@ffffe62a
    /n/n
    java.security.InvalidKeyException: Wrong format: RAW bytes needed

    How to solve it...

    ReplyDelete