Wednesday, November 30, 2011

JAVA utility class to encrypt/decrypt data using password based encryption(PBEWithMD5AndDES)

JAVA utility class to encrypt/decrypt data using password based encryption(PBEWithMD5AndDES)

The below code snippet will help us to encrypt/decrypt data using password based encryption(PBEWithMD5AndDES).

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.PBEParameterSpec;


public class RdsCryptoLibrary {

private static final String PBE_KEY = "gZWKbHnijPAxrH+Sxw4fqp0FoVj6Ia2zA==qlPsn33wsz"
+ "ExumaDburVAw==PiU+p0wzGH2IbpQrpR6C7g==ld1"
+ "XwIUXYbSIBlPjTUYotg==CYm5rNsRA5KrGdPTvsrWuQ==";

private static final String PBE_ALGORITHM = "PBEWithMD5AndDES";

private static final String PBE_PROVIDER = "PBEWithMD5AndDES/CBC/PKCS5Padding";

private Cipher encryptCipher;

private Cipher decryptCipher;

private sun.misc.BASE64Encoder encoder = new sun.misc.BASE64Encoder();

private sun.misc.BASE64Decoder decoder = new sun.misc.BASE64Decoder();

public RdsCryptoLibrary( ) throws SecurityException {
//java.security.Security.addProvider(new com.sun.crypto.provider.SunJCE());
java.security.Security.addProvider(new com.ibm.crypto.provider.IBMJCE());
char[] pass = PBE_KEY.toCharArray();
byte[] salt = { (byte) 0xa3 , (byte) 0x21 , (byte) 0x24 , (byte) 0x2c ,
(byte) 0xf2 , (byte) 0xd2 , (byte) 0x3e , (byte) 0x19 };
int iterations = 3;
init(pass, salt, iterations);
}

public void init(char[] pass, byte[] salt, int iterations)
throws SecurityException {
try {
PBEParameterSpec ps = new javax.crypto.spec.PBEParameterSpec(salt,
20);

SecretKeyFactory kf = SecretKeyFactory.getInstance(PBE_ALGORITHM);
SecretKey k = kf.generateSecret(new javax.crypto.spec.PBEKeySpec(
pass));

encryptCipher = Cipher.getInstance(PBE_PROVIDER);
encryptCipher.init(Cipher.ENCRYPT_MODE, k, ps);

decryptCipher = Cipher.getInstance(PBE_PROVIDER);
decryptCipher.init(Cipher.DECRYPT_MODE, k, ps);
}
catch (Exception e) {
throw new SecurityException("Could not initialize CryptoLibrary: "
+ e.getMessage());
}
}

public synchronized String encrypt(String str) throws SecurityException {
try {
byte[] utf8 = str.getBytes("UTF8");
byte[] enc = encryptCipher.doFinal(utf8);
return encoder.encode(enc);
}
catch (Exception e) {
throw new SecurityException("Could not encrypt: " + e.getMessage());
}
}

public synchronized String decrypt(String str) throws SecurityException {
try {
byte[] dec = decoder.decodeBuffer(str);
byte[] utf8 = decryptCipher.doFinal(dec);
return new String(utf8, "UTF8");
}
catch (Exception e) {
throw new SecurityException("Could not decrypt: " + e.getMessage());
}
}
}


1 comment:

  1. Error for this line
    ==========================
    com.ibm.crypto.provider.IBMJCE()
    ==========================

    ReplyDelete