DES Encryption in C#

P

Peter Dolukhanov

Hi,

I am migrating some code from Java to C#. There is one class however,
which I am having trouble transferring. It deals with DES
Encryption/Decyption.

I have found the DESCryptoServiceProvider classes in C#, however I
cannot find the custom functionality used in Java. Included below is
the Java code:

-----

public class DesEncrypter
{
Cipher ecipher;
Cipher dcipher;

// 8-byte Salt
byte[] salt = {
(byte) 0xA9, (byte) 0x9B, (byte) 0xC8, (byte) 0x32,
(byte) 0x56, (byte) 0x35, (byte) 0xE3, (byte) 0x03
};

// Iteration count
int iterationCount = 19;


public DesEncrypter(String passPhrase)
{
try
{
// Create the key
KeySpec keySpec = new PBEKeySpec(passPhrase.toCharArray(),
salt, iterationCount);
SecretKey key =
SecretKeyFactory.getInstance("PBEWithMD5AndDES").generateSecret(keySpec);
ecipher = Cipher.getInstance(key.getAlgorithm());
dcipher = Cipher.getInstance(key.getAlgorithm());

// Prepare the parameter to the ciphers
AlgorithmParameterSpec paramSpec = new
PBEParameterSpec(salt, iterationCount);

// Create the ciphers
ecipher.init(Cipher.ENCRYPT_MODE, key, paramSpec);
dcipher.init(Cipher.DECRYPT_MODE, key, paramSpec);
}
catch (Exception e)
{
e.printStackTrace();
}
}

public String encrypt(String str)
{
try
{
// Encode the string into bytes using utf-8
byte[] utf8 = str.getBytes("UTF8");

// Encrypt
byte[] enc = ecipher.doFinal(utf8);

// Encode bytes to base64 to get a string
return new sun.misc.BASE64Encoder().encode(enc);
}
catch (Exception e)
{
e.printStackTrace();
}
return null;
}


public String encryptHex(String str)
{
try
{
// Encode the string into bytes using utf-8
byte[] utf8 = str.getBytes("UTF8");

// Encrypt
byte[] enc = ecipher.doFinal(utf8);

return toHex(enc);
}
catch (Exception e)
{
e.printStackTrace();
}
return null;
}

public static String toHex(byte[] b)
{
if (b == null)
{
return null;
}
String hits = "0123456789ABCDEF";
StringBuffer sb = new StringBuffer();

for (int i = 0; i < b.length; i++)
{
int j = ((int) b) & 0xFF;

char first = hits.charAt(j / 16);
char second = hits.charAt(j % 16);

sb.append(first);
sb.append(second);
}

return sb.toString();
}


public String decrypt(String str)
{
try
{
// Decode base64 to get bytes
byte[] dec = new
sun.misc.BASE64Decoder().decodeBuffer(str);

// Decrypt
byte[] utf8 = dcipher.doFinal(dec);

// Decode using utf-8
return new String(utf8, "UTF8");
}
catch (Exception e)
{
e.printStackTrace();
}
return null;
}
}

-----

Any advice would be greatly appreciated.

Best regards,

Peter Dolukhanov
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top