GeeCON Prague 2014*
The moose likes I/O and Streams and the fly likes how to serialize a java.security.key Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


JavaRanch » Java Forums » Java » I/O and Streams
Bookmark "how to serialize a java.security.key" Watch "how to serialize a java.security.key" New topic
Author

how to serialize a java.security.key

sudheer kiran
Ranch Hand

Joined: Jun 26, 2008
Posts: 237

hi all my requirement is i need to store a key value as string .

i need this because i nee to store that key as a string into a map.

map.put("pwd","keyValueAsString");

is it possible..suggest me please.


Sudheer
SCWCD, SCJP 5
Ulf Dittmer
Marshal

Joined: Mar 22, 2005
Posts: 42038
    
  64
By "java.security.key", do you mean a byte[]? You can use base-64 encoding to convert that to a String. But maps can hold any kind of object (including byte[]), so I may be misunderstanding what you're trying to do.


Ping & DNS - my free Android networking tools app
sudheer kiran
Ranch Hand

Joined: Jun 26, 2008
Posts: 237

hi Ulf Dittmer,

i cannot change map from map<String,String>..as map is used every where in my project;
so i need to convert a "java.security.key' object to String Object and store into map.
and i should retrieve and convert it back to Key object. is that possible.

thank you for the reply.



James Sabre
Ranch Hand

Joined: Sep 07, 2004
Posts: 781

sudheer kiran wrote:hi Ulf Dittmer,

i cannot change map from map<String,String>..as map is used every where in my project;
so i need to convert a "java.security.key' object to String Object and store into map.
and i should retrieve and convert it back to Key object. is that possible.


java.security.Key has a method getEncoded() which return a byte[] array representing the bytes of the key. As Ulf says, you can then Base64 (or Hex or even ASCII85) encode these bytes to create a String. Recovery of the key can then be achieved by creating of an appropriate SecretKeySpec instance using the bytes of the decoded String and specifying the type of the key. You should note that SecretKeySpec extends java.security.Key so as long as you are talking of a SecretKey and not an RSA or DSA key then you don't have to go through any contortions involving KeyGenerator or the like.

Don't even think about just creating a String directly from the bytes of the key. String is not a suitable container for binary data and keys most definitely are binary data.


Retired horse trader.
 Note: double-underline links may be advertisements automatically added by this site and are probably not endorsed by me.
sudheer kiran
Ranch Hand

Joined: Jun 26, 2008
Posts: 237

hi James your solution resoled my problem,it's all working very fine ,very much thanks to you.
thank you Ulf Dittmer.
 
GeeCON Prague 2014
 
subject: how to serialize a java.security.key