Question

I've been fighting with this issue for a while now. The matter is that I have to send a PEM string to a server, which expects the final step of the following:

  • An encryption key of type 3DES o AES-256.
  • That key, encrypted with an RSA key.
  • That output, encoded in Base64 and in PEM format.

Here's what I got so far:

  • Based on the RSA key I've got from the server, I create a Cipher:

     Cipher rsa = Cipher.getInstance("RSA");
    
     rsa.init(Cipher.ENCRYPT_MODE, (RSAPublicKey) obj);
    
  • Later, I create an AES key:

    //IV. 
    byte[] bytes = new byte[16];
    SecureRandom random = new SecureRandom();
    random.nextBytes(bytes);
    
    Map<String, byte[]> aes = new HashMap<String, byte[]>();
    
    aes.put("IV", ConversionUtil.toHex(bytes, 8).getBytes());
    
    KeyGenerator keyGen = KeyGenerator.getInstance("AES");
    
    keyGen.init(256);
    Key encryptionKey = keyGen.generateKey();
    
    Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding"); 
    
    cipher.init(Cipher.ENCRYPT_MODE, encryptionKey, new IvParameterSpec(ConversionUtil.toHex(bytes, 8).getBytes()));
    
    aes.put("key", cipher.doFinal(encryptionKey.getEncoded()));
    

Use all that to create the PEM string:

            StringBuilder sb = new StringBuilder();
            sb.append(StringUtils.repeat("-", 5));
            sb.append("BEGIN PEM file");
            sb.append(StringUtils.repeat("-", 5));
            sb.append("\n");

            sb.append("Proc-Type: 4,ENCRYPTED\n");
            sb.append("DEK-Info: " + "AES-256-CBC" + "," + new String(aes.get("IV")) + "\n");
            sb.append("");
            sb.append(Base64.encode(rsa.doFinal(aes.get("key"))));

            sb.append("\n");
            sb.append(StringUtils.repeat("-", 5));
            sb.append("END PEM file");
            sb.append(StringUtils.repeat("-", 5));

And then send that out to the server, which throws the following error:

3936:error:0906D06C:PEM routines:PEM_read_bio:no start line:.\crypto\pem\pem_lib.c:698:

I don't have much more visibility of the error, but I wanted to check if there's anything wrong I might be doing in the process, as it seems that error is associated to the unrecognition of the PEM.

Let me know if you have any questions.

Thanks!

Was it helpful?

Solution

The specific error is reported because there should be no spaces between the dashes and the BEGIN statement. I don't know about the other issues, but it seems you have some work ahead of you to match the exact input requirements. Make sure you understand precisely what is expected, or you may have to try different formats "ad nauseam".

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top