Asynchronous Encryption and decryption with out file only key pass

package com.kartik;

import java.io.IOException;
import java.math.BigInteger;
import java.security.KeyFactory;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.RSAPrivateKeySpec;
import java.security.spec.RSAPublicKeySpec;

import javax.crypto.Cipher;
/**
 * 
 * @author kartik 
 * Blog kartikchandramandal.blogspot.com
 * RSA - Encrypt Data using Public Key
 * RSA - Descypt Data using Private Key
 */
public class RSAEncryptDescryptDemo {
public static void main(String[] args) throws IOException {
try {
System.out
.println("-------GENRATE PUBLIC and PRIVATE KEY-------------");
KeyPairGenerator keyPairGenerator = KeyPairGenerator
.getInstance("RSA");
keyPairGenerator.initialize(2048); // 1024 used for normal
// securities
KeyPair keyPair = keyPairGenerator.generateKeyPair();
PublicKey publicKey = keyPair.getPublic();
PrivateKey privateKey = keyPair.getPrivate();
// Pullingout parameters which makes up Key
System.out
.println("\n------- PULLING OUT PARAMETERS WHICH MAKES KEYPAIR----------\n");
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
RSAPublicKeySpec rsaPubKeySpec = keyFactory.getKeySpec(publicKey,
RSAPublicKeySpec.class);
RSAPrivateKeySpec rsaPrivKeySpec = keyFactory.getKeySpec(
privateKey, RSAPrivateKeySpec.class);
// Share public key with other so they can encrypt data and decrypt
// thoses using private key(Don't share with Other)
System.out
.println("\n--------SAVING PUBLIC KEY AND PRIVATE KEY TO FILES-------\n");
RSAEncryptDescryptDemo rsaObj = new RSAEncryptDescryptDemo();
String pubKey = rsaObj.saveKeysVal(rsaPubKeySpec.getModulus(),
rsaPubKeySpec.getPublicExponent());
System.out.println("PubKey --------- : " + pubKey);
String privtKey = rsaObj.saveKeysVal(rsaPrivKeySpec.getModulus(),
rsaPrivKeySpec.getPrivateExponent());
System.out.println("PrivKey --------- : " + privtKey);
// Encrypt Data using Public Key
byte[] encryptedData = rsaObj.encryptData(
"Kartik mandal - Classified Information !", pubKey);
// Descypt Data using Private Key
rsaObj.decryptData(encryptedData, privtKey);

} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (InvalidKeySpecException e) {
e.printStackTrace();
}

}

/**
*
* @param mod
*            mod
* @param exp
*            exp
* @return key
* @throws IOException
*             IOException
*/
private String saveKeysVal(BigInteger mod, BigInteger exp)
throws IOException {
String key = null;
return key = String.valueOf(mod) + " " + String.valueOf(exp);
}

/**
*
* @param data
*            data
* @param key
*            key
* @return encryptedData object
* @throws IOException
*             IOException
*/
private byte[] encryptData(String data, String key) throws IOException {
System.out.println("\n----------------ENCRYPTION STARTED------------");

System.out.println("Data Before Encryption :" + data);
byte[] dataToEncrypt = data.getBytes();
byte[] encryptedData = null;
try {
PublicKey pubKey = readPublicKeyFromString(key);
Cipher cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.ENCRYPT_MODE, pubKey);
encryptedData = cipher.doFinal(dataToEncrypt);
System.out.println("Encryted Data: " + encryptedData);

} catch (Exception e) {
e.printStackTrace();
}

System.out.println("----------------ENCRYPTION COMPLETED------------");
return encryptedData;
}

/**
*
* @param data
*            data
* @param puvKey
*            puvKey
* @throws IOException
*             IOException
*/
private void decryptData(byte[] data, String puvKey) throws IOException {
System.out.println("\n----------------DECRYPTION STARTED------------");
byte[] descryptedData = null;

try {
PrivateKey privateKey = readPrivateKeyFromString(puvKey);
Cipher cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.DECRYPT_MODE, privateKey);
descryptedData = cipher.doFinal(data);
System.out.println("Decrypted Data: " + new String(descryptedData));

} catch (Exception e) {
e.printStackTrace();
}

System.out.println("----------------DECRYPTION COMPLETED------------");
}

/**
*
* @param key
*            key
* @return publicKey generate
* @throws IOException
*             IOException
*/
public PublicKey readPublicKeyFromString(String key) throws IOException {
String[] temp;
BigInteger modulus = null;
BigInteger exponent = null;
String delimiter = " ";
temp = key.split(delimiter);
for (int i = 0; i < temp.length; i++) {
if (i == 0) {
modulus = new BigInteger(temp[i]);
} else if (i == 1) {
exponent = new BigInteger(temp[i]);
}
}
try {
// Get Public Key
RSAPublicKeySpec rsaPublicKeySpec = new RSAPublicKeySpec(modulus,
exponent);
KeyFactory fact = KeyFactory.getInstance("RSA");
PublicKey publicKey = fact.generatePublic(rsaPublicKeySpec);

return publicKey;

} catch (Exception e) {
e.printStackTrace();
}

return null;
}

/**
*
* @param key
*            key
* @return privateKey
* @throws IOException
*             IOException
*/
public PrivateKey readPrivateKeyFromString(String key) throws IOException {
String[] temp;
BigInteger modulus = null;
BigInteger exponent = null;
String delimiter = " ";
temp = key.split(delimiter);
for (int i = 0; i < temp.length; i++) {
if (i == 0) {
modulus = new BigInteger(temp[i]);
} else if (i == 1) {
exponent = new BigInteger(temp[i]);
}
}
try {
// Get Private Key
RSAPrivateKeySpec rsaPrivateKeySpec = new RSAPrivateKeySpec(
modulus, exponent);
KeyFactory fact = KeyFactory.getInstance("RSA");
PrivateKey privateKey = fact.generatePrivate(rsaPrivateKeySpec);

return privateKey;

} catch (Exception e) {
e.printStackTrace();
}

return null;
}

}

Previous
Next Post »