0

So I have been stuck at this for a week. I want to perform a very basic RSA encryption using Java libraries. Here's my code:

package com.company;
import java.util.Base64;
import java.security.*;
import java.security.spec.X509EncodedKeySpec;
import javax.crypto.Cipher;

public class Main
{
    public static void main(String[] args) throws Exception
    {
        System.out.println("Encryption process started...");
        //Next Line Explanation: "Bytes" is a class developed by me and for this case, its behaviour is verified.
        byte[] rawData = Bytes.fromHexString("ec5ac9830817ED48941A08F98100000004494C553B00000004539110730000003E0549828CCA27E966B301A48FECE2FCA5CF4D33F4A11EA877BA4AA573907330311C85DB234AA2640AFC4A76A735CF5B1F0FD68BD17FA181E1229AD867CC024D").toPbytes();
        System.out.println("Bytes to encrypt:");
        System.out.println(new Bytes(rawData).toString());
        final String RSA_PUBLIC_KEY = "-----BEGIN RSA PUBLIC KEY-----" +
                "MIIBCgKCAQEAwVACPi9w23mF3tBkdZz+zwrzKOaaQdr01vAbU4E1pvkfj4sqDsm6" +
                "lyDONS789sVoD/xCS9Y0hkkC3gtL1tSfTlgCMOOul9lcixlEKzwKENj1Yz/s7daS" +
                "an9tqw3bfUV/nqgbhGX81v/+7RFAEd+RwFnK7a+XYl9sluzHRyVVaTTveB2GazTw" +
                "Efzk2DWgkBluml8OREmvfraX3bkHZJTKX4EQSjBbbdJ2ZXIsRrYOXfaA+xayEGB+" +
                "8hdlLmAjbCVfaigxX0CDqWeR1yFL9kwd9P0NsZRPsmoqVwMbMu7mStFai6aIhc3n" +
                "Slv8kg9qv1m6XHVQY3PnEw+QQtqSIXklHwIDAQAB" +
                "-----END RSA PUBLIC KEY-----";
        byte[] rsaPublicKeyBytes = Base64.getDecoder().decode(RSA_PUBLIC_KEY);
        X509EncodedKeySpec x509EncodedKeySpec = new X509EncodedKeySpec(rsaPublicKeyBytes);
        PublicKey publicKey = KeyFactory.getInstance("RSA").generatePublic(x509EncodedKeySpec);
        Cipher cipher = Cipher.getInstance("RSA");
        cipher.init(Cipher.ENCRYPT_MODE, publicKey);
        byte[] encryptedData = cipher.doFinal(rawData);
        System.out.println(new Bytes(encryptedData).toString());
    }
}

Running this I get:

Encryption process started...
Bytes to encrypt:


EC  5A  C9  83  08  17  ED  48  
94  1A  08  F9  81  00  00  00  
04  49  4C  55  3B  00  00  00  
04  53  91  10  73  00  00  00  
3E  05  49  82  8C  CA  27  E9  
66  B3  01  A4  8F  EC  E2  FC  
A5  CF  4D  33  F4  A1  1E  A8  
77  BA  4A  A5  73  90  73  30  
31  1C  85  DB  23  4A  A2  64  
0A  FC  4A  76  A7  35  CF  5B  
1F  0F  D6  8B  D1  7F  A1  81  
E1  22  9A  D8  67  CC  02  4D  

Exception in thread "main" java.lang.IllegalArgumentException: Illegal base64 character 2d
    at java.util.Base64$Decoder.decode0(Base64.java:714)
    at java.util.Base64$Decoder.decode(Base64.java:526)
    at java.util.Base64$Decoder.decode(Base64.java:549)

