8

The two strings that are the private and public keys are :

    static String Public =          
       "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDH+wPrKYG1KVlzQUVtBghR8n9d" + "/n" +
     "zcShSZo0+3KgyVdOea7Ei7vQ1U4wRn1zlI5rSqHDzFitblmqnB2anzVvdQxLQ3Uq" + "/n" +
    "EBKBfMihnLgCSW8Xf7MCH+DSGHNvBg2xSNhcfEmnbLPLnbuz4ySn1UB0lH2eqxy5" + "/n"+
     "0zstxhTY0binD9Y+rwIDAQAB"+ "/n";
    static String Private = 
        "MIICxjBABgkqhkiG9w0BBQ0wMzAbBgkqhkiG9w0BBQwwDgQIr5NQ/LYPG/UCAggA" +"/n"+
      "MBQGCCqGSIb3DQMHBAiLh89iGSkmoASCAoBCpAo9/IzDE3yGhvWr9RgozE7revOo" +"/n"+
          "V2OXmU+d0+WYAAx2GYVaUCbFVrmgiVmrbiTgLUMXAGIpvxQ2rzyIvRHW/RN3Gcky" +"/n"+
        "qR/AwBatzixqrnoS4aD1/Ovjr4hwde4XHYbPEilZZuVAJFiznhy73qm/So4XghSY........." ;

I have read the other questions and tried their solutions but nothing worked....I have a public and private key both as strings.. I need to convert them to 'Key' but i keep getting java.security.spec.InvalidKeySpecException: java.security.InvalidKeyException ..at generatePublic and generatePrivate functions.. also the keys are just for testing therefore, it is ok if they are known to others...

      public static Key loadPublicKey(String stored) throws GeneralSecurityException, IOException 
       {
      byte[] data = Base64.getDecoder().decode((stored.getBytes()));
      X509EncodedKeySpec spec = new X509EncodedKeySpec(data);
      KeyFactory fact = KeyFactory.getInstance("RSA");
      return fact.generatePublic(spec);

        }


public static Key loadPrivateKey(String key64) throws     GeneralSecurityException, IOException {
        byte[] clear = Base64.getDecoder().decode(key64.getBytes());
        PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(clear);
        KeyFactory fact = KeyFactory.getInstance("RSA");
        PrivateKey priv = fact.generatePrivate(keySpec);
        Arrays.fill(clear, (byte) 0);
        return priv;

   }
Haya Raed
  • 5,921
  • 5
  • 16
  • 19
  • 4
    remove the line feed `+ "/n"` – Jens Apr 12 '17 at 14:14
  • still the same issue .. am getting java.security.spec.InvalidKeySpecException: java.security.InvalidKeyException: I changed the public key to :"MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDH+wPrKYG1KVlzQUVtBghR8n9dzcShSZo0+3KgyVdOea7Ei7vQ1U4wRn1zlI5rSqHDzFitblmqnB2anzVvdQxLQ3UqEBKBfMihnLgCSW8Xf7MCH+DSGHNvBg2xSNhcfEmnbLPLnbuz4ySn1UB0lH2eqxy50zstxhTY0binD9Y+rwIDAQAB" – Haya Raed Apr 12 '17 at 14:17
  • I have tried it by my own with the public key and it is working – Jens Apr 12 '17 at 14:19
  • 2
    Line feeds are `\n`, not `/n`. In a string, this would look like `"\\n"`. – Artjom B. Apr 12 '17 at 18:06
  • Necroed but for info: aside from the extraneous `/n`, your `Public` is indeed base64 of X.509-SPKI publickey suitable for Java `X509EncodedKeySpec`, but **your `Private` is (base64 of beginning of) an _encrypted_ PKCS8 private key** (EncryptedPrivateKeyInfo) while `PKCS8EncodedKeySpec` must be _unencrypted_ or here _decrypted_. If you have the password and (can) use BouncyCastle see https://stackoverflow.com/questions/49932334/how-read-a-pkcs8-encrypted-private-key-which-is-also-encoded-in-der-with-bouncyc otherwise it's rather complicated. – dave_thompson_085 Dec 17 '21 at 11:48

1 Answers1

8

Remove the line Feeds in the string declaration. That is not part of the key:

static String Public =          
       "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDH+wPrKYG1KVlzQUVtBghR8n9d" +
     "zcShSZo0+3KgyVdOea7Ei7vQ1U4wRn1zlI5rSqHDzFitblmqnB2anzVvdQxLQ3Uq" + 
    "EBKBfMihnLgCSW8Xf7MCH+DSGHNvBg2xSNhcfEmnbLPLnbuz4ySn1UB0lH2eqxy5" +
     "0zstxhTY0binD9Y+rwIDAQAB";
static String Private = 
        "MIICxjBABgkqhkiG9w0BBQ0wMzAbBgkqhkiG9w0BBQwwDgQIr5NQ/LYPG/UCAggA" +
      "MBQGCCqGSIb3DQMHBAiLh89iGSkmoASCAoBCpAo9/IzDE3yGhvWr9RgozE7revOo" +
          "V2OXmU+d0+WYAAx2GYVaUCbFVrmgiVmrbiTgLUMXAGIpvxQ2rzyIvRHW/RN3Gcky" +
        "qR/AwBatzixqrnoS4aD1/Ovjr4hwde4XHYbPEilZZuVAJFiznhy73qm/So4XghSY........." ;

I have tried it with the following code:

  public static void main(String[] args) throws GeneralSecurityException, IOException {
      System.out.println(loadPublicKey(Public));

  }

  public static Key loadPublicKey(String stored) throws GeneralSecurityException, IOException 
  {
 byte[] data = Base64.getDecoder().decode((stored.getBytes()));
 X509EncodedKeySpec spec = new X509EncodedKeySpec(data);
 KeyFactory fact = KeyFactory.getInstance("RSA");
 return fact.generatePublic(spec);

   }

And Output is:

Sun RSA public key, 1024 bits
  modulus: 140431102839105138202102866401190456107365606715815288536913018579006717438700259314092212104831553250527764925385527697411165705192297577022746989837839401358787285684108054389360182109284048524426941021357601686464156659759470495649944686235380003772357268264646549523784880655065600797504478771675703688879
  public exponent: 65537
Jens
  • 67,715
  • 15
  • 98
  • 113
  • @zaph it is a string of multiple lines .. it cannot be written as is ... unless it is all placed in one line – Haya Raed Apr 12 '17 at 14:21
  • @HayaRaed It can not be. I have tried it by my own with public key and no exception – Jens Apr 12 '17 at 14:22
  • @Jens really!! Why am I getting.... Exception in thread "main" java.security.spec.InvalidKeySpecException: java.security.InvalidKeyException: IOException : DER input, Integer tag error at sun.security.rsa.RSAKeyFactory.engineGeneratePrivate(Unknown Source) at java.security.KeyFactory.generatePrivate(Unknown Source) at Main.loadPrivateKey(Main.java:144) at Main.main(Main.java:185) Caused by: java.security.InvalidKeyException: IOException : DER input, Integer tag error at sun.security.pkcs.PKCS8Key.decode(Unknown Source) – Haya Raed Apr 12 '17 at 14:25
  • @HayaRaed You refer the private key part. I can not check it, because you have not shown it completly – Jens Apr 12 '17 at 14:27
  • Looks like it is a DER and not an RSA Key? – Jens Apr 12 '17 at 14:27
  • what should do for Load Private key – Navin Kumar Jun 06 '19 at 10:51