java.lang.Object
org.codelibs.saml2.core.util.Util

public final class Util extends Object
Util class of Java Toolkit. A class that contains several auxiliary methods related to the SAML protocol
  • Field Details

  • Method Details

    • isJaxp15Supported

      public static boolean isJaxp15Supported()
      Method which uses the recommended way ( https://docs.oracle.com/javase/tutorial/jaxp/properties/error.html ) of checking if JAXP is equal or greater than 1.5 options are supported. Needed if the project which uses this library also has Xerces in it's classpath. If for whatever reason this method cannot determine if JAXP 1.5 properties are supported it will indicate the options are supported. This way we don't accidentally disable configuration options.
      Returns:
    • loadXML

      public static Document loadXML(String xml)
      This function load an XML string in a save way. Prevent XEE/XXE Attacks
      Parameters:
      xml - String. The XML string to be loaded.
      Returns:
      The result of load the XML at the Document or null if any error occurs
    • query

      public static NodeList query(Document dom, String query, Node context)
      Extracts a node from the DOMDocument
      Parameters:
      dom - The DOMDocument
      query - Xpath Expression
      context - Context Node (DomElement)
      Returns:
      DOMNodeList The queried node
    • query

      public static NodeList query(Document dom, String query)
      Extracts a node from the DOMDocument
      Parameters:
      dom - The DOMDocument
      query - Xpath Expression
      Returns:
      DOMNodeList The queried node
    • validateXML

      public static boolean validateXML(Document xmlDocument, URL schemaUrl)
      This function attempts to validate an XML against the specified schema.
      Parameters:
      xmlDocument - The XML document which should be validated
      schemaUrl - The schema filename which should be used
      Returns:
      found errors after validation
    • convertStringToDocument

      public static Document convertStringToDocument(String xmlStr)
      Converts an XML in string format in a Document object
      Parameters:
      xmlStr - The XML string which should be converted
      Returns:
      the Document object
    • parseXML

      public static Document parseXML(InputSource inputSource)
      Parse an XML from input source to a Document object
      Parameters:
      inputSource - The InputSource with the XML string which should be converted
      Returns:
      the Document object
    • convertDocumentToString

      public static String convertDocumentToString(Document doc, boolean c14n)
      Converts an XML in Document format in a String
      Parameters:
      doc - The Document object
      c14n - If c14n transformation should be applied
      Returns:
      the Document object
    • convertDocumentToString

      public static String convertDocumentToString(Document doc)
      Converts an XML in Document format in a String without applying the c14n transformation
      Parameters:
      doc - The Document object
      Returns:
      the Document object
    • formatCert

      public static String formatCert(String cert, boolean heads)
      Returns a certificate in String format (adding header and footer if required)
      Parameters:
      cert - A x509 unformatted cert
      heads - True if we want to include head and footer
      Returns:
      X509Certificate $x509 Formated cert
    • formatPrivateKey

      public static String formatPrivateKey(String key, boolean heads)
      Returns a private key (adding header and footer if required).
      Parameters:
      key - A private key
      heads - True if we want to include head and footer
      Returns:
      Formated private key
    • loadCert

      public static X509Certificate loadCert(String certString)
      Load X.509 certificate
      Parameters:
      certString - certificate in string format
      Returns:
      Loaded Certificate. X509Certificate object
    • loadPrivateKey

      public static PrivateKey loadPrivateKey(String keyString)
      Load private key
      Parameters:
      keyString - private key in string format
      Returns:
      Loaded private key. PrivateKey object
    • calculateX509Fingerprint

      public static String calculateX509Fingerprint(X509Certificate x509cert, String alg)
      Calculates the fingerprint of a x509cert
      Parameters:
      x509cert - x509 certificate
      alg - Digest Algorithm
      Returns:
      the formated fingerprint
    • calculateX509Fingerprint

      public static String calculateX509Fingerprint(X509Certificate x509cert)
      Calculates the SHA-1 fingerprint of a x509cert
      Parameters:
      x509cert - x509 certificate
      Returns:
      the SHA-1 formated fingerprint
    • convertToPem

      public static String convertToPem(X509Certificate certificate)
      Converts an X509Certificate in a well formated PEM string
      Parameters:
      certificate - The public certificate
      Returns:
      the formated PEM string
    • getFileAsString

      public static String getFileAsString(String relativeResourcePath)
      Loads a resource located at a relative path
      Parameters:
      relativeResourcePath - Relative path of the resource
      Returns:
      the loaded resource in String format
    • base64decodedInflated

      public static String base64decodedInflated(String input)
      Returns String Base64 decoded and inflated
      Parameters:
      input - String input
      Returns:
      the base64 decoded and inflated string
    • deflatedBase64encoded

      public static String deflatedBase64encoded(String input)
      Returns String Deflated and base64 encoded
      Parameters:
      input - String input
      Returns:
      the deflated and base64 encoded string
    • base64encoder

      public static String base64encoder(byte[] input)
      Returns String base64 encoded
      Parameters:
      input - Stream input
      Returns:
      the base64 encoded string
    • base64encoder

      public static String base64encoder(String input)
      Returns String base64 encoded
      Parameters:
      input - String input
      Returns:
      the base64 encoded string
    • base64decoder

      public static byte[] base64decoder(byte[] input)
      Returns String base64 decoded
      Parameters:
      input - Stream input
      Returns:
      the base64 decoded bytes
    • base64decoder

      public static byte[] base64decoder(String input)
      Returns String base64 decoded
      Parameters:
      input - String input
      Returns:
      the base64 decoded bytes
    • urlEncoder

      public static String urlEncoder(String input)
      Returns String URL encoded
      Parameters:
      input - String input
      Returns:
      the URL encoded string
    • urlDecoder

      public static String urlDecoder(String input)
      Returns String URL decoded
      Parameters:
      input - URL encoded input
      Returns:
      the URL decoded string
    • sign

      public static byte[] sign(String text, PrivateKey key, String signAlgorithm)
      Generates a signature from a string
      Parameters:
      text - The string we should sign
      key - The private key to sign the string
      signAlgorithm - Signature algorithm method
      Returns:
      the signature
    • signatureAlgConversion

      public static String signatureAlgConversion(String sign)
      Converts Signature algorithm method name
      Parameters:
      sign - signature algorithm method
      Returns:
      the converted signature name
    • validateSign

      public static boolean validateSign(Document doc, X509Certificate cert, String fingerprint, String alg, String xpath)
      Validate the signature pointed to by the xpath
      Parameters:
      doc - The document we should validate
      cert - The public certificate
      fingerprint - The fingerprint of the public certificate
      alg - The signature algorithm method
      xpath - the xpath of the ds:Signture node to validate
      Returns:
      True if the signature exists and is valid, false otherwise.
    • validateSign

      public static boolean validateSign(Document doc, List<X509Certificate> certList, String fingerprint, String alg, String xpath)
      Validate the signature pointed to by the xpath
      Parameters:
      doc - The document we should validate
      certList - The public certificates
      fingerprint - The fingerprint of the public certificate
      alg - The signature algorithm method
      xpath - the xpath of the ds:Signture node to validate
      Returns:
      True if the signature exists and is valid, false otherwise.
    • validateSign

      public static boolean validateSign(Document doc, List<X509Certificate> certList, String fingerprint, String alg, String xpath, boolean rejectDeprecatedAlg)
      Validate the signature pointed to by the xpath
      Parameters:
      doc - The document we should validate
      certList - The public certificates
      fingerprint - The fingerprint of the public certificate
      alg - The signature algorithm method
      xpath - the xpath of the ds:Signture node to validate
      rejectDeprecatedAlg - Flag to invalidate or not Signatures with deprecated alg
      Returns:
      True if the signature exists and is valid, false otherwise.
    • validateMetadataSign

      public static boolean validateMetadataSign(Document doc, X509Certificate cert, String fingerprint, String alg)
      Validate signature (Metadata).
      Parameters:
      doc - The document we should validate
      cert - The public certificate
      fingerprint - The fingerprint of the public certificate
      alg - The signature algorithm method
      Returns:
      True if the sign is valid, false otherwise.
    • validateMetadataSign

      public static boolean validateMetadataSign(Document doc, X509Certificate cert, String fingerprint, String alg, boolean rejectDeprecatedAlg)
      Validate signature (Metadata).
      Parameters:
      doc - The document we should validate
      cert - The public certificate
      fingerprint - The fingerprint of the public certificate
      alg - The signature algorithm method
      rejectDeprecatedAlg - Flag to invalidate or not Signatures with deprecated alg
      Returns:
      True if the sign is valid, false otherwise.
    • mustRejectDeprecatedSignatureAlgo

      public static boolean mustRejectDeprecatedSignatureAlgo(String signAlg, boolean rejectDeprecatedAlg)
    • validateSignNode

      public static boolean validateSignNode(Node signNode, X509Certificate cert, String fingerprint, String alg)
      Validate signature of the Node.
      Parameters:
      signNode - The document we should validate
      cert - The public certificate
      fingerprint - The fingerprint of the public certificate
      alg - The signature algorithm method
      Returns:
      True if the sign is valid, false otherwise.
    • validateSignNode

      public static boolean validateSignNode(Node signNode, X509Certificate cert, String fingerprint, String alg, boolean rejectDeprecatedAlg)
      Validate signature of the Node.
      Parameters:
      signNode - The document we should validate
      cert - The public certificate
      fingerprint - The fingerprint of the public certificate
      alg - The signature algorithm method
      rejectDeprecatedAlg - Flag to invalidate or not Signatures with deprecated alg
      Returns:
      True if the sign is valid, false otherwise.
    • validateSignNode

      public static boolean validateSignNode(org.apache.xml.security.signature.XMLSignature signature, X509Certificate cert, String fingerprint, X509Certificate extractedCert, String extractedFingerprint)
      Validate signature of the Node.
      Parameters:
      signature - XMLSignature we should validate
      cert - The public certificate
      fingerprint - The fingerprint of the public certificate
      extractedCert - The cert extracted from the signNode
      extractedFingerprint - The fingerprint extracted from the signNode
      Returns:
      true if the sign is valid, false otherwise.
    • isAlgorithmWhitelisted

      public static boolean isAlgorithmWhitelisted(String alg)
      Whitelist the XMLSignature algorithm
      Parameters:
      alg - The signature algorithm method
      Returns:
      True if the sign is valid, false otherwise.
    • decryptElement

      public static void decryptElement(Element encryptedDataElement, PrivateKey inputKey)
      Decrypt an encrypted element.
      Parameters:
      encryptedDataElement - The encrypted element.
      inputKey - The private key to decrypt.
    • decryptUsingHsm

      public static void decryptUsingHsm(Element encryptedDataElement, HSM hsm)
      Decrypts the encrypted element using an HSM.
      Parameters:
      encryptedDataElement - The encrypted element.
      hsm - The HSM object.
    • copyDocument

      public static Document copyDocument(Document source)
      Clone a Document object.
      Parameters:
      source - The Document object to be cloned.
      Returns:
      the clone of the Document object
    • addSign

      public static String addSign(Document document, PrivateKey key, X509Certificate certificate, String signAlgorithm)
      Signs the Document using the specified signature algorithm with the private key and the public certificate.
      Parameters:
      document - The document to be signed
      key - The private key
      certificate - The public certificate
      signAlgorithm - Signature Algorithm
      Returns:
      the signed document in string format
    • addSign

      public static String addSign(Document document, PrivateKey key, X509Certificate certificate, String signAlgorithm, String digestAlgorithm)
      Signs the Document using the specified signature algorithm with the private key and the public certificate.
      Parameters:
      document - The document to be signed
      key - The private key
      certificate - The public certificate
      signAlgorithm - Signature Algorithm
      digestAlgorithm - Digest Algorithm
      Returns:
      the signed document in string format
    • addSign

      public static String addSign(Node node, PrivateKey key, X509Certificate certificate, String signAlgorithm, String digestAlgorithm)
      Signs a Node using the specified signature algorithm with the private key and the public certificate.
      Parameters:
      node - The Node to be signed
      key - The private key
      certificate - The public certificate
      signAlgorithm - Signature Algorithm
      digestAlgorithm - Digest Algorithm
      Returns:
      the signed document in string format
    • addSign

      public static String addSign(Node node, PrivateKey key, X509Certificate certificate, String signAlgorithm)
      Signs a Node using the specified signature algorithm with the private key and the public certificate.
      Parameters:
      node - The Node to be signed
      key - The private key
      certificate - The public certificate
      signAlgorithm - Signature Algorithm
      Returns:
      the signed document in string format
    • validateBinarySignature

      public static boolean validateBinarySignature(String signedQuery, byte[] signature, X509Certificate cert, String signAlg)
      Validates signed binary data (Used to validate GET Signature).
      Parameters:
      signedQuery - The element we should validate
      signature - The signature that will be validate
      cert - The public certificate
      signAlg - Signature Algorithm
      Returns:
      the signed document in string format
    • validateBinarySignature

      public static boolean validateBinarySignature(String signedQuery, byte[] signature, List<X509Certificate> certList, String signAlg)
      Validates signed binary data (Used to validate GET Signature).
      Parameters:
      signedQuery - The element we should validate
      signature - The signature that will be validate
      certList - The List of certificates
      signAlg - Signature Algorithm
      Returns:
      the signed document in string format
    • getStatus

      public static SamlResponseStatus getStatus(String statusXpath, Document dom)
      Get Status from a Response
      Parameters:
      dom - The Response as XML
      Returns:
      SamlResponseStatus
    • generateNameId

      public static String generateNameId(String value, String spnq, String format, String nq, X509Certificate cert)
      Generates a nameID.
      Parameters:
      value - The value
      spnq - SP Name Qualifier
      format - SP Format
      nq - Name Qualifier
      cert - IdP Public certificate to encrypt the nameID
      Returns:
      Xml contained in the document.
    • generateNameId

      public static String generateNameId(String value, String spnq, String format, X509Certificate cert)
      Generates a nameID.
      Parameters:
      value - The value
      spnq - SP Name Qualifier
      format - SP Format
      cert - IdP Public certificate to encrypt the nameID
      Returns:
      Xml contained in the document.
    • generateNameId

      public static String generateNameId(String value, String spnq, String format)
      Generates a nameID.
      Parameters:
      value - The value
      spnq - SP Name Qualifier
      format - SP Format
      Returns:
      Xml contained in the document.
    • generateNameId

      public static String generateNameId(String value)
      Generates a nameID.
      Parameters:
      value - The value
      Returns:
      Xml contained in the document.
    • generateUniqueID

      public static String generateUniqueID(String prefix)
      Generates a unique string (used for example as ID of assertions)
      Parameters:
      prefix - Prefix for the Unique ID. Use property onelogin.saml2.unique_id_prefix to set this.
      Returns:
      A unique string
    • generateUniqueID

      public static String generateUniqueID()
      Generates a unique string (used for example as ID of assertions)
      Returns:
      A unique string
    • parseDuration

      public static long parseDuration(String duration)
      Interprets a ISO8601 duration value relative to a current time timestamp.
      Parameters:
      duration - The duration, as a string.
      Returns:
      int The new timestamp, after the duration is applied.
    • parseDuration

      public static long parseDuration(String durationString, long timestamp)
      Interprets a ISO8601 duration value relative to a given timestamp.
      Parameters:
      durationString - The duration, as a string.
      timestamp - The unix timestamp we should apply the duration to.
      Returns:
      the new timestamp, after the duration is applied In Seconds.
    • getCurrentTimeStamp

      public static Long getCurrentTimeStamp()
      Returns:
      the unix timestamp that matches the current time.
    • getExpireTime

      public static long getExpireTime(String cacheDuration, String validUntil)
      Compare 2 dates and return the the earliest
      Parameters:
      cacheDuration - The duration, as a string.
      validUntil - The valid until date, as a string
      Returns:
      the expiration time (timestamp format).
    • getExpireTime

      public static long getExpireTime(String cacheDuration, long validUntil)
      Compare 2 dates and return the the earliest
      Parameters:
      cacheDuration - The duration, as a string.
      validUntil - The valid until date, as a timestamp
      Returns:
      the expiration time (timestamp format).
    • formatDateTime

      public static String formatDateTime(long timeInMillis)
      Create string form time In Millis with format yyyy-MM-ddTHH:mm:ssZ
      Parameters:
      timeInMillis - The time in Millis
      Returns:
      string with format yyyy-MM-ddTHH:mm:ssZ
    • parseDateTime

      public static Instant parseDateTime(String dateTime)
      Create calendar form string with format yyyy-MM-ddTHH:mm:ssZ // yyyy-MM-ddTHH:mm:ss.SSSZ
      Parameters:
      dateTime - string with format yyyy-MM-ddTHH:mm:ssZ // yyyy-MM-ddTHH:mm:ss.SSSZ
      Returns:
      datetime
    • toXml

      public static String toXml(String text)
      Escape a text so that it can be safely used within an XML element contents or attribute value.
      Parameters:
      text - the text to escape
      Returns:
      the escaped text (null if the input is null)
    • getCurrentTimeMillis

      public static long getCurrentTimeMillis()
      Get current timestamp milliseconds.
      Returns:
      current timestamp
    • isEqualNow

      public static boolean isEqualNow(Instant instant)
      Checks if specified instant is equal to now.
      Parameters:
      instant - the instant to compare to
      Returns:
      true if instant is equal to now
    • isBeforeNow

      public static boolean isBeforeNow(Instant instant)
      Checks if specified instant is before now.
      Parameters:
      instant - the instant to compare to
      Returns:
      true if instant is before now
    • isAfterNow

      public static boolean isAfterNow(Instant instant)
      Checks if specified instant is after now.
      Parameters:
      instant - the instant to compare to
      Returns:
      true if instant is before now