I am calling a SOAP Webservice to fetch the public key in the form of byte[] .
I want to encrypt some input text with this public key using RSA Encryption in java.
I am using the below class:
public class CryptographyUtil {
private static final String ALGORITHM = "RSA";
public static byte[] encrypt(byte[] publicKey, byte[] inputData)
throws Exception {
PublicKey key = KeyFactory.getInstance(ALGORITHM).generatePublic(new X509EncodedKeySpec(publicKey));
Cipher cipher = Cipher.getInstance(ALGORITHM);
cipher.init(Cipher.PUBLIC_KEY, key);
byte[] encryptedBytes = cipher.doFinal(inputData);
return encryptedBytes;
}
}
I am calling the above:
String text = "1234";
byte[] c = CryptographyUtil.encrypt(publickKey.getBytes(), text.getBytes() );
But i am getting the below exception
java.security.spec.InvalidKeySpecException: java.security.InvalidKeyException: invalid key format
at sun.security.rsa.RSAKeyFactory.engineGeneratePublic(RSAKeyFactory.java:188)
How can i resolve this?