skip to Main Content

I have the key -----BEGIN PRIVATE KEY-----nnwb945yptghjs8hg45954hg945hn/gsnohuoi5gh549usgh5498gh4p95sognosgn54ui3ghns459uigh54g98s45ghy4598ngkeot84n-----END PRIVATE KEY----- (for illustration purposes) and when running jws.sign() on my home computer it works as expected.

However, when I store the secret in AWS Secrets Manager and retrieve it in a container on EC2, even after confirming (by logging it) that it looks the exact same way, I get a Could not deserialize key data error, or more specifically InvalidData(InvalidByte(0, 92)).

Byte 92 is the "" character, so the issue seems to lie in Jose treating the "n" as literals instead of new lines for some reason. How do I fix that?

2

Answers


  1. Chosen as BEST ANSWER

    What was suggested fixed that specific issue, but I kept getting failure to deserialize errors, despite it working fine retrieving and using the same key on my local PC. What ended up fixing it is replacing new lines with spaces when storing it in AWS and then re-building it programmatically, like so

    f"-----BEGIN PRIVATE KEY-----n{secrets.PRIVATE_KEY.replace(" ", "n")}n-----END PRIVATE KEY-----"
    

    Still don't know what could cause such an issue but this works.


  2. Reason is newline characters (n) being treated as literal strings instead of actual line breaks when retrieved from AWS Secrets Manager. This can happen because AWS Secrets Manager stores the secret as a single string, which may cause the newline characters to be escaped.

    One possible solution is to replace the literal n characters with actual newline characters after retrieving the secret and before using it with jws.sign()

    # Retrieve the key from AWS Secrets Manager
    retrieved_key = secret_manager.get_secret_value(...)  # Replace with your actual retrieval code
    
    # Replace literal 'n' with actual newlines
    formatted_key = retrieved_key.replace('\n', 'n')
    

    OR you can also use "formatted_key" when signing your data

    # Use the formatted key with jws.sign()
    signature = jws.sign(data, formatted_key, algorithm='RS256')
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search