After getting this exception, I thought that this may be caused by the key string having illegal characters in the header. So I removed the header:

        final String RSA_PUBLIC_KEY = "" +
            "MIIBCgKCAQEAwVACPi9w23mF3tBkdZz+zwrzKOaaQdr01vAbU4E1pvkfj4sqDsm6" +
            "lyDONS789sVoD/xCS9Y0hkkC3gtL1tSfTlgCMOOul9lcixlEKzwKENj1Yz/s7daS" +
            "an9tqw3bfUV/nqgbhGX81v/+7RFAEd+RwFnK7a+XYl9sluzHRyVVaTTveB2GazTw" +
            "Efzk2DWgkBluml8OREmvfraX3bkHZJTKX4EQSjBbbdJ2ZXIsRrYOXfaA+xayEGB+" +
            "8hdlLmAjbCVfaigxX0CDqWeR1yFL9kwd9P0NsZRPsmoqVwMbMu7mStFai6aIhc3n" +
            "Slv8kg9qv1m6XHVQY3PnEw+QQtqSIXklHwIDAQAB" +
            "";

Trying this code I get:

Encryption process started...
Bytes to encrypt:


EC  5A  C9  83  08  17  ED  48  
94  1A  08  F9  81  00  00  00  
04  49  4C  55  3B  00  00  00  
04  53  91  10  73  00  00  00  
3E  05  49  82  8C  CA  27  E9  
66  B3  01  A4  8F  EC  E2  FC  
A5  CF  4D  33  F4  A1  1E  A8  
77  BA  4A  A5  73  90  73  30  
31  1C  85  DB  23  4A  A2  64  
0A  FC  4A  76  A7  35  CF  5B  
1F  0F  D6  8B  D1  7F  A1  81  
E1  22  9A  D8  67  CC  02  4D  

Exception in thread "main" java.security.spec.InvalidKeySpecException: java.security.InvalidKeyException: IOException: algid parse error, not a sequence
    at sun.security.rsa.RSAKeyFactory.engineGeneratePublic(RSAKeyFactory.java:205)
    at java.security.KeyFactory.generatePublic(KeyFactory.java:334)
    at com.company.Main.main(Main.java:26)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:483)
    at com.intellij.rt.execution.application.AppMain.main(AppMain.java:147)
Caused by: java.security.InvalidKeyException: IOException: algid parse error, not a sequence
    at sun.security.x509.X509Key.decode(X509Key.java:398)
    at sun.security.x509.X509Key.decode(X509Key.java:403)
    at sun.security.rsa.RSAPublicKeyImpl.<init>(RSAPublicKeyImpl.java:84)
    at sun.security.rsa.RSAKeyFactory.generatePublic(RSAKeyFactory.java:298)
    at sun.security.rsa.RSAKeyFactory.engineGeneratePublic(RSAKeyFactory.java:201)
    ... 7 more

I searched the web a lot, and tried some changes to the code but didn't find a workaround for this. So I think I had to ask this question.

Edit:

This question has been marked as duplicate. However I had already seen that thread and if you notice, my code is exactly the same as the code provided in the second answer.

Community
  • 1
  • 1
Mostafa Farzán
  • 899
  • 2
  • 11
  • 30
  • Why do you have the Base64-decoding step? Did you try it without (`string.getBytes("UTF-8")` instead)? – Artjom B. Mar 19 '17 at 13:24
  • I've adjusted my answer on an earlier question that is based on the same problem. Please check if this is what you needed and comment here if it is not. I'm partial to reopening this question if you indicate that the other *question* doesn't cover your issue. – Maarten Bodewes Mar 19 '17 at 13:27
  • @MaartenBodewes I had already seen the post. I preferred to follow the non-3rd-party approach provided in the second answer, but I can't get that implementation to work. I'll definitely appreciate a 3rd party approach iff it can't be done using native libraries. – Mostafa Farzán Mar 19 '17 at 13:38
  • That second answer is wrong. You can't do it that way. Read @MaartenBodewes answer which is correct. – President James K. Polk Mar 19 '17 at 14:15
  • The ASN.1 decoder link was very useful, as I used it to simply decompose the key into Modulus and Public Exponent, and create an RSAPublicKeySpec. This resolved my problem, and I still don't need a third party library :) – Mostafa Farzán Mar 19 '17 at 15:25

0 Answers0