This is my requirement,
i have constant
string say "PASS123"
I need to
- Generate Random DES Key
- Generate a secret key using PASS123
- Encrypt the Random DES key using the secret key generated in second step.
On the decryption side what are the exact steps i need to follow to get the Random DES key that was generated from the client. I would have the secret key that is generated using "PASS123".
Please provide any helpful tips on this.
I was able to acheive the encryption steps mentioned above. But unable to decrypt!
Links i have referred
=============
http://www.java2s.com/Code/Java/Security/EncryptingwithDESUsingaPassPhrase.htm
http://sangchin.byus.net/JavaHelps/Javax_crypto/PassKey.html
http://download.oracle.com/javase/6/docs/technotes/guides/security/crypto/CryptoSpec.html
Source code
=========
import java.security.SecureRandom;
import java.security.spec.KeySpec;
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;
public class DESEnc {
private static final String UNICODE_FORMAT = "UTF8";
public static final String DES_ENCRYPTION_SCHEME = "DES";
private KeySpec myKeySpec;
private SecretKeyFactory mySecretKeyFactory;
private Cipher cipher;
SecretKey key, randomDESKey;
DESEnc(){
}
byte[] encrypt () throws Exception {
byte[] keyAsBytes;
String myEncryptionKey;
//generate a key with Password
myEncryptionKey = "Some 16 bit Key";
keyAsBytes = myEncryptionKey.getBytes(UNICODE_FORMAT);
myKeySpec = new DESKeySpec(keyAsBytes);
mySecretKeyFactory = SecretKeyFactory.getInstance(DES_ENCRYPTION_SCHEME);
cipher = Cipher.getInstance(DES_ENCRYPTION_SCHEME);
key = mySecretKeyFactory.generateSecret(myKeySpec);
System.out.println("Secret key" + new String(key.getEncoded()));
//generate Random DES Key
KeyGenerator generator;
generator = KeyGenerator.getInstance("DES");
generator.init(new SecureRandom());
randomDESKey = generator.generateKey();
System.out.println("RDK " + new String(randomDESKey.getEncoded()));
Cipher cipher = Cipher.getInstance("DES");
cipher.init(Cipher.ENCRYPT_MODE,randomDESKey);
byte[] encryptedText = cipher.doFinal(key.getEncoded());
System.out.println("Encrypted " + new String(encryptedText));
return encryptedText;
}
void decrypt(byte[] encStr) throws Exception {
cipher = Cipher.getInstance(DES_ENCRYPTION_SCHEME);
cipher.init(Cipher.DECRYPT_MODE, key);
byte[] decText = cipher.doFinal(encStr);
System.out.println("Decrypted Text " + new String(decText));
}
public static void main(String[] args) throws Exception {
DESEnc enc = new DESEnc();
enc.decrypt(enc.encrypt());
}
}