40

I've been trying to convert a byte array to its original SecretKey, but I've no more ideas left. The most promising attempt was this one:

byte[] encodedKey     = Base64.decode(stringKey);
SecretKey originalKey = SecretKeySpec(encodedKey, 0, encodedKey.length, "AES")

found here: Converting Secret Key into a String and Vice Versa

I'm using the import javax.crypto.spec.SecretKeySpec, so the constructor for SecretKeySpec should be used correctly, at least referring to http://docs.oracle.com/javase/1.5.0/docs/api/javax/crypto/spec/SecretKeySpec.html.

Nonetheless I always get "The Method SecretKeySpec is undefined for ... [Class Name]" - which I just don't get.

I'm guessing it's just some minor mistake, but I just can't figure it out. Can someone please help me out here?

Community
  • 1
  • 1
Horstus Horax
  • 483
  • 2
  • 5
  • 5

1 Answers1

65

You need to use the new keyword to call the constructor and create the object.

SecretKey originalKey = new SecretKeySpec(encodedKey, 0, encodedKey.length, "AES");

When you try to call it without new, the compiler thinks it might be a method you've defined inside that class, hence your error message.

asteri
  • 11,402
  • 13
  • 60
  • 84
  • I know, still - it's good to know not to be alone ;-) thanks again! – Horstus Horax Jan 07 '13 at 22:00
  • 1
    Can you please say why you opted to use the 4-parameter constructor instead of `public SecretKeySpec(byte[] key, String algorithm)`? [link](https://docs.oracle.com/javase/7/docs/api/javax/crypto/spec/SecretKeySpec.html#SecretKeySpec(byte[],%20java.lang.String)). Thanks! – Kevin Meredith Nov 08 '20 at 04:03