Solved

convert byte[] to key

Posted on 2000-04-13
13
410 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
Independent Software Vendors: 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!

 
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

[Webinar] Code, Load, and Grow

Managing multiple websites, servers, applications, and security on a daily basis? Join us for a webinar on May 25th to learn how to simplify administration and management of virtual hosts for IT admins, create a secure environment, and deploy code more effectively and frequently.

Question has a verified solution.

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

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…
In this post we will learn how to connect and configure Android Device (Smartphone etc.) with Android Studio. After that we will run a simple Hello World Program.
Viewers learn about the third conditional statement “else if” and use it in an example program. Then additional information about conditional statements is provided, covering the topic thoroughly. Viewers learn about the third conditional statement …
The viewer will learn how to implement Singleton Design Pattern in Java.
Suggested Courses

734 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