java
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
* 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;
}
}
|
This Java code demonstrates how to perform RSA encryption
and decryption using public and private keys. Below is an overview of the key
components and functionality of the program:
Overview:
- RSA
Key Pair Generation: The code generates a public-private key pair
using KeyPairGenerator. The public key is used for encryption, and the
private key is used for decryption.
- Key
Specification Extraction: It extracts the modulus and exponent values
from the generated key pair using KeyFactory and stores them in a string
format.
- Encryption:
The method encryptData() encrypts a string using the public key.
- Decryption:
The method decryptData() decrypts the encrypted data back to its original
form using the private key.
Key Components:
- Key
Pair Generation:
java
KeyPairGenerator
keyPairGenerator = KeyPairGenerator.getInstance("RSA");
keyPairGenerator.initialize(2048);
KeyPair
keyPair = keyPairGenerator.generateKeyPair();
PublicKey
publicKey = keyPair.getPublic();
PrivateKey
privateKey = keyPair.getPrivate();
|
- Extracting
Modulus and Exponent:
java
RSAPublicKeySpec
rsaPubKeySpec = keyFactory.getKeySpec(publicKey, RSAPublicKeySpec.class);
RSAPrivateKeySpec
rsaPrivKeySpec = keyFactory.getKeySpec(privateKey, RSAPrivateKeySpec.class);
|
- Saving
Keys: The modulus and exponent are stored as strings:
java
String pubKey
= rsaObj.saveKeysVal(rsaPubKeySpec.getModulus(),
rsaPubKeySpec.getPublicExponent());
String
privtKey = rsaObj.saveKeysVal(rsaPrivKeySpec.getModulus(),
rsaPrivKeySpec.getPrivateExponent());
|
- Encryption:
java
byte[]
encryptedData = rsaObj.encryptData("Kartik mandal - Classified
Information !", pubKey);
|
- Decryption:
java
rsaObj.decryptData(encryptedData,
privtKey);
|
Methods:
- saveKeysVal(BigInteger
mod, BigInteger exp): Combines modulus and exponent into a single string.
- encryptData(String
data, String key): Encrypts the given data using the provided public key.
- decryptData(byte[]
data, String puvKey): Decrypts the given encrypted data using the provided
private key.
- readPublicKeyFromString(String
key): Converts the string representation of the public key back into a PublicKey
object.
- readPrivateKeyFromString(String
key): Converts the string representation of the private key back into a PrivateKey
object.
Example Usage:
When run, the program:
- Generates
RSA public and private keys.
- Encrypts
a sample string using the public key.
- Decrypts
the encrypted data using the private key, restoring the original string.
This is a basic demonstration of RSA encryption and
decryption in Java, highlighting key generation, encryption, and decryption
processes using RSA.
 |
Asynchronous Encryption and decryption |
0 Comments