flashman
← All posts

PEM newline converter trim debugging

Debug PEM conversion when blank lines and indentation vanish, surrounding quotes are stripped separately, and a doubled backslash-n is only half undone.

2026-10-19 · 6 min read · Rahul Chitturi

  • pem
  • env
  • secrets

The PEM newline tool has two directions. Escape turns a key into one line joined by the two characters backslash and n. Restore turns those sequences back into line breaks. Neither direction checks that the text is a key. Both directions change more than the line breaks.

A block that looks the same in a viewer can still fail a checksum, or fail a parser, after a round trip. Diff the escaped line and the restored block against the file you started with.

Blank lines and indentation are removed

Escape first turns CRLF and bare CR into LF, trims the whole value, trims each line, drops lines that are empty after that trim, and joins the survivors with a literal backslash-n. A blank line between the body and the END line is deleted. Spaces before ABC and spaces after DEF are deleted. A line that contains only spaces is deleted.

The sample with a Windows line ending, an indented body line, a blank line, and a padded next line comes back as four segments: the BEGIN line, ABC, DEF, and the END line. The body text ABCDEF is intact only because those letters were the whole trimmed lines. A checksum of the original PEM text will not match.

  • Diff the restored PEM against the file you pasted.
  • Expect a blank line before END to disappear.
  • Expect leading spaces and tabs on a line to disappear.
  • Do not use the escaped form as a byte-for-byte backup.

Quotes are stripped from both ends independently

Restore trims, then removes one leading quote and one trailing quote if they are present. The quotes do not have to match. The text "abc' loses both the double quote and the apostrophe and becomes abc. A matching pair "abc" also becomes abc, which is what you want for one layer of .env quotes.

The combined escape output wraps each key as PUBLIC_KEY="..." or PRIVATE_KEY="...". A body that already contains a double quote is not escaped. Escape of a line A "quote" followed by a newline and B is the characters A "quote" then backslash-n then B. Putting that inside another pair of double quotes breaks the env line.

A doubled escape is only half undone

Restore replaces the four characters backslash, r, backslash, n with a newline first, then replaces backslash-n. A doubled backslash before n, written as two backslashes and an n, becomes one backslash and a newline. The second backslash was the one that formed the escape. The first backslash remains.

Use the PEM tool to move a development key into a single env line, the JWT tool only with a PKCS#8 block you are willing to discard, and diff on the round trip. The Base64 tool is for a separate text encoding, not for this newline pass. Keep production key material out of both pages.

Try these tools