Search code examples
javawindowsencryptionjnadpapi

Decrypt Data which was encrypted with MS DPAPI with JNA


is it possible to decrypt data which was encrypted with MS DPAPI? For example i want to decrypt a digital certificate from the windows registry.

byte[] byteArray = (byte[]) Advapi32Util.registryGetValue(WinReg.HKEY_LOCAL_MACHINE, "SOFTWARE\\Microsoft\\SystemCertificates\\AuthRoot\\Certificates\\02FAF3E291435468607857694DF5E45B68851868", "Blob");

byte[] decrypted = Crypt32Util.cryptUnprotectData(byteArray);

String stringDecrypted = new String(decrypted);
System.out.println(stringDecrypted);

But i get an Win32 Exception: Exception in thread "main" com.sun.jna.platform.win32.Win32Exception: Data are invalid.

I don't found any information about this Exception. So what das this mean?? And could i decrypt these files like i want it or is it not possible?

Thnaks for help!


Solution

  • According to the MSDN documentation, you're missing six additional arguments to cryptUnprotectData.

    Even if these arguments are marked "optional", you still need to declare them in your interface method signature.

    UPDATE

    Based on the MSDN documentation:

    BOOL WINAPI CryptUnprotectData(
      _In_        DATA_BLOB *pDataIn,
      _Out_opt_   LPWSTR *ppszDataDescr,
      _In_opt_    DATA_BLOB *pOptionalEntropy,
      _Reserved_  PVOID pvReserved,
      _In_opt_    CRYPTPROTECT_PROMPTSTRUCT *pPromptStruct,
      _In_        DWORD dwFlags,
      _Out_       DATA_BLOB *pDataOut
    );
    

    The second, third, fourth, and fifth arguments can probably be null. The sixth argument can probably be zero. The final argument needs to be an appropriately allocated DATA_BLOB where the function can store its results (this structure is defined in JNA's platform.jar). Don't forget to free the DATA_BLOB's pbData field when you're done with it, passing its value to LocalFree.