singhsumit
singhsumit

Reputation: 974

InvalidKeyException: invalid key format in Java using RSA Keys

I generated a public using java keygenerator:

Sun RSA public key, 1024 bits modulus: 106394877608018766537720801416655991345106535990850729605963854419450103716730599362154190537257597233014065015311499176359112816419965961469419756050290964343366687334245741905264407605904082573446954295309549250335299907317631410981650257400135070254491184426528002396792285738067623733919575203674519111607 public exponent: 65537

I sent this key from client side(via copy,paste) and received exactly exactly the same as a string. Then I tried to reconstruct it:

byte [] bytes = publicKey.getBytes("UTF-8");
Key key = KeyFactory.getInstance("RSA").generatePublic(new X509EncodedKeySpec(bytes));

Then I am returning from the function. I am getting Invalid Key Exception from line 2 where I form Key.

Any ideas?

Upvotes: 0

Views: 2369

Answers (1)

Dungeon Hunter
Dungeon Hunter

Reputation: 20603

You need to Use RSAPublicKeySpec

String modulus="106394877608018766537720801416655991345106535990850729605963854419450103716730599362154190537257597233014065015311499176359112816419965961469419756050290964343366687334245741905264407605904082573446954295309549250335299907317631410981650257400135070254491184426528002396792285738067623733919575203674519111607";
    RSAPublicKeySpec spec = new RSAPublicKeySpec(new BigInteger(modulus),BigInteger.valueOf(65537));

    Key key = KeyFactory.getInstance("RSA").generatePublic(spec);

Upvotes: 3

Related Questions