Monday, March 21, 2011

Encrypt using RSA in Java

package com.emjay.util.encryption;

import java.io.IOException;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.Provider;
import java.security.PublicKey;
import java.security.Security;

import javax.crypto.Cipher;

public class EncryptionUtil {

protected static final String ALGORITHM = "RSA";

public static void main(String[] args) throws Exception {

Provider[] providerArray = Security.getProviders();

// Iterate through the default providers and print the name
for(int i=0; i
System.out.println("Built in Providers: (" + i + ")" + providerArray[i]);
}
// Generate the public and private key
KeyPair keyPair = EncryptionUtil.generateKey();
PublicKey publicKey = keyPair.getPublic();
PrivateKey privateKey = keyPair.getPrivate();

// Encrypt the String
byte[] encryptedBytes = encrypt(decodeBASE64("ABCDEFGH"), publicKey);
String encryptedString = encodeBASE64(encryptedBytes);
System.out.println("Encrypted String is: " + encryptedString);

// Decrypt the String
System.out.println("Decrypted String is: " + encodeBASE64(decrypt(encryptedBytes, privateKey)));
}

private static KeyPair generateKey() throws NoSuchAlgorithmException {
KeyPairGenerator keyGen = KeyPairGenerator.getInstance(ALGORITHM);
keyGen.initialize(1024);
KeyPair key = keyGen.generateKeyPair();
return key;
}

public static byte[] encrypt(byte[] text, PublicKey key) throws Exception {
byte[] cipherText = null;

Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
//System.out.println("Provider is: " + cipher.getProvider().getInfo());

cipher.init(Cipher.ENCRYPT_MODE, key);
cipherText = cipher.doFinal(text);
return cipherText;
}

private static byte[] decrypt(byte[] text, PrivateKey key) throws Exception {
byte[] dectyptedText = null;

Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
cipher.init(Cipher.DECRYPT_MODE, key);
dectyptedText = cipher.doFinal(text);
return dectyptedText;
}

private static String encodeBASE64(byte[] bytes) {
// Implement this method to convert byte array to String back
}

private static byte[] decodeBASE64(String text) throws IOException {
// Implement this method to convert String to byte array
}
}


* Please see Base64Coder from http://www.source-code.biz/base64coder/java/

How to create signed trusted applet?

Applets that get downloaded from server and executes on client browser operates in a sandbox. The process of applet getting downloaded is without user's approval and is automatic as we navigate to a page that contains applet. Hence, to prevent a malicious applet from potentially affecting the client system, the applet has certain constraints on what it can and what it cannot do.

If for a specific reason, you wish to allow the applet to (say) write to the file system on the client disk, you could do so by making a signed applet and user could accept the certificate to allow the applet to perform its operation. Without deliberating too much on the theory, I will illustrate the steps to create a signed applet.


1) Write the Java Applet code.

package com.emjay.applet;

import java.applet.Applet;
import java.awt.Graphics;
import java.io.BufferedOutputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

public class WriteFile extends Applet {
String myFile = "C:\\Users\\emjay\\test.foo";
File f = new File(myFile);
DataOutputStream ds;

public void paint(Graphics g) {
try {
ds = new DataOutputStream(new BufferedOutputStream(
new FileOutputStream(myFile), 128));

ds.writeChars("Wrote into the file system!!");
ds.flush();
g.drawString("Successfully wrote to " + myFile, 10, 10);
} catch (SecurityException e) {
g.drawString("Caught security exception", 10, 10);
} catch (IOException ioe) {
g.drawString("Caught I/O exception", 10, 10);
}
}
}

2) Compile the Java class and Jar the applet

javac com\emjay\applet\WriteFile.java
jar cvf WriteFile.jar com\emjay\applet\WriteFile.class

3) Generate the key certificate (Self Signed) using the command below:

keytool -genkey -alias WriteFileApplet -validity 365

* WriteFileApplet is an alias for the certificate that will be stored in .keystore.
* 365 indicates that this self signed certificate will be valid for 1 year
* You will have to answer a few questions while you generate the self signed cert including selecting a password.

4) Now, sign the applet jar filewith the Self Signed Cert using the command below:

jarsigner WriteFile.jar WriteFileApplet

* You will have to enter the password selected in the Step 3 while executing the command mentioned above.

5) Finally, create a simple web application and write the HTML file that uses this applet:

<applet code="com.emjay.applet.WriteFile" archive="WriteFile.jar" div=""></applet>

* Remember to place the WriteFile.jar and the HTML file under Web application's root directory.

6) When you access the HTML using a browser, you will see the certificate similar to the picture below:



Once you accept the certificate and press the Run button, the applet will load and execute.