Let's start Scheme

2012-04-20

簡易PEMファイルリーダー

とりあえずささっと作ってみた。X509証明書のみに対応という手抜きっぷり。
#!/usr/local/bin/sash

#< (sagittarius regex) >
(import (rnrs) (asn.1) (getopt)
 (sagittarius)
 (sagittarius regex)
 (sagittarius control)
 (rfc base64)
 (rfc x.509)
 (util file))

(define (read-content p end)
  (let loop ((line (get-line p))
      (r ""))
    (if (eof-object? line)
 (assertion-violation 'read-content "unexpected eof")
 (cond ((looking-at #/-----END (\w+)-----/i line)
        => (lambda (m)
      (unless (string=? (m 1) end)
        (assertion-violation 'read-content
        "invalid pem file"))
      r))
       (else
        (loop (get-line p)
       (string-append r line)))))))

(define (parse-pem-file in)
  (call-with-input-file in
    (lambda (p)
      (let loop ((line (get-line p)))
 (unless (eof-object? line)
   (cond ((looking-at #/-----BEGIN (\w+)-----/i line)
   => (lambda (m)
        ;; read until end comes
        (let1 base64 (base64-decode-string (read-content p (m 1))
        #f)
   (print (make-x509-certificate 
    (open-bytevector-input-port base64))))))
  (else
   (loop (get-line p)))))))))

(define (usage args)
  (format (current-error-port) "usage: ~a -i file~%" (car args))
  (exit -1))

(define (main args)
  (with-args args
      ((in (#\i "input") #t (usage args)))
    (parse-pem-file in)))
まぁ、使い捨てのスクリプトとしては短めに書ける方ではないだろうか。よく言えばこの辺りを処理をするライブラリがそろっていると。というか、そんなライブラリくらいしかないのだが。偏りが激しい。ちょっと手を入れれば、RSAの公開鍵と秘密鍵も読めるようになる。けど、今のところいらないので無視。

No comments:

Post a Comment