0

I have a private key in .pem format. The contents start with "BEGIN RSA Private Key" and is ASCII armored.

I need to use this key in the object of Signature but it throws an error stating Invalid Key format. Please help!

package com.scb;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.security.KeyFactory;
import java.security.Signature;
import java.security.spec.PKCS8EncodedKeySpec;
import java.util.Base64;

public class Dec {

public static void main(String[] args) {
    

    String input = "hello";
    try {

     //Capturing the key file
     byte[] keyBytes = Files.readAllBytes(Paths.get("C:\\Users\\note3\\Desktop\\Key pair\\0x719D855F-sec.asc"));

        PKCS8EncodedKeySpec spec =
          new PKCS8EncodedKeySpec(keyBytes);

        KeyFactory kf = KeyFactory.getInstance("RSA");

        Signature privateSignature = Signature.getInstance("SHA256withRSA");
        privateSignature.initSign(kf.generatePrivate(spec));
        privateSignature.update(input.getBytes("UTF-8"));
        byte[] s = privateSignature.sign();
        System.out.println(Base64.getEncoder().encodeToString(s));
    }
    catch(Exception e) {
        e.printStackTrace();
    }
}}

Error Screenshot

Tobito
  • 3
  • 1
  • EDIT : The .asc file in the code is just a test case. The actual file I am using to get the Private key is in .pem format – Tobito Jul 27 '21 at 14:13
  • 1
    The first line "BEGIN RSA Private Key" in your PEM keyfile directs to a RSA key that is encoded in PKCS#1 encoding. For now you have two choices: a) convert the private key e.g. with openssl to PKCS8-encoded form (which would be good for a one time conversion) and use it in the way of stripping-off the header and footer line and decode it with a Base64 decoder of your choice. The second option wood be to use a library like e.g. Bouncy Castle that could consume such a file without any further conversions. – Michael Fehr Jul 27 '21 at 15:03
  • 1
    Your private key has the PKCS#1 format and `PKCS8EncodedKeySpec` expects the PKCS#8 format. There are several solutions, here are two: Convert the key online (see e.g. [here](https://8gwifi.org/pemconvert.jsp)), or import the key in PKCS#1 format, e.g. with _BouncyCastle_, (see e.g. [here](https://stackoverflow.com/a/41953072)). – Topaco Jul 27 '21 at 15:03

0 Answers0