开发者

JAVA: 128-bit key to String problem and back

I have created a SecretkeySpec object wich contains a 128 bit key. I would like to have this key in a String(this string needs to be put back in to the original key later), so i use Base64 encoding.

This is how my key looks in raw format from the byte array into chars:

*P??? ?ukL|?~

So I take the bytes and encode it like this.

byte[] okay = Base64.encode(eF.开发者_开发技巧getSpec().getEncoded());

Now when i translate it into chars i get:

S2xEa3Ara0o5blVGYTB3WkRIeUZmZz09DQo=

Now i want to have my key back restored to it's original format from the base64 encoded array.

String dkey = "S2xEa3Ara0o5blVGYTB3WkRIeUZmZz09DQo=";

byte[] key = null;
key = dKey.getBytes();
key = Base64.decode(key);

Now when i check the result i get:

DKlDkp+kJ9nUFa0wZHyFfg==

instead of:

*P??? ?ukL|?~ 

As you can see this is not the result i hoped to see. I surely made a novice mistake, and forgive me for that but i am relativaly new to programming. I would appreciate it if someone could give me a working example of transforming the 128 bit key to and from readable format, and perhaps an explanation where i went wrong with thinking.

And i apologize for any spelling mistakes, English is not my native language.

Thanks in advance


S2xEa3Ara0o5blVGYTB3WkRIeUZmZz09DQo=

decodes to

KlDkp+kJ9nUFa0wZDHyFfg==.

Is the extra D at the beginning a copy and paste error?

KlDkp+kJ9nUFa0wZDHyFfg== 

in turn is a valid base64 string that decodes to some binary data. So it seems that you are doing the encoding twice.

Now when i translate it into chars i get

How exactly are you doing that? Is there another base64 encoding involved in that step?


You had some errors in the code (presuming you wrote it from the top of your head). This looks like a working version. Note that using these internal classes is not very clever (here I would prefer to use Apache Commons Codecs library, for example and its org.apache.commons.codec.binary.Base64 class).

package edu.sasik.test.encoding;

import com.sun.org.apache.xerces.internal.impl.dv.util.Base64;

public class TestBase64 {

  public static void main(String[] args) {
    String base64Str = Base64.encode("Hello World!".getBytes());
    System.out.println(base64Str);
    byte[] bytes = Base64.decode(base64Str);
    System.out.println(new String(bytes));
  }

}

Output:

SGVsbG8gV29ybGQh
Hello World!

Hope this helps.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