Solved

convert byte[] to key

Posted on 2000-04-13
13
414 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 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
Revamp Your Training Process

Drastically shorten your training time with WalkMe's advanced online training solution that Guides your trainees to action.

 
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

The Ultimate Checklist to Optimize Your Website

Websites are getting bigger and complicated by the day. Video, images, custom fonts are all great for showcasing your product/service. But the price to pay in terms of reduced page load times and ultimately, decreased sales, can lead to some difficult decisions about what to cut.

Question has a verified solution.

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

After being asked a question last year, I went into one of my moods where I did some research and code just for the fun and learning of it all.  Subsequently, from this journey, I put together this article on "Range Searching Using Visual Basic.NET …
By the end of 1980s, object oriented programming using languages like C++, Simula69 and ObjectPascal gained momentum. It looked like programmers finally found the perfect language. C++ successfully combined the object oriented principles of Simula w…
Viewers will learn one way to get user input in Java. Introduce the Scanner object: Declare the variable that stores the user input: An example prompting the user for input: Methods you need to invoke in order to properly get  user input:
This video teaches viewers about errors in exception handling.

726 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