Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Validating that an uploaded file is a valid PEM file

I'm trying to figure out an effective/elegant way to validate that a user uploaded file is a valid pem file without relying on validating the extension. Anyone accomplish this or have any ideas?

like image 544
Mike Keen Avatar asked Apr 28 '15 15:04

Mike Keen


People also ask

What is PEM format for certificate?

PEM stands for Privacy Enhanced Mail. The PEM format is often used to represent certificates, certificate requests, certificate chains, and keys.

What type of file extension is PEM?

Privacy Enhanced Mail (PEM) files are a type of Public Key Infrastructure (PKI) file used for keys and certificates. PEM, initially invented to make e-mail secure, is now an Internet security standard.


1 Answers

Use "openssl rsa" and parse its output

Wrong file:

$ openssl rsa -noout -modulus -in ./wrong.pem 
unable to load Private Key

140324790638432:error:0906D06C:PEM routines:PEM_read_bio:no start line:pem_lib.c:703:Expecting: ANY PRIVATE KEY

Proper key

$ openssl rsa -noout -modulus -in ../proper.pem
Modulus=98B139C27E3623E542CEC76ECEA0619D045746B2F99265F030391296C5DD83301A85C43A00C745DAB77DFC771CE5666CF81ED81C4561F945EF123D5CB5687500A243E1F87B707FFFC318EA8E9605B2047E2D790BB71B9AF04F385C2E40C18A40FE5FB5CBC96C0C05D4220E5C73564027C6CB0DEEDB8AD8460B78A54536ADB81D204FDDFDB388F6EEFD537E6C3D743A9C9C2FE00D9A819A9587EE359DAA48AD08FC06D99D8686C38B0BD684CC41F0B61115F65B005C53F472D648C2EB92AAFC6526E7F4FFE873FB0C3589C24CCCCA1DCA08B352F9893310F876C007E72B809FAB6738855C5C901C8C006E9E137BF340E8A6E204FC70864AE29D9009DC9CBBEAD9

so you can wrap openssl execution to shell_exec(),parse output and check for "unable to load Private Key" to detect wrong certificate

like image 84
Evgeniy Kuzmin Avatar answered Oct 27 '22 00:10

Evgeniy Kuzmin