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/

No comments:

Post a Comment