[2 days left] What’s wrong with your cloud strategy? Learn why multicloud solutions matter with Nimble Storage.Register Now

x
?
Solved

convert byte[] to key

Posted on 2000-04-13
13
Medium Priority
?
421 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
Concerto Cloud for Software Providers & ISVs

Can Concerto Cloud Services help you focus on evolving your application offerings, while delivering the best cloud experience to your customers? From DevOps to revenue models and customer support, the answer is yes!

Learn how Concerto can help you.

 
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 48 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

Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

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

Java had always been an easily readable and understandable language.  Some relatively recent changes in the language seem to be changing this pretty fast, and anyone that had not seen any Java code for the last 5 years will possibly have issues unde…
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…
Viewers learn about the “for” loop and how it works in Java. By comparing it to the while loop learned before, viewers can make the transition easily. You will learn about the formatting of the for loop as we write a program that prints even numbers…
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 …
Suggested Courses

656 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