Search code examples
phpopensslphp-openssl

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?


Solution

  • 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