Solved

convert byte[] to key

Posted on 2000-04-13
13
398 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
 
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
What Should I Do With This Threat Intelligence?

Are you wondering if you actually need threat intelligence? The answer is yes. We explain the basics for creating useful threat intelligence.

 
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

What Should I Do With This Threat Intelligence?

Are you wondering if you actually need threat intelligence? The answer is yes. We explain the basics for creating useful threat intelligence.

Join & Write a Comment

Suggested Solutions

Title # Comments Views Activity
unix in java example 9 43
bitbucket vs gitbucket 3 34
Strange loading of website behaviour 3 23
github account with ecipse 1 20
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…
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 …
The viewer will learn how to implement Singleton Design Pattern in Java.

762 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

Need Help in Real-Time?

Connect with top rated Experts

20 Experts available now in Live!

Get 1:1 Help Now