dcsimg
how can I convert a byte array (from KEY.getEncoded()) back to a key
2 posts in topic
Flat View  Flat View
TOPIC ACTIONS:
 

Posted By:   Alex_Homans
Posted On:   Wednesday, April 16, 2003 03:26 PM

Evening all! Got a problem with some encryption work (pretty basic stuff it has to be admitted!). Heres my problem: 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:    More>>

Evening all!



Got a problem with some encryption work (pretty basic stuff it has to be admitted!). Heres my problem:



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.



Hope someone can shed some light!



Cheers!



Alex




================ 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!

**/





}

}

   <<Less

Re: how can I convert a byte array (from KEY.getEncoded()) back to a key

Posted By:   Bahman_Barzideh  
Posted On:   Thursday, April 17, 2003 11:41 AM

Have you tried:

DESKeySpec keySpec = new DESKeySpec (loadedKeyBytes);
SecretKeyFactory factory = SecretKeyFactory.getInstance ("DES");
SecretKey secretKey = factory.generateSecret (keySpec);

Re: how can I convert a byte array (from KEY.getEncoded()) back to a key

Posted By:   Eugene_Kuleshov  
Posted On:   Thursday, April 17, 2003 06:05 AM

There is nothing wron with DESKeySpec, so you can use that. You can also use the following code as suggested in Java Almanac.
  SecretKey key = new SecretKeySpec(keyBytes, "DES");

If you needed to use a passphrase for your DES encryption, then probably you should consider the following code (also from Java Almanac).

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

int iterationCount = 19;

KeySpec keySpec = new PBEKeySpec(passPhrase.toCharArray(), salt, iterationCount);
SecretKey key = SecretKeyFactory.getInstance( "PBEWithMD5AndDES").generateSecret(keySpec);
ecipher = Cipher.getInstance(key.getAlgorithm());

AlgorithmParameterSpec paramSpec = new PBEParameterSpec(salt, iterationCount);
ecipher.init(Cipher.ENCRYPT_MODE, key, paramSpec);

byte[] utf8 = str.getBytes("UTF8");

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

return new sun.misc.BASE64Encoder().encode(enc);
About | Sitemap | Contact