java.lang.Object
org.codelibs.saml2.core.util.Util
Util class of Java Toolkit.
A class that contains several auxiliary methods related to the SAML protocol
-
Field Summary
Fields -
Method Summary
Modifier and TypeMethodDescriptionstatic StringaddSign(Document document, PrivateKey key, X509Certificate certificate, String signAlgorithm) Signs the Document using the specified signature algorithm with the private key and the public certificate.static StringaddSign(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.static StringaddSign(Node node, PrivateKey key, X509Certificate certificate, String signAlgorithm) Signs a Node using the specified signature algorithm with the private key and the public certificate.static StringaddSign(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.static Stringbase64decodedInflated(String input) Returns String Base64 decoded and inflatedstatic byte[]base64decoder(byte[] input) Returns String base64 decodedstatic byte[]base64decoder(String input) Returns String base64 decodedstatic Stringbase64encoder(byte[] input) Returns String base64 encodedstatic Stringbase64encoder(String input) Returns String base64 encodedstatic StringcalculateX509Fingerprint(X509Certificate x509cert) Calculates the SHA-1 fingerprint of a x509certstatic StringcalculateX509Fingerprint(X509Certificate x509cert, String alg) Calculates the fingerprint of a x509certstatic StringConverts an XML in Document format in a String without applying the c14n transformationstatic StringconvertDocumentToString(Document doc, boolean c14n) Converts an XML in Document format in a Stringstatic DocumentconvertStringToDocument(String xmlStr) Converts an XML in string format in a Document objectstatic StringconvertToPem(X509Certificate certificate) Converts an X509Certificate in a well formated PEM stringstatic DocumentcopyDocument(Document source) Clone a Document object.static voiddecryptElement(Element encryptedDataElement, PrivateKey inputKey) Decrypt an encrypted element.static voiddecryptUsingHsm(Element encryptedDataElement, HSM hsm) Decrypts the encrypted element using an HSM.static StringdeflatedBase64encoded(String input) Returns String Deflated and base64 encodedstatic StringformatCert(String cert, boolean heads) Returns a certificate in String format (adding header and footer if required)static StringformatDateTime(long timeInMillis) Create string form time In Millis with format yyyy-MM-ddTHH:mm:ssZstatic StringformatPrivateKey(String key, boolean heads) Returns a private key (adding header and footer if required).static StringgenerateNameId(String value) Generates a nameID.static StringgenerateNameId(String value, String spnq, String format) Generates a nameID.static StringgenerateNameId(String value, String spnq, String format, String nq, X509Certificate cert) Generates a nameID.static StringgenerateNameId(String value, String spnq, String format, X509Certificate cert) Generates a nameID.static StringGenerates a unique string (used for example as ID of assertions)static StringgenerateUniqueID(String prefix) Generates a unique string (used for example as ID of assertions)static longGet current timestamp milliseconds.static Longstatic longgetExpireTime(String cacheDuration, long validUntil) Compare 2 dates and return the the earlieststatic longgetExpireTime(String cacheDuration, String validUntil) Compare 2 dates and return the the earlieststatic StringgetFileAsString(String relativeResourcePath) Loads a resource located at a relative pathstatic SamlResponseStatusGet Status from a Responsestatic booleanisAfterNow(Instant instant) Checks if specified instant is after now.static booleanWhitelist the XMLSignature algorithmstatic booleanisBeforeNow(Instant instant) Checks if specified instant is before now.static booleanisEqualNow(Instant instant) Checks if specified instant is equal to now.static booleanMethod 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.static X509CertificateLoad X.509 certificatestatic PrivateKeyloadPrivateKey(String keyString) Load private keystatic DocumentThis function load an XML string in a save way.static booleanmustRejectDeprecatedSignatureAlgo(String signAlg, boolean rejectDeprecatedAlg) static InstantparseDateTime(String dateTime) Create calendar form string with format yyyy-MM-ddTHH:mm:ssZ // yyyy-MM-ddTHH:mm:ss.SSSZstatic longparseDuration(String duration) Interprets a ISO8601 duration value relative to a current time timestamp.static longparseDuration(String durationString, long timestamp) Interprets a ISO8601 duration value relative to a given timestamp.static DocumentparseXML(InputSource inputSource) Parse an XML from input source to a Document objectstatic NodeListExtracts a node from the DOMDocumentstatic NodeListExtracts a node from the DOMDocumentstatic byte[]sign(String text, PrivateKey key, String signAlgorithm) Generates a signature from a stringstatic StringsignatureAlgConversion(String sign) Converts Signature algorithm method namestatic StringEscape a text so that it can be safely used within an XML element contents or attribute value.static StringurlDecoder(String input) Returns String URL decodedstatic StringurlEncoder(String input) Returns String URL encodedstatic booleanvalidateBinarySignature(String signedQuery, byte[] signature, X509Certificate cert, String signAlg) Validates signed binary data (Used to validate GET Signature).static booleanvalidateBinarySignature(String signedQuery, byte[] signature, List<X509Certificate> certList, String signAlg) Validates signed binary data (Used to validate GET Signature).static booleanvalidateMetadataSign(Document doc, X509Certificate cert, String fingerprint, String alg) Validate signature (Metadata).static booleanvalidateMetadataSign(Document doc, X509Certificate cert, String fingerprint, String alg, boolean rejectDeprecatedAlg) Validate signature (Metadata).static booleanvalidateSign(Document doc, X509Certificate cert, String fingerprint, String alg, String xpath) Validate the signature pointed to by the xpathstatic booleanvalidateSign(Document doc, List<X509Certificate> certList, String fingerprint, String alg, String xpath) Validate the signature pointed to by the xpathstatic booleanvalidateSign(Document doc, List<X509Certificate> certList, String fingerprint, String alg, String xpath, boolean rejectDeprecatedAlg) Validate the signature pointed to by the xpathstatic booleanvalidateSignNode(org.apache.xml.security.signature.XMLSignature signature, X509Certificate cert, String fingerprint, X509Certificate extractedCert, String extractedFingerprint) Validate signature of the Node.static booleanvalidateSignNode(Node signNode, X509Certificate cert, String fingerprint, String alg) Validate signature of the Node.static booleanvalidateSignNode(Node signNode, X509Certificate cert, String fingerprint, String alg, boolean rejectDeprecatedAlg) Validate signature of the Node.static booleanvalidateXML(Document xmlDocument, URL schemaUrl) This function attempts to validate an XML against the specified schema.
-
Field Details
-
UNIQUE_ID_PREFIX
- See Also:
-
RESPONSE_SIGNATURE_XPATH
- See Also:
-
ASSERTION_SIGNATURE_XPATH
- See Also:
-
-
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
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
Extracts a node from the DOMDocument- Parameters:
dom- The DOMDocumentquery- Xpath Expressioncontext- Context Node (DomElement)- Returns:
- DOMNodeList The queried node
-
query
Extracts a node from the DOMDocument- Parameters:
dom- The DOMDocumentquery- Xpath Expression- Returns:
- DOMNodeList The queried node
-
validateXML
This function attempts to validate an XML against the specified schema.- Parameters:
xmlDocument- The XML document which should be validatedschemaUrl- The schema filename which should be used- Returns:
- found errors after validation
-
convertStringToDocument
Converts an XML in string format in a Document object- Parameters:
xmlStr- The XML string which should be converted- Returns:
- the Document object
-
parseXML
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
Converts an XML in Document format in a String- Parameters:
doc- The Document objectc14n- If c14n transformation should be applied- Returns:
- the Document object
-
convertDocumentToString
Converts an XML in Document format in a String without applying the c14n transformation- Parameters:
doc- The Document object- Returns:
- the Document object
-
formatCert
Returns a certificate in String format (adding header and footer if required)- Parameters:
cert- A x509 unformatted certheads- True if we want to include head and footer- Returns:
- X509Certificate $x509 Formated cert
-
formatPrivateKey
Returns a private key (adding header and footer if required).- Parameters:
key- A private keyheads- True if we want to include head and footer- Returns:
- Formated private key
-
loadCert
Load X.509 certificate- Parameters:
certString- certificate in string format- Returns:
- Loaded Certificate. X509Certificate object
-
loadPrivateKey
Load private key- Parameters:
keyString- private key in string format- Returns:
- Loaded private key. PrivateKey object
-
calculateX509Fingerprint
Calculates the fingerprint of a x509cert- Parameters:
x509cert- x509 certificatealg- Digest Algorithm- Returns:
- the formated fingerprint
-
calculateX509Fingerprint
Calculates the SHA-1 fingerprint of a x509cert- Parameters:
x509cert- x509 certificate- Returns:
- the SHA-1 formated fingerprint
-
convertToPem
Converts an X509Certificate in a well formated PEM string- Parameters:
certificate- The public certificate- Returns:
- the formated PEM string
-
getFileAsString
Loads a resource located at a relative path- Parameters:
relativeResourcePath- Relative path of the resource- Returns:
- the loaded resource in String format
-
base64decodedInflated
Returns String Base64 decoded and inflated- Parameters:
input- String input- Returns:
- the base64 decoded and inflated string
-
deflatedBase64encoded
Returns String Deflated and base64 encoded- Parameters:
input- String input- Returns:
- the deflated and base64 encoded string
-
base64encoder
Returns String base64 encoded- Parameters:
input- Stream input- Returns:
- the base64 encoded string
-
base64encoder
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
Returns String base64 decoded- Parameters:
input- String input- Returns:
- the base64 decoded bytes
-
urlEncoder
Returns String URL encoded- Parameters:
input- String input- Returns:
- the URL encoded string
-
urlDecoder
Returns String URL decoded- Parameters:
input- URL encoded input- Returns:
- the URL decoded string
-
sign
Generates a signature from a string- Parameters:
text- The string we should signkey- The private key to sign the stringsignAlgorithm- Signature algorithm method- Returns:
- the signature
-
signatureAlgConversion
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 validatecert- The public certificatefingerprint- The fingerprint of the public certificatealg- The signature algorithm methodxpath- 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 validatecertList- The public certificatesfingerprint- The fingerprint of the public certificatealg- The signature algorithm methodxpath- 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 validatecertList- The public certificatesfingerprint- The fingerprint of the public certificatealg- The signature algorithm methodxpath- the xpath of the ds:Signture node to validaterejectDeprecatedAlg- 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 validatecert- The public certificatefingerprint- The fingerprint of the public certificatealg- 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 validatecert- The public certificatefingerprint- The fingerprint of the public certificatealg- The signature algorithm methodrejectDeprecatedAlg- 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 validatecert- The public certificatefingerprint- The fingerprint of the public certificatealg- 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 validatecert- The public certificatefingerprint- The fingerprint of the public certificatealg- The signature algorithm methodrejectDeprecatedAlg- 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 validatecert- The public certificatefingerprint- The fingerprint of the public certificateextractedCert- The cert extracted from the signNodeextractedFingerprint- The fingerprint extracted from the signNode- Returns:
- true if the sign is valid, false otherwise.
-
isAlgorithmWhitelisted
Whitelist the XMLSignature algorithm- Parameters:
alg- The signature algorithm method- Returns:
- True if the sign is valid, false otherwise.
-
decryptElement
Decrypt an encrypted element.- Parameters:
encryptedDataElement- The encrypted element.inputKey- The private key to decrypt.
-
decryptUsingHsm
Decrypts the encrypted element using an HSM.- Parameters:
encryptedDataElement- The encrypted element.hsm- The HSM object.
-
copyDocument
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 signedkey- The private keycertificate- The public certificatesignAlgorithm- 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 signedkey- The private keycertificate- The public certificatesignAlgorithm- Signature AlgorithmdigestAlgorithm- 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 signedkey- The private keycertificate- The public certificatesignAlgorithm- Signature AlgorithmdigestAlgorithm- 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 signedkey- The private keycertificate- The public certificatesignAlgorithm- 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 validatesignature- The signature that will be validatecert- The public certificatesignAlg- 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 validatesignature- The signature that will be validatecertList- The List of certificatessignAlg- Signature Algorithm- Returns:
- the signed document in string format
-
getStatus
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 valuespnq- SP Name Qualifierformat- SP Formatnq- Name Qualifiercert- IdP Public certificate to encrypt the nameID- Returns:
- Xml contained in the document.
-
generateNameId
Generates a nameID.- Parameters:
value- The valuespnq- SP Name Qualifierformat- SP Formatcert- IdP Public certificate to encrypt the nameID- Returns:
- Xml contained in the document.
-
generateNameId
Generates a nameID.- Parameters:
value- The valuespnq- SP Name Qualifierformat- SP Format- Returns:
- Xml contained in the document.
-
generateNameId
Generates a nameID.- Parameters:
value- The value- Returns:
- Xml contained in the document.
-
generateUniqueID
Generates a unique string (used for example as ID of assertions)- Parameters:
prefix- Prefix for the Unique ID. Use propertyonelogin.saml2.unique_id_prefixto set this.- Returns:
- A unique string
-
generateUniqueID
Generates a unique string (used for example as ID of assertions)- Returns:
- A unique string
-
parseDuration
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
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
- Returns:
- the unix timestamp that matches the current time.
-
getExpireTime
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
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
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
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
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 (
nullif the input isnull)
-
getCurrentTimeMillis
public static long getCurrentTimeMillis()Get current timestamp milliseconds.- Returns:
- current timestamp
-
isEqualNow
Checks if specified instant is equal to now.- Parameters:
instant- the instant to compare to- Returns:
- true if instant is equal to now
-
isBeforeNow
Checks if specified instant is before now.- Parameters:
instant- the instant to compare to- Returns:
- true if instant is before now
-
isAfterNow
Checks if specified instant is after now.- Parameters:
instant- the instant to compare to- Returns:
- true if instant is before now
-