Opening and checking a Pem file in SWI-Prolog

◇◆丶佛笑我妖孽 提交于 2019-12-10 17:14:50

问题


How do I open a Pem file to check a) That the 'Not before' and 'Not after' dates are okay and b) That there is a chain of certs in the pem file to a route certificate authority?

I have tried:

:-use_module(library(http/http_client)).

url('http://fm4dd.com/openssl/source/PEM/certs/512b-rsa-example-cert.pem').

url_data(Url,D):-
 http_get(Url,D,[to(string)]).

url_data1(Url,Certificate):-
 http_get(Url,D,[to(stream(Stream))]),
 load_certificate(Stream, Certificate),
 close(Stream).

url_data/1 works in that it returns the pem file as a string. But url_data1/1 does not work. It is intended to return each certificate(s) as a list of terms.

* Update *

I have:

url_data1(Url,Certs):-
 http_open(Url,Stream,[]),
 all_certs(Stream,Certs),
 forall(member(C,Certs),my_validate(C)),
 close(Stream).

all_certs(Stream,[C1|Certs]):-
 catch(load_certificate(Stream,C1),_,fail),
 all_certs(Stream,Certs),!.
all_certs(_Stream,[]).

my_validate(C):-
 memberchk(to_be_signed(Signed),C),
 memberchk(key(Key),C),
 memberchk(signature(Signature),C),
 memberchk(signature_algorithm(A),C),
 algo_code(A,Code),
 rsa_verify(Key,Signed,Signature,[type(Code)]).

algo_code('RSA-SHA256',sha256).
algo_code('RSA-SHA1',sha1).

Which fails. What are the correct arguments?


回答1:


You can use http_open/3 in combination with load_certificate/2:

?- url(Url),
   http_open(Url, Stream, []),
   load_certificate(Stream, Certificate),
   maplist(portray_clause, Certificate).

Yielding:

version(0).
notbefore(1345613214).
notafter(1503293214).
serial('0DFA').
subject(['C'='JP', 'ST'='Tokyo', 'O'='Frank4DD', 'CN'='www.example.com']).
hash("071CB94F0CC8514D024124708EE8B2687BD7D9D5").
signature("14B64CBB817933E671A4DA516FCB081D8D60ECBC18C7734759B1F22048BB61FAFC4DAD898DD121EBD5D8E5BAD6A636FD745083B60FC71DDF7DE52E817F45E09FE23E79EED73031C72072D9582E2AFE125A3445A119087C89475F4A95BE23214A5372DA2A052F2EC970F65BFAFDDFB431B2C14A9C062543A1E6B41E7F869B1640").
signature_algorithm('RSA-SHA1').
etc.

Check the issuer_name/1 element to obtain the issuer. You can use load_certificate/2 again to read further certificates from the file.

Note that a much more typical way to validate the certificate chain is to establish a secure connection (via HTTPS), and then to use ssl_peer_certificate/2 or ssl_peer_certificate_chain/2 on the stream to obtain the peer certificate and certificate chain.

To validate the chain, you must verify the signature/1 fields, which contain the digital signatures of the to_be_signed/1 portions of the certificate, signed by the respective issuer.

You can use library(crypto) to verify the signatures.



来源:https://stackoverflow.com/questions/44497172/opening-and-checking-a-pem-file-in-swi-prolog

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!