Home | Contact Us | FAQ | Search & Site Map | Link to Us
Sign In | Join | Other 45 Sites in Network
HomeAnnouncementsWhite Papers
Discussion GroupsFirst AidDatabasesJavaBeansGUIJava 3DVirtual MachineCORBASecurityToolsGeneral
Java DirectoryOpen Source ProjectsSample Book ChaptersUser GroupsWeb Resources
Related Topics
Databases.NETMore Topics ...

Java Forum / Security / February 2004

Tip: Looking for answers? Try searching our database.

How convert Public Key in byte[] to a String ??

Thread view: 
pcouas@infodev.fr - 06 Feb 2004 20:37 GMT
Hi,

I want convert kp.getPublic().getEncoded() to a string.
I want store this key in special file which is a text file, because
this is shared with a no java application.

When i convertr byte[] to string and after string to byte[], i havent
same result, why ?

UTF8 and BASE64Encoder don't resolve my problem.

Thanks

Philippe

import java.math.*;
import java.security.*;
import java.security.spec.*;

import javax.crypto.*;
import javax.crypto.spec.*;
import javax.crypto.interfaces.*;

import sun.misc.*; //Base64

import java.io.*;

public class Test3  {
   boolean doneAGI = false;
   byte[] ciphertext;
   static byte alice[]; //Test
   static String aliceb;
   static String alicec;

 
   public static void main(String args[]) {
     int taillekpg=512; //512 suffit pour test
     
       try {
           // Step 1:  AGI generates a key pair
           System.out.println("Etape 1");
           KeyPairGenerator kpg = KeyPairGenerator.getInstance("DH");
           kpg.initialize(taillekpg);
           KeyPair kp = kpg.generateKeyPair();
           

//        the encoded key, or null if the key does not support
encoding.
           alice = kp.getPublic().getEncoded();
           aliceb = new String(kp.getPublic().getEncoded(),"UTF8");
 

          System.out.println("alice "+alice); //
          System.out.println("aliceB "+aliceb);
          BASE64Encoder encoder = new BASE64Encoder();
          String alicec = encoder.encode(alice);
          System.out.println("aliceC "+alicec);

          String roundTrip = new String(alice);
          String roundTrip2 = new String(alice, "UTF8");
   
          byte[] Bytes1 = roundTrip.getBytes();
          byte[] utf8Bytes2 = roundTrip2.getBytes("UTF8");

          byte[] Bytes1b = aliceb.getBytes();
          byte[] utf8Bytes2b2 = aliceb.getBytes("UTF8");

          BASE64Decoder decoder = new BASE64Decoder();
          byte[]  utf8Bytes6 = decoder.decodeBuffer(alicec);

         System.out.println("alice1 "+Bytes1); //Mauvais
         System.out.println("alice2 "+utf8Bytes2); //Mauvais
     
         System.out.println("alice1B "+Bytes1b); //Mauvais
         System.out.println("alice2B "+utf8Bytes2b2); //Mauvais
         System.out.println("alicex6G "+utf8Bytes6); //Mauvais
        } catch (Exception e) {
           e.printStackTrace();
       }
   }
}

