Solved

convert byte[] to key

Posted on 2000-04-13
13
406 Views
Last Modified: 2012-05-05
Dear,

   After I have generate a key,I want to turn it to byte[] ,and then encrypt it before saving to a file.When I want to use the key,I have to reverse the process:read from file,decrypt,and turn byte[] to key.However,I don't know how to turn byte[] to key(Class Key).May anyone show me the code?Thanks!
0
Comment
Question by:hpchong7
  • 7
  • 6
13 Comments
 
LVL 3

Expert Comment

by:Laminamia063099
ID: 2712019
Are you using a class that implements the interface Key?  If so, what class are you using?

Laminamia
0
 
LVL 2

Author Comment

by:hpchong7
ID: 2712561
May be I post the code here:
import java.io.*;
import java.security.*;

import javax.crypto.*;
import sun.misc.*;

public class prekey{
 public static void main(String[] args) throws Exception {
     
   Key key;
   try { ObjectInputStream in = new ObjectInputStream(
           new FileInputStream("ckey.ser"));
         key=(Key)in.readObject();
         in.close();
       }
   catch (FileNotFoundException fnfe) {
      KeyGenerator generator = KeyGenerator.getInstance("DES");
        
        generator.init(new SecureRandom());
        key = generator.generateKey();
      ObjectOutputStream out = new ObjectOutputStream(
        new FileOutputStream("ckey.ser"));
        out.writeObject(key);
        out.close();
    }
      

 }
}      

ie. I use the interface Key to creat a key.
Hope you can solve my problem!
0
 
LVL 3

Expert Comment

by:Laminamia063099
ID: 2712685
In this example, you are just writing the key to the file using serialization.  Where are you converting it to the byte code and encrypting it?

Laminamia :)
0
Announcing the Most Valuable Experts of 2016

MVEs are more concerned with the satisfaction of those they help than with the considerable points they can earn. They are the types of people you feel privileged to call colleagues. Join us in honoring this amazing group of Experts.

 
LVL 2

Author Comment

by:hpchong7
ID: 2712883
I do not converting it to the byte code and encrypting it in this example.However,I need to do it later on.Anyway ,back to my question,after I decrypt,how can I convert byte[] back to key?

0
 
LVL 2

Author Comment

by:hpchong7
ID: 2712889
I do not converting it to the byte code and encrypting it in this example.However,I need to do it later on.Anyway ,back to my question,after I decrypt,how can I convert byte[] back to key?

0
 
LVL 3

Accepted Solution

by:
Laminamia063099 earned 12 total points
ID: 2712983
Once you've read the byte string in and you've decoded it, construct the key using the following constructor:

key = new SecretKeySpec(byteArray, 0, byteArray.length, "DEC")

Laminamia :)
0
 
LVL 2

Author Comment

by:hpchong7
ID: 2713135
thanks!I'll try it first!
0
 
LVL 3

Expert Comment

by:Laminamia063099
ID: 2716038
Any luck?

Laminamia :)
0
 
LVL 2

Author Comment

by:hpchong7
ID: 2718637
Here is my overall program:

import java.io.*;
import java.security.*;

import javax.crypto.*;
import sun.misc.*;
import javax.crypto.spec.*;

public class keytest{
 public static void main(String[] args) throws Exception {
   MessageDigest md=MessageDigest.getInstance("SHA-1");
   BASE64Encoder encoder = new BASE64Encoder();
   BASE64Decoder decoder = new BASE64Decoder();
   Key key;
   try { ObjectInputStream in = new ObjectInputStream(
           new FileInputStream("ckey.ser"));
         key=(Key)in.readObject();
         in.close();
       }
   catch (FileNotFoundException fnfe) {
      KeyGenerator generator = KeyGenerator.getInstance("DES");
        
        generator.init(new SecureRandom());
        key = generator.generateKey();
      ObjectOutputStream out = new ObjectOutputStream(
        new FileOutputStream("ckey.ser"));
        out.writeObject(key);
        out.close();
    }
      
    byte[] priv=key.getEncoded();
      int len3=priv.length;
      md.update(priv,0,len3);
      byte[] raw3=md.digest();
      String keystring=encoder.encode(raw3);
      System.out.println(keystring);
      
      
      byte[] raw=decoder.decodeBuffer(keystring);
      //construct key from byte
      Key sk=new SecretKeySpec(raw, 0, raw.length, "DES");
      System.out.println(sk);
      
      byte[] pr=sk.getEncoded();
      int len=pr.length;
      md.update(pr,0,len);
      byte[] raw1=md.digest();
      String kstring=encoder.encode(raw1);
      System.out.println(kstring);
 }
}      

However,I find that the reconstructed Key sk is not equal to the original key!(As the message digest keystring and kstring are different)How come?!
0
 
LVL 3

Expert Comment

by:Laminamia063099
ID: 2722531
Sorry, I've tried to run your test but I'm getting an error: Algorithm "DES" not available.  Is your key already created via the serialized key, or are you creating it in this statement:
    KeyGenerator generator = KeyGenerator.getInstance("DES");

Laminamia :)
0
 
LVL 2

Author Comment

by:hpchong7
ID: 2723350
I work out finally.The code should be:
byte[] p=key.getEncoded();
String base64c=encoder.encode(p);
   

byte[] pp=decoder.decodeBuffer(base64c);
   
 KeySpec ks=new SecretKeySpec(pp,0,pp.length,"DES");
   SecretKeyFactory skfact=SecretKeyFactory.getInstance("DES");
   SecretKey sk=skfact.generateSecret(ks);
   System.out.println(sk);                  
   
Then ,I can get back the key(sk) again!
0
 
LVL 2

Author Comment

by:hpchong7
ID: 2723351
Thanks!
0
 
LVL 3

Expert Comment

by:Laminamia063099
ID: 2723417
Glad I could help.  Send me a copy of your final test class: jrayburn@wvu.edu, so I can see the final working code :)

Laminamia :)
0

Featured Post

Announcing the Most Valuable Experts of 2016

MVEs are more concerned with the satisfaction of those they help than with the considerable points they can earn. They are the types of people you feel privileged to call colleagues. Join us in honoring this amazing group of Experts.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
eclipse java  build path 6 59
Configure a Bean in an XML file 4 34
How do I remove an object from a 3 28
Chrome and Firefox Java 5 34
For beginner Java programmers or at least those new to the Eclipse IDE, the following tutorial will show some (four) ways in which you can import your Java projects to your Eclipse workbench. Introduction While learning Java can be done with…
This was posted to the Netbeans forum a Feb, 2010 and I also sent it to Verisign. Who didn't help much in my struggles to get my application signed. ------------------------- Start The idea here is to target your cell phones with the correct…
Video by: Michael
Viewers learn about how to reduce the potential repetitiveness of coding in main by developing methods to perform specific tasks for their program. Additionally, objects are introduced for the purpose of learning how to call methods in Java. Define …
Viewers learn how to read error messages and identify possible mistakes that could cause hours of frustration. Coding is as much about debugging your code as it is about writing it. Define Error Message: Line Numbers: Type of Error: Break Down…

825 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question