Class: XMLSecurity::SignedDocument

Inherits:
REXML::Document
  • Object
show all
Defined in:
lib/xml_security.rb

Instance Method Summary collapse

Instance Method Details

#validate(idp_cert_fingerprint, logger = nil) ⇒ Object



36
37
38
39
40
41
42
43
44
45
46
47
48
49
# File 'lib/xml_security.rb', line 36

def validate (idp_cert_fingerprint, logger = nil)
  # get cert from response
  base64_cert             = self.elements["//ds:X509Certificate"].text
  cert_text               = Base64.decode64(base64_cert)
  cert                    = OpenSSL::X509::Certificate.new(cert_text)

  # check cert matches registered idp cert
  fingerprint             = Digest::SHA1.hexdigest(cert.to_der)
  valid_flag              = fingerprint == idp_cert_fingerprint.gsub(":", "").downcase

  return valid_flag if !valid_flag

  validate_doc(base64_cert, logger)
end

#validate_doc(base64_cert, logger) ⇒ Object



51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
# File 'lib/xml_security.rb', line 51

def validate_doc(base64_cert, logger)
  # validate references

  # remove signature node
  sig_element = REXML::XPath.first(self, "//ds:Signature", {"ds"=>"http://www.w3.org/2000/09/xmldsig#"})
  sig_element.remove

  #check digests
  REXML::XPath.each(sig_element, "//ds:Reference", {"ds"=>"http://www.w3.org/2000/09/xmldsig#"}) do | ref |

    uri                   = ref.attributes.get_attribute("URI").value
    hashed_element        = REXML::XPath.first(self, "//[@ID='#{uri[1,uri.size]}']")
    canoner               = XML::Util::XmlCanonicalizer.new(false, true)
    canon_hashed_element  = canoner.canonicalize(hashed_element)
    hash                  = Base64.encode64(Digest::SHA1.digest(canon_hashed_element)).chomp
    digest_value          = REXML::XPath.first(ref, "//ds:DigestValue", {"ds"=>"http://www.w3.org/2000/09/xmldsig#"}).text

    valid_flag            = hash == digest_value

    return valid_flag if !valid_flag
  end

  # verify signature
  canoner                 = XML::Util::XmlCanonicalizer.new(false, true)
  signed_info_element     = REXML::XPath.first(sig_element, "//ds:SignedInfo", {"ds"=>"http://www.w3.org/2000/09/xmldsig#"})
  canon_string            = canoner.canonicalize(signed_info_element)

  base64_signature        = REXML::XPath.first(sig_element, "//ds:SignatureValue", {"ds"=>"http://www.w3.org/2000/09/xmldsig#"}).text
  signature               = Base64.decode64(base64_signature)

  # get certificate object
  cert_text               = Base64.decode64(base64_cert)
  cert                    = OpenSSL::X509::Certificate.new(cert_text)

  valid_flag              = cert.public_key.verify(OpenSSL::Digest::SHA1.new, signature, canon_string)

  return valid_flag
end