Evening all!

Having a problem with keys, please allow me to explain(!):

I *CAN* create a key and convert the key to a byte array, then convert the array to a string(base 64):

KeyGenerator generator = KeyGenerator.getInstance("DES");
generator.init(new SecureRandom());
key = generator.generateKey();
byte[] keyBytes = key.getEncoded;
BASE64Encoder encoder = new BASE64Encoder();
String randomKey = encoder.encode(keyBytes);

and I *CAN* save that string to a database, forget about it, then sometime later reload it and convert it to a byte array again:

String loadedKey = "WhAt3Ver-It-I5" //from DB
BASE64Decoder decoder = new BASE64Decoder();
byte[] loadedKeyBytes = decoder.decodeBuffer(loadedKey);

what I *CAN'T* do is convert the loadedKeyBytes back into the key of the same type as it was originally, enabling me to decrypt whatever that key originally encrypted.

Does anyone know.

I know I need to convert it to a KeySpec, I presume as:


DESKeySpec keySpec = new DESKeySpec(loadedKeyBytes);

this compiles correctly.... but how do i then recreate the key so i can use it for decryption.

Suggestions / solutions would be gratefully received!

Cheers!

Relisys


================ CODE FOLLOWS ======================
import java.io.*;
import java.security.*;
import java.security.spec.*;
import javax.crypto.*;
import javax.crypto.spec.*;
import com.sun.crypto.provider.SunJCE;
import sun.misc.*;

public class SecPrescrip {

public static void main(String[] args) throws Exception {

// Create Key.
Key key;

KeyGenerator generator = KeyGenerator.getInstance("DES");
generator.init(new SecureRandom());
key = generator.generateKey();

// Get a cipher object

Cipher cipher = Cipher.getInstance("DES/ECB/PKCS5Padding");

// Encrypt the input string:

cipher.init(Cipher.ENCRYPT_MODE, key);
String input = "Medicare Secure Prescription: 30 Tamazopan 200mg tablets. Dosage: 1 to be taken every 4 hours";

System.out.println("Stage 1: ENCRYPT PRESCRIPTION WITH A RANDOM DES KEY");
System.out.println("===================================================");
System.out.println(" - Input Plain Text: "+input);
System.out.println("");
byte[] stringBytes = input.getBytes("UTF8");
byte[] raw = cipher.doFinal(stringBytes);
BASE64Encoder encoder = new BASE64Encoder();

String ciphertext1 = encoder.encode(raw);
System.out.println(" - Cipher Text: "+ciphertext1);
System.out.println("");

byte[] keybytes = key.getEncoded();
String randomkey = encoder.encode(keybytes);

System.out.println(" - Random Prescription Key: "+randomkey);
System.out.println("");
System.out.println("ENCRYPTION SUCESSFULL");
System.out.println("");
System.out.println("");
System.out.println("Stage 2: ENCRYPT RANDOM KEY WITH PATIENT MEDICARE KEY");
System.out.println("=====================================================");

BASE64Decoder decoder = new BASE64Decoder();

String passphrase = "ABCD1234efghIJ56"; //Patient Medicare Key

System.out.println(" - Patient Medicare Key: "+passphrase);
System.out.println("");
System.out.println(" - Input Plain Text: "+randomkey);


String algorithm = "PBEWithMD5AndDES";
byte[] salt = new byte[8];
int iteration = 20;

KeySpec ks = new PBEKeySpec(passphrase.toCharArray());
SecretKeyFactory skf = SecretKeyFactory.getInstance(algorithm);
SecretKey key2 = skf.generateSecret(ks);

byte[] input2 = decoder.decodeBuffer(randomkey);

MessageDigest md = MessageDigest.getInstance("MD5");
md.update(passphrase.getBytes());
md.update(input2);
byte[] digest = md.digest();
System.arraycopy(digest, 0, salt, 0, 8);

AlgorithmParameterSpec aps = new PBEParameterSpec(salt, iteration);
cipher = Cipher.getInstance(algorithm);
cipher.init(Cipher.ENCRYPT_MODE, key2, aps);
byte[] outputFinalKey = cipher.doFinal(input2);
String ciphertext2 = encoder.encode(outputFinalKey);
String saltString = encoder.encode(salt);
String encryptedCiphertext = saltString+ciphertext2;
System.out.println("");
System.out.println(" - Cipher Text (Final Prescription Key): "+ciphertext2);
System.out.println("");
System.out.println(" - Salt: "+saltString);
System.out.println("");
System.out.println(" - Full Encrypted Output: "+encryptedCiphertext);
System.out.println("");
System.out.println("ENCRYPTION SUCESSFULL");
System.out.println("");
System.out.println("");
System.out.println("Stage 3: DECRYPT PRESCRIPTION KEY USING PATIENT MEDICARE KEY");
System.out.println("============================================================");

//NOT CHANGED String passphrase = "ABCD1234efghIJ56";
System.out.println(" - Patient Medicare Key: "+passphrase);
System.out.println("");
System.out.println(" - Input Plain Text: "+ciphertext2);

algorithm = "PBEWithMD5AndDES";
salt = new byte[8];
iteration = 20;

ks = new PBEKeySpec(passphrase.toCharArray());
skf = SecretKeyFactory.getInstance(algorithm);
SecretKey key3 = skf.generateSecret(ks);

//Load in the input bytes as if they had been loaded from an sql database or the like

String saltIn = encryptedCiphertext.substring(0,12);
String ciphertext3 = encryptedCiphertext.substring(12,encryptedCiphertext.length());

byte[] saltArray = decoder.decodeBuffer(saltIn);
byte[] ciphertextarray = decoder.decodeBuffer(ciphertext3);


aps = new PBEParameterSpec(saltArray, iteration);
cipher = Cipher.getInstance(algorithm);

cipher.init(Cipher.DECRYPT_MODE, key3, aps);
byte[] outputKey2 = cipher.doFinal(ciphertextarray);
String plaintext2 = encoder.encode(outputKey2);

System.out.println(" - Plain Text (Random Generated Key): "+plaintext2);
System.out.println("");
System.out.println("");
System.out.println("ENCRYPTION SUCESSFULL");
System.out.println("");
System.out.println("");
System.out.println("Stage 4: DECRYPT PRESCRIPTION KEY USING PATIENT MEDICARE KEY");
System.out.println("============================================================");

// The decrypter string plaintext should be the same as the BASE64 Encoded representation of the random DES string
byte[] randomKeyFetched = decoder.decodeBuffer(plaintext2);

generator = KeyGenerator.getInstance("DES");

DESKeySpec keyspec = new DESKeySpec(randomKeyFetched);

/**
* Stuck here! Once the key is reformed it will be complete!
**/



}
}