apple / swift-asn1

An implementation of ASN.1 for Swift
https://swiftpackageindex.com/apple/swift-asn1/main/documentation/swiftasn1
Apache License 2.0
137 stars 25 forks source link

`PEMDocument(pemString:)` does not support Windows line endings #66

Open natevw opened 1 month ago

natevw commented 1 month ago

When initializing a PEMDocument (or in my case really a swift-certificates Certificate) via a pemString: which comes from a Windows-world service, an error is thrown that it "could not find PEM start marker". The same string piped to openssl x509 is recognized successfully.

I believe the problem is that https://github.com/apple/swift-asn1/blob/60b2af8382fab55e76bb57eb36cf77bf1a239838/Sources/SwiftASN1/Basic%20ASN1%20Types/PEMDocument.swift#L232-L239 looks only for a suffix of specifically "-----\n" and thus does not match on what in my case is "-----\r\n". (There may be more "\n"-dependent logic beyond that point but this is the source of the initial failure.)

The workaround I'm using is to pass in myPemString.replacingOccurences(of: "\r\n", with: "\n") but it would be nice if these libraries could handle line breaks more generically. I'm not sure if this is the most relevant standard but RFC 1421 says:

To represent the encapsulated text of a PEM message, the encoding function's output is delimited into text lines (using local conventions) […]

which I suppose could be argued that the PEM document conventions could to be local to the receiver but in this case my PEM document is using the "local conventions" of the sender :-)

Lukasa commented 1 month ago

Thanks for this @natevw! This is a good catch.

I'd like to avoid replacingOccurences(of:with:) here, but updating our parsing logic to handle windows newlines would be very valuable.