Friday, April 18, 2014

RSA Encryption/Decryption - Part 1


What is Cryptography?

Cryptography is the practice or techniques for securing a communication in the presence of others. It is about constructing and analyzing protocols that overcome the influence of adversaries and are related to various aspects in information security such as data confidentiality, data integrity, authentication.

What is Encryption?

Encryption is one of the ways to achieve data security by translation of data into secret code or unreadable format called cipher text.

What is Decryption?

Decryption is the reverse of encryption that is converting cipher text to its original message, i.e. plain or readable text.

What is RSA?

RSA is one of the widely used public key cryptography for secure data communication. RSA stands for Ron Rivest, Adi Shamir and Leonard Adleman, who first publicly described it in 1978. Public key cryptohraphy is also called Asymmetric cryptography which requires two separate keys, one which is private key (secret key) and another which is public key. the public key is used to encrypt text while private key is used to decrypt text.

How to generate public/private key in java?




public static void generateKey(String private_key, String public_key) {
  try {
   final KeyPairGenerator keyGen = KeyPairGenerator
     .getInstance(ALGORITHM);
   keyGen.initialize(512);
   final KeyPair key = keyGen.generateKeyPair();

   File privateKeyFile = new File(private_key);
   File publicKeyFile = new File(public_key);

   // Create files to store public and private key
   if (privateKeyFile.getParentFile() != null) {
    privateKeyFile.getParentFile().mkdirs();
   }
   privateKeyFile.createNewFile();

   if (publicKeyFile.getParentFile() != null) {
    publicKeyFile.getParentFile().mkdirs();
   }
   publicKeyFile.createNewFile();

   // Saving the Public key in a file
   ObjectOutputStream publicKeyOS = new ObjectOutputStream(
     new FileOutputStream(publicKeyFile));
   publicKeyOS.writeObject(key.getPublic());
   publicKeyOS.close();

   // Saving the Private key in a file
   ObjectOutputStream privateKeyOS = new ObjectOutputStream(
     new FileOutputStream(privateKeyFile));
   privateKeyOS.writeObject(key.getPrivate());
   privateKeyOS.close();
  } catch (Exception e) {
   e.printStackTrace();
  }

 }

To call

generateKey("c:/rsa/key/public.key", "c:/rsa/key/private.key");
My next post on RSA details about how to encrypt and decrypt in java using  public and private key generated above.

No comments:

Post a Comment