Skip to main content
Vivian Furtado a posé une question dans #MuleSoft DataWeave

Hey Team,

​

I have a requirement where I need to pass the JKS file to dataweave to generate a token. I can read the .pem file using readUrl function but cannot read jks file.

 

We are using the dataweave component DataWeave JWT Library - RSA (mulesoft.com) to generate the token. Currently working fine with .pem file,

​

​

Any help would be greatly appreciated.

​

4 réponses
  1. 8 févr. 2024, 06:30

    As you dont need to use Java utils specifically , then you can convert the JSK to .PEM and then us that segment. As you already mention .PEM is working fine. I can share some step for converting JSK to .PEM and then reading in mule setup.

     

    Step 1: Convert JKS to PEM

    You'll need to extract the private key and certificate from the JKS keystore and convert them to PEM format. This step is done outside of MuleSoft, typically using the

    'keytool' and 'openssl'

    command-line tools. Here's how you can do it:

    1) Export the private key and certificate from the JKS:

    keytool -importkeystore -srckeystore [your-keystore-file.jks] -destkeystore [keystore.p12] -deststoretype PKCS12 -srcalias [your-alias] -deststorepass [dest-password] -destkeypass [dest-key-password]

     

    2) Export the certificate to a PEM file:

    openssl pkcs12 -in [keystore.p12] -nokeys -out [certificate.pem] -password pass:[dest-password]

     

    3) Export the private key to a PEM file:

    openssl pkcs12 -in [keystore.p12] -nocerts -out [key.pem] -password pass:[dest-password] -nodes

     

    Replace [your-keystore-file.jks] , [your-alias] , [dest-password] , [dest-key-password] , [keystore.p12] , [certificate.pem] , and [key.pem] with appropriate values for your use case.

     

    Step 2: Use PEM File in DataWeave

    Once you have your PEM files, you can use them in your existing DataWeave script for JWT token generation. Assuming you are using the DataWeave JWT Library, your DataWeave script would look something like this:

     

    %dw 2.0

    import * from dw::Crypto

    output application/json

    ---

    {

      // JWT Header

      "alg": "RS256",

      "typ": "JWT"

    },

    {

      // JWT Payload

      "sub": "1234567890",

      "name": "John Doe",

      "iat": now() as Number {unit: "seconds"},

      "exp": (now() + |PT1H|) as Number {unit: "seconds"}

    },

    {

      // Read the private key from PEM file

      "key" : readUrl("classpath://path/to/your/key.pem", "application/pem")

    }

    as String {format: "application/jwt"}

     

    This script assumes that you have the private key PEM file (key.pem) accessible within your MuleSoft application, probably stored in the src/main/resources directory.

     

    Let me know if this can help you a bit.

     

    Source of information : Personal Experience + Chatgpt