20.11.09

A Simple DES Encrypting/Decrypting Sample


public class TestCrypto {

public static void main(String [] args) throws Exception{
SecureRandom sr = new SecureRandom();
KeyGenerator kg = KeyGenerator.getInstance("DES");
kg.init(sr);

SecretKey key = kg.generateKey();
byte rawKeyData[] = key.getEncoded();

System.out.println("Secret Key => " + Arrays.toString(rawKeyData));

String str = "hello world";

DESKeySpec dks = new DESKeySpec(rawKeyData);
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
SecretKey key2 = keyFactory.generateSecret(dks);

Cipher ci = Cipher.getInstance("DES");
ci.init(Cipher.ENCRYPT_MODE, key, sr);
byte data[] = str.getBytes();
byte[] encryptedData = ci.doFinal(data);

ci = Cipher.getInstance("DES");
ci.init(Cipher.DECRYPT_MODE, key, sr);
byte[] decryptedData = ci.doFinal(encryptedData);
System.out.println("Decrypted => " + new String(decryptedData));

}

}

No comments: