Class DSSUtils

java.lang.Object
eu.europa.esig.dss.spi.DSSUtils

public final class DSSUtils extends Object
Set of common utils
  • Field Details

    • EMPTY_BYTE_ARRAY

      public static final byte[] EMPTY_BYTE_ARRAY
      Empty byte array
    • CARRIAGE_RETURN

      public static final byte CARRIAGE_RETURN
      Represents a carriage return '\r' character
      See Also:
    • LINE_FEED

      public static final byte LINE_FEED
      Represents a new line '\n' character
      See Also:
    • RFC3339_TIME_FORMAT

      public static final String RFC3339_TIME_FORMAT
      RFC 3339 DateTime format used by default
      See Also:
    • UTC_TIMEZONE

      public static final TimeZone UTC_TIMEZONE
      The UTC timezone (GMT+0), used by default
    • UTF8_ENCODING

      public static final String UTF8_ENCODING
      The UTF-8 encoding name string
      See Also:
    • OID_NAMESPACE_PREFIX

      public static final String OID_NAMESPACE_PREFIX
      The URN OID prefix (RFC 3061)
      See Also:
  • Method Details

    • formatDateToRFC

      public static String formatDateToRFC(Date date)
      Formats a date to use according to RFC 3339. The date is aligned to UTC TimeZone Example: "2019-11-19T17:28:15Z"
      Parameters:
      date - the date to be converted
      Returns:
      the textual representation (a null date will result in "N/A")
    • formatDateWithCustomFormat

      public static String formatDateWithCustomFormat(Date date, String format)
      Formats the date according to the given format (with system TimeZone)
      Parameters:
      date - Date to transform to a String
      format - String representing a Date format to be used
      Returns:
      String formatted date
    • formatDateWithCustomFormat

      public static String formatDateWithCustomFormat(Date date, String format, String timeZone)
      Formats the date according to the given format and timeZone as String. NOTE : When null or empty string is provided, the system default timezone is used!
      Parameters:
      date - Date to transform to a String
      format - String representing a Date format to be used
      timeZone - String specifying a TimeZone
      Returns:
      String formatted date
    • formatDateWithCustomFormat

      public static String formatDateWithCustomFormat(Date date, String format, TimeZone timeZone)
      Formats the date according to the given format and TimeZone NOTE : When null TimeZone is provided, the system default timezone is used!
      Parameters:
      date - Date to transform to a String
      format - String representing a Date format to be used
      timeZone - TimeZone specifying a TimeZone
      Returns:
      String formatted date
    • toHex

      public static String toHex(byte[] value)
      Converts an array of bytes into a String representing the hexadecimal values of each byte in order. The returned String will be double the length of the passed array, as it takes two characters to represent any given byte. If the input array is null then null is returned. The obtained string is converted to uppercase.
      Parameters:
      value - the value to be converted to hexadecimal
      Returns:
      the hexadecimal String
    • convertToPEM

      public static String convertToPEM(CertificateToken cert)
      This method converts the given certificate into its PEM string.
      Parameters:
      cert - the token to be converted to PEM
      Returns:
      PEM encoded certificate
    • isStartWithASN1SequenceTag

      public static boolean isStartWithASN1SequenceTag(InputStream is)
      This method returns true if the inputStream starts with an ASN.1 Sequence
      Parameters:
      is - the inputstream to be tested
      Returns:
      true if DER encoded
    • convertToDER

      public static byte[] convertToDER(String pemContent)
      This method converts a PEM encoded certificate/crl/... to DER encoded
      Parameters:
      pemContent - the String which contains the PEM encoded object
      Returns:
      the binaries of the DER encoded object
    • loadCertificate

      public static CertificateToken loadCertificate(File file)
      This method loads a certificate from the given location. The certificate must be DER-encoded and may be supplied in binary or printable (PEM / Base64) encoding. If the certificate is provided in Base64 encoding, it must be bounded at the beginning by -----BEGIN CERTIFICATE-----, and must be bounded at the end by -----END CERTIFICATE-----.
      Parameters:
      file - the file with the certificate
      Returns:
      the certificate token
    • loadCertificate

      public static CertificateToken loadCertificate(InputStream inputStream)
      This method loads a certificate from the given location. The certificate must be DER-encoded and may be supplied in binary or printable (PEM / Base64) encoding. If the certificate is provided in Base64 encoding, it must be bounded at the beginning by -----BEGIN CERTIFICATE-----, and must be bounded at the end by -----END CERTIFICATE-----.
      Parameters:
      inputStream - input stream containing the certificate
      Returns:
      the certificate token
    • loadCertificateFromP7c

      public static List<CertificateToken> loadCertificateFromP7c(InputStream is)
      Loads a collection of certificates from a p7c source
      Parameters:
      is - InputStream p7c
      Returns:
      a list of CertificateTokens
    • loadCertificate

      public static CertificateToken loadCertificate(byte[] input)
      This method loads a certificate from the byte array. The certificate must be DER-encoded and may be supplied in binary or printable (Base64) encoding. If the certificate is provided in Base64 encoding, it must be bounded at the beginning by -----BEGIN CERTIFICATE-----, and must be bounded at the end by -----END CERTIFICATE-----. It throws an DSSException or return null when the certificate cannot be loaded.
      Parameters:
      input - array of bytes containing the certificate
      Returns:
      the certificate token
    • loadCertificateFromBase64EncodedString

      public static CertificateToken loadCertificateFromBase64EncodedString(String base64Encoded)
      This method loads a certificate from a base 64 encoded String
      Parameters:
      base64Encoded - the base64 encoded certificate
      Returns:
      the certificate token
    • getSHA1Digest

      public static String getSHA1Digest(String stringToDigest)
      This method digests the given string with SHA1 algorithm and encode returned array of bytes as hex string.
      Parameters:
      stringToDigest - Everything in the name
      Returns:
      hex encoded digest value
    • isSHA1Digest

      public static boolean isSHA1Digest(String str)
      This method checks if the provided str represents a SHA-1 digest
      Parameters:
      str - String to check
      Returns:
      TRUE if the string represents SHA-1 digest, FALSE otherwise
    • digest

      public static byte[] digest(DigestAlgorithm digestAlgorithm, byte[] data)
      This method allows to digest the data with the given algorithm.
      Parameters:
      digestAlgorithm - the algorithm to use
      data - the data to digest
      Returns:
      digested array of bytes
    • getMessageDigest

      public static MessageDigest getMessageDigest(DigestAlgorithm digestAlgorithm)
      Gets the message digest from the DigestAlgorithm
      Parameters:
      digestAlgorithm - DigestAlgorithm
      Returns:
      MessageDigest
    • toDigestDocument

      public static DigestDocument toDigestDocument(Digest digest)
      Creates a DigestDocument with the provided Digest
      Parameters:
      digest - Digest to use to create a DigestDocument
      Returns:
      DigestDocument containing Digest
    • toDigestDocument

      public static DigestDocument toDigestDocument(DigestAlgorithm digestAlgorithm, byte[] digestValue)
      Creates a DigestDocument with the provided DigestAlgorithm and digestValue
      Parameters:
      digestAlgorithm - DigestAlgorithm
      digestValue - byte array containing digest value
      Returns:
      DigestDocument containing the given digest value with the defined algorithm
    • encodeRSADigest

      public static byte[] encodeRSADigest(DigestAlgorithm digestAlgorithm, byte[] digest)
      This method wraps the digest value in a DigestInfo (combination of digest algorithm and value). This encapsulation is required to operate NONEwithRSA signatures.
      Parameters:
      digestAlgorithm - the used digest algorithm
      digest - the digest value
      Returns:
      DER encoded binaries of the related digest info
    • digest

      public static byte[] digest(DigestAlgorithm digestAlgo, InputStream inputStream)
      This method allows to digest the data in the InputStream with the given algorithm.
      Parameters:
      digestAlgo - the algorithm to use
      inputStream - the data to digest
      Returns:
      digested array of bytes
    • digest

      public static byte[] digest(DigestAlgorithm digestAlgorithm, DSSDocument document)
      Computes the digests for the document
      Parameters:
      digestAlgorithm - DigestAlgorithm to use
      document - DSSDocument to calculate the digest on
      Returns:
      digest value
    • digest

      public static byte[] digest(DigestAlgorithm digestAlgorithm, byte[]... data)
      Computes the digest on the data concatenation
      Parameters:
      digestAlgorithm - DigestAlgorithm to use
      data - a sequence of byte arrays to compute digest on
      Returns:
      digest value
    • toInputStream

      public static InputStream toInputStream(File file)
      This method returns an InputStream which needs to be closed, based on FileInputStream.
      Parameters:
      file - File to read.
      Returns:
      an InputStream materialized by a FileInputStream representing the contents of the file @ if an I/O error occurred
    • toByteArrayInputStream

      public static InputStream toByteArrayInputStream(File file)
      This method returns an InputStream which does not need to be closed, based on ByteArrayInputStream.
      Parameters:
      file - File to read
      Returns:
      InputStream based on ByteArrayInputStream
    • toByteArray

      public static byte[] toByteArray(File file)
      FROM: Apache Reads the contents of a file into a byte array. The file is always closed.
      Parameters:
      file - the file to read, must not be null
      Returns:
      the file contents, never null
    • splitDocument

      public static DSSDocument splitDocument(DSSDocument origin, int start, int end)
      This method create a new document from a sub-part of another document
      Parameters:
      origin - the original document
      start - the start position to retrieve
      end - the end position to retrieve
      Returns:
      a new DSSDocument
    • toByteArray

      public static byte[] toByteArray(DSSDocument document)
      Get the contents of an DSSDocument as a byte[].
      Parameters:
      document - the document to read
      Returns:
      the content as byte array
    • toByteArray

      public static byte[] toByteArray(InputStream inputStream)
      Get the contents of an InputStream as a byte[].
      Parameters:
      inputStream - the inputstream to read
      Returns:
      the content of the inputstream as byte array
    • toCMSSignedData

      public static org.bouncycastle.cms.CMSSignedData toCMSSignedData(DSSDocument document)
      Gets CMSSignedData from the document bytes
      Parameters:
      document - DSSDocument contained CMSSignedData
      Returns:
      CMSSignedData
    • toCMSSignedData

      public static org.bouncycastle.cms.CMSSignedData toCMSSignedData(byte[] encoded)
      Creates CMSSignedData from the DER-encoded binaries representing CMS
      Parameters:
      encoded - byte array representing CMSSignedData
      Returns:
      CMSSignedData
    • isEmpty

      public static boolean isEmpty(DSSDocument document)
      This method verifies if the document is empty (does not have body)
      Parameters:
      document - DSSDocument to check
      Returns:
      TRUE if the document is empty, FALSE otherwise
    • isTimestampToken

      public static boolean isTimestampToken(DSSDocument document)
      Checks if the document contains a TimeStampToken
      Parameters:
      document - the DSSDocument to be checked
      Returns:
      true if the document is a timestamp
    • getFileByteSize

      public static long getFileByteSize(DSSDocument dssDocument)
      Returns byte size of the given document
      Parameters:
      dssDocument - DSSDocument to get size for
      Returns:
      long size of the given document
    • saveToFile

      public static void saveToFile(byte[] bytes, File file)
      This method saves the given array of byte to the provided File.
      Parameters:
      bytes - the binary to save
      file - the file where to store
    • getNormalizedString

      public static String getNormalizedString(String str)
      This method replaces all special characters by an underscore
      Parameters:
      str - the string / filename / url to normalize
      Returns:
      the normalized String
    • getDeterministicId

      public static String getDeterministicId(Date signingTime, TokenIdentifier id)
      Return a unique id for a date and the certificateToken id.
      Parameters:
      signingTime - the signing time
      id - the token identifier
      Returns:
      a unique string
    • getCounterSignatureDeterministicId

      public static String getCounterSignatureDeterministicId(Date signingTime, TokenIdentifier id, String masterSignatureId)
      Return a unique id for a counter signature.
      Parameters:
      signingTime - the signing time
      id - the token identifier
      masterSignatureId - id of a signature to be counter-signed
      Returns:
      a unique string
    • getMD5Digest

      public static String getMD5Digest(byte[] bytes)
      Returns a Hex encoded of the MD5 digest of binaries
      Parameters:
      bytes - the bytes to be digested
      Returns:
      the hex encoded MD5 digest
    • getX500PrincipalOrNull

      public static X500Principal getX500PrincipalOrNull(String x500PrincipalString)
      This method returns the X500Principal corresponding to the given string or null if the conversion is not possible.
      Parameters:
      x500PrincipalString - a String representation of the X500Principal
      Returns:
      X500Principal or null
    • getUtcDate

      public static Date getUtcDate(int year, int month, int day)
      This method returns an UTC date base on the year, the month and the day. The year must be encoded as 1978... and not 78
      Parameters:
      year - the value used to set the YEAR calendar field.
      month - the month. Month value is 0-based. e.g., 0 for January.
      day - the value used to set the DAY_OF_MONTH calendar field.
      Returns:
      the UTC date base on parameters
    • printSecurityProviders

      public static void printSecurityProviders()
      This method lists all defined security providers.
    • readFirstByte

      public static byte readFirstByte(DSSDocument dssDocument)
      Reads the first byte from the DSSDocument
      Parameters:
      dssDocument - the document
      Returns:
      the first byte
    • startsWithBytes

      @Deprecated public static boolean startsWithBytes(DSSDocument dssDocument, byte[] preamble)
      Deprecated.
      since DSS 5.13. See eu.europa.esig.dss.utils.Utils.startsWith(inputStream, preamble)
      Reads first preamble.length bytes of the dssDocument and compares them with preamble
      Parameters:
      dssDocument - DSSDocument to read bytes from
      preamble - byte array to compare the beginning string with
      Returns:
      TRUE if the document starts from preamble, FALSE otherwise
    • startsWithBytes

      @Deprecated public static boolean startsWithBytes(byte[] byteArray, byte[] preamble)
      Deprecated.
      since DSS 5.13. See eu.europa.esig.dss.utils.Utils.startsWithBytes(byteArray, preamble)
      Reads first preamble.length bytes of the byteArray and compares them with preamble
      Parameters:
      byteArray - DSSDocument to compare bytes from
      preamble - byte array to compare the beginning string with
      Returns:
      TRUE if the document starts from preamble, FALSE otherwise
    • startsWithBytes

      @Deprecated public static boolean startsWithBytes(InputStream inputStream, byte[] preamble)
      Deprecated.
      since DSS 5.13. See eu.europa.esig.dss.utils.Utils.startsWith(inputStream, preamble)
      Reads first preamble.length bytes of the InputStream and compares them with preamble
      Parameters:
      inputStream - InputStream to read bytes from
      preamble - byte array to compare the beginning string with
      Returns:
      TRUE if the document starts from preamble, FALSE otherwise
    • decodeURI

      public static String decodeURI(String uri)
      This method decodes a URI to be compliant with the RFC 3986 (see DSS-2411 for details)
      Parameters:
      uri - String
      Returns:
      String UTF-8
    • skipAvailableBytes

      public static long skipAvailableBytes(InputStream is, int n) throws IllegalStateException
      Skip the defined n number of bytes from the InputStream and validates success of the operation
      Parameters:
      is - InputStream to skip bytes from
      n - int number bytes to skip
      Returns:
      actual number of bytes have been skipped
      Throws:
      IllegalStateException - in case of InputStream reading error
    • readAvailableBytes

      public static long readAvailableBytes(DSSDocument dssDocument, byte[] b) throws IllegalStateException
      Read the requested number of bytes from DSSDocument according to the size of the provided byte[] buffer and validates success of the operation
      Parameters:
      dssDocument - DSSDocument to read bytes from
      b - byte[] buffer to fill
      Returns:
      the total number of bytes read into buffer
      Throws:
      IllegalStateException - in case of InputStream reading error
    • readAvailableBytes

      public static long readAvailableBytes(InputStream is, byte[] b) throws IllegalStateException
      Read the requested number of bytes from InputStream according to the size of the provided byte[] buffer and validates success of the operation
      Parameters:
      is - InputStream to read bytes from
      b - byte[] buffer to fill
      Returns:
      the total number of bytes read into buffer
      Throws:
      IllegalStateException - in case of InputStream reading error
    • readAvailableBytes

      public static long readAvailableBytes(InputStream is, byte[] b, int off, int len) throws IllegalStateException
      Read the requested number of bytes from InputStream and validates success of the operation
      Parameters:
      is - InputStream to read bytes from
      b - byte[] buffer to fill
      off - int offset in the destination array
      len - int number of bytes to read
      Returns:
      the total number of bytes read into buffer
      Throws:
      IllegalStateException - in case of InputStream reading error
    • encodeURI

      public static String encodeURI(String fileURI)
      This method encodes a URI to be compliant with the RFC 3986 (see DSS-1475 for details)
      Parameters:
      fileURI - the uri to be encoded
      Returns:
      the encoded result
    • getExceptionMessage

      public static String getExceptionMessage(Exception e)
      Returns a message retrieved from an exception, its cause message if the first is not defined, or exception class name if non of them is specified
      Parameters:
      e - Exception to get message for
      Returns:
      String exception message
    • getDigest

      public static Digest getDigest(DigestAlgorithm digestAlgo, DSSDocument dssDocument)
      Returns Digest of the dssDocument
      Parameters:
      digestAlgo - DigestAlgorithm to use
      dssDocument - DSSDocument to compute digest on
      Returns:
      Digest
    • removeControlCharacters

      public static String removeControlCharacters(String str)
      Replaces null ASCII characters 00-31 and 127 with ''
      Parameters:
      str - String to remove Ctrls characters from
      Returns:
      String without Ctrls characters
    • replaceAllNonAlphanumericCharacters

      public static String replaceAllNonAlphanumericCharacters(String str, String replacement)
      Replaces all non-alphanumeric characters in the str by the replacement
      Parameters:
      str - String to replace non-alphanumeric characters in
      replacement - String to be used as a replacement
      Returns:
      String
    • isUrnOid

      public static boolean isUrnOid(String id)
      Checks if the given id is a URN representation of OID according to IETF RFC 3061
      Parameters:
      id - String to check
      Returns:
      TRUE if the provided id is a URN representation of OID, FALSE otherwise
    • isOidCode

      public static boolean isOidCode(String oid)
      Checks if the given oid is a valid OID Ex.: 1.3.6.1.4.1.343 = valid 25.25 = invalid http://sample.com = invalid Source: regexr.com/38m0v (OID Validator)
      Parameters:
      oid - String oid to verify
      Returns:
      TRUE if the string is a valid OID code, FALSE otherwise
    • getOidCode

      public static String getOidCode(String urnOid)
      Keeps only code of the oid string e.g. "urn:oid:1.2.3" to "1.2.3"
      Parameters:
      urnOid - String uri to extract OID value from
      Returns:
      OID Code
    • toUrnOid

      public static String toUrnOid(String oid)
      Returns a URN URI generated from the given OID: Ex.: OID = 1.2.4.5.6.8 becomes URI = urn:oid:1.2.4.5.6.8 Note: see RFC 3061 "A URN Namespace of Object Identifiers"
      Parameters:
      oid - String to be converted to URN URI
      Returns:
      URI based on the algorithm's OID
    • getObjectIdentifierValue

      public static String getObjectIdentifierValue(String oidOrUriString)
      Normalizes and retrieves a String identifier (to be used for non-XAdES processing). Examples: "http://website.com" = "http://website.com" "urn:oid:1.2.3" = "1.2.3" "1.2.3" = "1.2.3"
      Parameters:
      oidOrUriString - String identifier
      Returns:
      String
    • getObjectIdentifierValue

      public static String getObjectIdentifierValue(String oidOrUriString, ObjectIdentifierQualifier qualifier)
      This method returns a URI value of the oidOrUriString taking into account the defined ObjectIdentifierQualifier (to be used for XAdES processing). Examples: "http://nowina.lu/policy" = "http://nowina.lu/policy" "1.2.3.4.5" = "1.2.3.4.5" "urn:oid:1.2.3.4.5" = "1.2.3.4.5"
      Parameters:
      oidOrUriString - String identifier value
      qualifier - ObjectIdentifierQualifier when present
      Returns:
      String URI
    • stripFirstLeadingOccurrence

      public static String stripFirstLeadingOccurrence(String text, String leading)
      Trims the leading string if it is a leading part of the text
      Parameters:
      text - String to trim
      leading - String to remove
      Returns:
      trimmed text String
    • getDocumentNames

      public static List<String> getDocumentNames(List<DSSDocument> dssDocuments)
      Returns a list of document names from the given document list
      Parameters:
      dssDocuments - a list of DSSDocuments to get names of
      Returns:
      a list of String document names
    • getDocumentWithName

      public static DSSDocument getDocumentWithName(List<DSSDocument> documents, String fileName)
      Returns a document with the given fileName from the list of documents, when present
      Parameters:
      documents - a list of DSSDocuments
      fileName - String name of the document to extract
      Returns:
      DSSDocument when found, NULL otherwise
    • getDocumentWithLastName

      public static DSSDocument getDocumentWithLastName(List<DSSDocument> documents)
      Returns the last document in the alphabetical ascendant order
      Parameters:
      documents - a list of DSSDocuments
      Returns:
      DSSDocument
    • enrichCollection

      public static <T> void enrichCollection(Collection<T> currentCollection, Collection<T> toAddCollection)
      Adds all objects from toAddCollection into currentCollection without duplicates
      Type Parameters:
      T - an Object
      Parameters:
      currentCollection - a collection to enrich
      toAddCollection - a collection to add values from
    • convertECSignatureValue

      public static SignatureValue convertECSignatureValue(SignatureAlgorithm expectedAlgorithm, SignatureValue signatureValue)
      This method ensures the SignatureValue has an expected format and converts it when required
      Parameters:
      expectedAlgorithm - SignatureAlgorithm the target SignatureAlgorithm
      signatureValue - SignatureValue the obtained SignatureValue
      Returns:
      SignatureValue with the target SignatureAlgorithm
    • getEdDSASignatureAlgorithm

      public static SignatureAlgorithm getEdDSASignatureAlgorithm(byte[] signatureValue)
      This method returns a SignatureAlgorithm used to create the signatureValue NOTE: Only EdDSA algorithm is being returned by this method. For non-EdDSA or unsupported format, NULL will be returned
      Parameters:
      signatureValue - byte array representing the signature value
      Returns:
      SignatureAlgorithm
    • assertSPUserNoticeConfigurationValid

      public static void assertSPUserNoticeConfigurationValid(UserNotice userNotice) throws IllegalArgumentException
      This method verifies the validity of thw provided UserNotice object
      Parameters:
      userNotice - UserNotice to check
      Throws:
      IllegalArgumentException - in case of an invalid configuration
    • toBigIntegerList

      public static List<BigInteger> toBigIntegerList(int[] integers)
      Transforms the given array of integers to a list of BigIntegers
      Parameters:
      integers - array of integers
      Returns:
      a list of BigIntegers
    • isLineBreakByte

      public static boolean isLineBreakByte(byte b)
      This method verifies if the given byte represents a line break character (new line or a carriage return)
      Parameters:
      b - byte to verify
      Returns:
      TRUE if the byte represents a line break char, FALSE otherwise