--------------------
alice [B@79dc36
aliceB 0
aliceC MIHfMIGXBgkqhkiG9w0BAwEwgYkCQQC+m8J4M39zZdhT0/Wu1oBfjdY/L2TQXo4Vidj4qW8u
8p1
wwUlw+Uv6ZT0x6bDpwKiRGIKGsWCxtZKWnCISMSdAkBVN4odeD1PftneQ8M3QV7Obx/JW3DRj9cT
H8thomXhM5nVQZ1nPNTCg2PCmMdsE0bI2TjyOp3xvb5LJGhj9VamAgIB/wNDAAJAe4YdEiC7ocJq
MRBN0XOtbNWMYuy5lOgNcHyVgSpsrMco1aulwcSf5PeuMbJRaxm+qIxMr1tu04cK0HcPjUISyQ==
alicex1G [B@2b95e6
alicex2G [B@7e64b9
alicex1B [B@6db54
alicex2B [B@297b0b
alicex6G [B@4d2c3c
Appuyez sur une touche pour continuer...
Michael Amling - 07 Feb 2004 03:07 GMT
> I want convert kp.getPublic().getEncoded() to a string.
> I want store this key in special file which is a text file, because
> this is shared with a no java application.
>
> When i convertr byte[] to string and after string to byte[], i havent
> same result, why ?

  byte[] to String is guaranteed to work only if you are using the same
encoding as was used to make the byte array from an original String. A
byte array you get from a String is always a valid encoding of some
String, but it's unlikely that a random byte array (and a cryptographic
key would always appear random) would by chance happen to be a valid
character encoding.

> UTF8 and BASE64Encoder don't resolve my problem.

  What's wrong with base 64? Base 64 can represent any sequence of bytes.

--Mike Amling
pcouas@infodev.fr - 08 Feb 2004 16:37 GMT
Hi,

If i understand your mail, byte[] alice=kp.getPublic().getEncoded()
could not be converted to a string and then after reconvert in a
byte[] ?
Could you confirm me

Thanks
Philippe
Michael Amling - 08 Feb 2004 20:47 GMT
> If i understand your mail, byte[] alice=kp.getPublic().getEncoded()
> could not be converted to a string and then after reconvert in a
> byte[] ?

  A naive method won't work, at least not all the time, and is unlikely
to work on a randomly selected key.
  For instance, the following is a naive method:

    byte[] keybytes=....getEncoded();
    String mySecretKeyString=new String(keybytes);

  Someone trying to use this method has not read
"http://java.sun.com/j2se/1.4.1/docs/api/java/lang/String.html#String(byte[])",
which states that the String constructor that takes a byte array as its
only parameter "Constructs a new String by decoding the specified array
of bytes using the platform's default charset. The length of the new
String is a function of the charset, and hence may not be equal to the
length of the byte array. The behavior of this constructor when the
given bytes are not valid in the default charset is unspecified."

  In fact, all the String constructors that take a byte array as a
parameter state that "The behavior of this constructor when the given
bytes are not valid in the given charset is unspecified."

  Those String constructors work when their byte array parameter was
obtained by conversion from a valid String using the same Charset.

  What will work for storing your key as ASCII characters is converting
the byte array to a base 64 representation of that that sequence of
bytes, and back.

--Mike Amling
pcouas@infodev.fr - 09 Feb 2004 11:02 GMT
Hi Mike,

I am newbie for theses problems,
I have tested without succes followong code lines

    KeyPairGenerator kpg = KeyPairGenerator.getInstance("DH");
           kpg.initialize(taillekpg);
           KeyPair kp = kpg.generateKeyPair();
           
           //Search default Encoding
           String de=null;
           OutputStreamWriter defaultReader = new OutputStreamWriter(System.out);
           de=defaultReader.getEncoding();
           System.out.println("defaultencoding "+de);  

          alice = kp.getPublic().getEncoded();
      aliced = new String(alice,de);


    BASE64Encoder encoder2 = new BASE64Encoder();
          String alicec = encoder2.encode(alice);

//------------------------------------------
    BASE64Decoder decoder2 = new BASE64Decoder();
    byte[]  utf8Bytes6 = decoder2.decodeBuffer(alicec);
   byte[] utf8Bytes4 = aliced.getBytes(de);

      System.out.println("alice "+alice);
     System.out.println("alice4 "+utf8Bytes4);
     System.out.println("alice6 "+utf8Bytes6);

I haven't same answer, could you give me a piece of code ??
Thanks

Philippe
Michael Amling - 10 Feb 2004 04:10 GMT
> Hi Mike,
>
> I am newbie for these problems,

  I believe you.

> I have tested without succes followong code lines
>
[quoted text clipped - 10 lines]
>            alice = kp.getPublic().getEncoded();
>       aliced = new String(alice,de);

  new String(alice,...) is not going to do you any good.

>  
>
[quoted text clipped - 3 lines]
> //------------------------------------------
>      BASE64Decoder decoder2 = new BASE64Decoder();
   byte[] b64decoded = decoder2.decodeBuffer(alicec);

  if (b64decoded.length!=alice.length) {
    System.out.println("Base 64 decoded array has "+
     b64decoded.length+" bytes but alice has "+
     alice.length+" bytes.");
  } else {
    int jj=alice.length;
    while (--jj>=0 && alice[jj]==b64decoded[jj]) {
    }
    if (jj<0) {
      System.out.println("Hooray! The alice array "+
       "has been reproduced from the base 64 String.");
    } else {
      System.out.println("alice["+jj+"]="+alice[jj]+
       "!=b64decoded["+jj+"]="+b64decoded[jj]);
    }
  }

>     byte[] utf8Bytes4 = aliced.getBytes(de);
>
>        System.out.println("alice "+alice);

  What do you expect this to print? Do you think it will magically
print the bytes of the alice array in hexadecimal? Actually, what it
prints does not depend at all on the contents of the alice array.

>       System.out.println("alice4 "+utf8Bytes4);
>       System.out.println("alice6 "+utf8Bytes6);
[quoted text clipped - 3 lines]
>
> Philippe

--Mike Amling
pcouas@infodev.fr - 10 Feb 2004 19:24 GMT
Thank you very much Mike.

Bye

Philippe
Michael Amling - 11 Feb 2004 15:51 GMT
> Thank you very much Mike.
>
> Bye

  You're welcome, Philippe. De rien.

--Mike Amling


Free Magazines

Get these publications absolutely FREE for up to 12 months. There are no hidden fees and no obligation. Simply choose a title, complete the application form and submit it. Read more ...

Oracle MagazineNetwork ComputingComputer WorldBio-IT WorldeWeekInformation WeekInfosecurity
 
Sign In
Join
My Latest Posts
My Monitored Threads
My Blog
My Photo Gallery
My Profile
My Homepage

Start New Thread
Enable EMail Alerts
Rate this Thread



©2008 Advenet LLC   Privacy Policy - Terms of Use
This website includes both content owned or controlled by Advenet as well as content owned or controlled by third parties.