Skip to Main Content

Java Programming

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

RSA Encryption in JAVA

imation3mFeb 10 2017 — edited Feb 15 2017

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?

Comments
Locked Post
New comments cannot be posted to this locked post.
Post Details
Locked on Mar 15 2017
Added on Feb 10 2017
7 comments
1,919 views