0

I'm importing RSA key from a folder and using it to generate signature. but its giving me following error.

Exception in thread "main" java.security.spec.InvalidKeySpecException: java.security.InvalidKeyException: IOException : algid parse error, not a sequence

following is the code for generating signature

public class GenerateSignature {
    public String getSignature(String msg) {
        
        HexString hs = new HexString();
        
          
        byte[] signature = null;
        try {
            PrivateKeyLoader loader = new PrivateKeyLoader();
            //put pertinent address
            PrivateKey key = loader.load("rsakey2.pem");
          
            System.out.println(key);
          
            Signature sign = Signature.getInstance("SHA256withRSA");
            sign.initSign(key);
            byte[] bytes = msg.getBytes();
            sign.update(bytes);
            signature = sign.sign();
        }
        catch (Exception e) {
            System.out.println(e); // this is where i got the error
                       //i think loader.load wasnt able to load the key.
        }
        return hs.toHexString(signature);
    }

}

following is the code for loading private key

public class PrivateKeyLoader {
    private String readFile(final String fileName) throws IOException {
        final File file = new File(fileName);

        return new String(Files.readAllBytes(file.toPath()));
    }
    
    private PrivateKey loadPemRsaPrivateKey(String pemFilename) throws Exception {

        String pemString = readFile(pemFilename);

        String privateKeyPEM = pemString
                .replace("-----BEGIN RSA PRIVATE KEY-----", "")
                .replaceAll(System.lineSeparator(), "")
                .replace("-----END RSA PRIVATE KEY-----", "");

        byte[] encoded = Base64.getDecoder().decode(privateKeyPEM);

        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(encoded);
        return keyFactory.generatePrivate(keySpec);
    }

    public PrivateKey load(String file) throws Exception {
        return loadPemRsaPrivateKey(file);
    }

}
Bhuvan M
  • 3
  • 2
  • The text `BEGIN/END RSA PRIVATE KEY` in the header/footer points to a private key in PKCS#1 format. However, `PKCS8EncodedKeySpec` requires a private key in PKCS#8 format. – Topaco Mar 01 '23 at 13:37
  • @Topaco Yes, the private key is in PKCS#1 format. So what's the appropriate alternative for PKCS8EncodedKeySpex ?. Could you write the alternative code if possible? – Bhuvan M Mar 01 '23 at 14:06
  • 1
    You can directly import a PEM encoded PKCS#1 key with BouncyCastle, see [here](https://stackoverflow.com/a/41953072). Alternatively the PKCS#1 key can be converted to a PKCS#8 key e.g. with OpenSSL. – Topaco Mar 01 '23 at 14:23

0 Answers0