Here is the DesEncrypter Class I have created.
package com.praxair.encryption;
import javax.crypto.*;
import javax.crypto.spec.SecretKeySpec;
import java.io.UnsupportedEncodingException;
import java.io.IOException;
public class DesEncrypter {
Cipher ecipher;
Cipher dcipher;
static final String ClassName = "com.praxair.encryption.Encrypt ";
public DesEncrypter()
{
//Set the Encrypt/Decrypt Keys
//String keyString = "4d89g13j4j91j27c582ji69373y788r6";
String keyString = "4d89g16h8k7j327c582ji6y9g3y788r6";
byte[] keyB = new byte[24]; // a Triple DES key is a byte[24] array
for (int i = 0; i < keyString.length() && i < keyB.length; i++) {
keyB[i] = (byte) keyString.charAt(i);
}
// Make the Key
SecretKey key = new SecretKeySpec(keyB, "DESede");
try {
ecipher = Cipher.getInstance("DES");
dcipher = Cipher.getInstance("DES");
ecipher.init(Cipher.ENCRYPT_MODE, key);
dcipher.init(Cipher.DECRYPT_MODE, key);
}
catch (javax.crypto.NoSuchPaddingException e) {}
catch (java.security.NoSuchAlgorithmException e) {}
catch (java.security.InvalidKeyException e) {}
}
public String encrypt(String str)
{
try {
byte[] utf8 = str.getBytes("UTF8");
byte[] enc = ecipher.doFinal(utf8);
return new sun.misc.BASE64Encoder().encode(enc);
}
catch (javax.crypto.BadPaddingException e) {}
catch (IllegalBlockSizeException e) {}
catch (UnsupportedEncodingException e) {}
return null;
}
public String decrypt(String str)
{
try {
byte[] dec = new sun.misc.BASE64Decoder().decodeBuffer(str);
byte[] utf8 = dcipher.doFinal(dec);
return new String(utf8, "UTF8");
}
catch (javax.crypto.BadPaddingException e) {}
catch (IllegalBlockSizeException e) {}
catch (UnsupportedEncodingException e) {}
catch (IOException e) {}
return null;
}
}
The class compiles with no problem.
When I import this class in another class and try to create a new instance of this I get an error. I changed the default constructor so instead of taking a SecretKey obeject as a parameter, I just store the "key" and use it everytime I want to encrypt or decrypt. therefore will always be using the same key throughout the whole application. Below is the method in the other class where Im trying to create an instance of the DesEncrypter so I can encrypt a string before I write it to the database. I get an error on the line " DesEncrypter encrypter = *new DesEncrypter();*" saying "the constructor DesEncrypter() is not visible?
{code}
public void encryptString(String x)
{
try
{
DesEncrypter encrypter = *new DesEncrypter();*
// Encrypt
String encrypted = encrypter.encrypt("Don't tell anybody!");
}
catch (Exception e)
{
}
}
{code}
Thanks for any help!