Package eu.europa.esig.dss.spi
Class DSSUtils
java.lang.Object
eu.europa.esig.dss.spi.DSSUtils
public final class DSSUtils extends Object
Set of common utils
-
Field Summary
Fields Modifier and Type Field Description static byte[]EMPTY_BYTE_ARRAYEmpty byte arraystatic StringOID_NAMESPACE_PREFIXThe URN OID prefix (RFC 3061) -
Method Summary
Modifier and Type Method Description static booleancompareFirstBytes(DSSDocument dssDocument, byte[] byteArray)Reads firstbyteArray.lengthbytes of thedssDocumentand compares them withbyteArraystatic byte[]concatenate(byte[]... arrays)Concatenates all the arrays into a new array.static byte[]convertToDER(String pemContent)This method converts a PEM encoded certificate/crl/... to DER encodedstatic StringconvertToPEM(CertificateToken cert)This method converts the given certificate into its PEM string.static StringdecodeUrl(String uri)Decodes URI to UTF-8static byte[]digest(DigestAlgorithm digestAlgorithm, byte[] data)This method allows to digest the data with the given algorithm.static byte[]digest(DigestAlgorithm digestAlgorithm, byte[]... data)Computes the digest on the data concatenationstatic byte[]digest(DigestAlgorithm digestAlgorithm, DSSDocument document)Computes the digests for thedocumentstatic byte[]digest(DigestAlgorithm digestAlgo, InputStream inputStream)This method allows to digest the data in theInputStreamwith the given algorithm.static byte[]encodeRSADigest(DigestAlgorithm digestAlgorithm, byte[] digest)This method wraps the digest value in a DigestInfo (combination of digest algorithm and value).static StringencodeURI(String fileURI)This method encodes an URI to be compliant with the RFC 3986 (see DSS-1475 for details)static <T> voidenrichCollection(Collection<T> currentCollection, Collection<T> toAddCollection)Adds all objects fromtoAddCollectionintocurrentCollectionwithout duplicatesstatic StringformatDateToRFC(Date date)Formats a date to use according to RFC 3339.static StringformatDateWithCustomFormat(Date date, String format)Formats the date according to the given format (with system TimeZone)static StringformatDateWithCustomFormat(Date date, String format, String timeZone)Formats the date according to the given format and timeZonestatic StringformatInternal(Date date)Formats a date to use for internal purposes (logging, toString) Example: "2019-11-19T17:28:15Z"static StringgetCounterSignatureDeterministicId(Date signingTime, TokenIdentifier id, String masterSignatureId)Return a unique id for a counter signature.static StringgetDeterministicId(Date signingTime, TokenIdentifier id)Return a unique id for a date and the certificateToken id.static DigestgetDigest(DigestAlgorithm digestAlgo, DSSDocument dssDocument)ReturnsDigestof thedssDocumentstatic List<String>getDocumentNames(List<DSSDocument> dssDocuments)Returns a list of document names from the given document liststatic StringgetExceptionMessage(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 specifiedstatic longgetFileByteSize(DSSDocument dssDocument)Returns byte size of the given documentstatic StringgetMD5Digest(byte[] bytes)Returns a Hex encoded of the MD5 digest of binariesstatic MessageDigestgetMessageDigest(DigestAlgorithm digestAlgorithm)Gets the message digest from theDigestAlgorithmstatic StringgetNormalizedString(String str)This method replaces all special characters by an underscorestatic StringgetObjectIdentifier(String oidOrUriString)Normalizes and retrieves aStringidentifier Examples: "http://website.com" = "http://website.com" "urn:oid:1.2.3" = "1.2.3" "1.2.3" = "1.2.3"static StringgetOidCode(String urnOid)Keeps only code of the oid string e.g.static StringgetSHA1Digest(String stringToDigest)This method digests the given string with SHA1 algorithm and encode returned array of bytes as hex string.static StringgetUriOrUrnOid(ObjectIdentifier objectIdentifier)Returns URI if present, otherwise URN encoded OID (see RFC 3061) Returns NULL if non of them is presentstatic DategetUtcDate(int year, int month, int day)This method returns an UTC date base on the year, the month and the day.static X500PrincipalgetX500PrincipalOrNull(String x500PrincipalString)This method returns theX500Principalcorresponding to the given string ornullif the conversion is not possible.static booleanisOidCode(String oid)Checks if the givenoidis 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)static booleanisSHA1Digest(String str)This method checks if the providedstrrepresents a SHA-1 digeststatic booleanisStartWithASN1SequenceTag(InputStream is)This method returns true if the inputStream starts with an ASN.1 Sequencestatic booleanisTimestampToken(DSSDocument document)Checks if the document contains a TimeStampTokenstatic booleanisUrnOid(String id)Checks if the given id is a URN representation of OID according to IETF RFC 3061static CertificateTokenloadCertificate(byte[] input)This method loads a certificate from the byte array.static CertificateTokenloadCertificate(File file)This method loads a certificate from the given location.static CertificateTokenloadCertificate(InputStream inputStream)This method loads a certificate from the given location.static CertificateTokenloadCertificateFromBase64EncodedString(String base64Encoded)This method loads a certificate from a base 64 encoded Stringstatic Collection<CertificateToken>loadCertificateFromP7c(InputStream is)Loads a collection of certificates from a p7c sourcestatic Collection<CertificateToken>loadPotentialIssuerCertificates(CertificateToken cert, DataLoader loader)This method loads the potential issuer certificate(s) from the given locations (AIA).static voidprintSecurityProviders()This method lists all defined security providers.static longreadAvailableBytes(DSSDocument dssDocument, byte[] b)Read the requested number of bytes fromDSSDocumentaccording to the size of the providedbyte[] buffer and validates success of the operationstatic longreadAvailableBytes(InputStream is, byte[] b)Read the requested number of bytes fromInputStreamaccording to the size of the providedbyte[] buffer and validates success of the operationstatic longreadAvailableBytes(InputStream is, byte[] b, int off, int len)Read the requested number of bytes fromInputStreamand validates success of the operationstatic bytereadFirstByte(DSSDocument dssDocument)Reads the first byte from the DSSDocumentstatic StringremoveControlCharacters(String str)Replaces null ASCII characters 00-31 and 127 with ''static voidsaveToFile(byte[] bytes, File file)This method saves the given array ofbyteto the providedFile.static longskipAvailableBytes(InputStream is, long n)Skip the definednnumber of bytes from theInputStreamand validates success of the operationstatic DSSDocumentsplitDocument(DSSDocument origin, int start, int end)This method create a new document from a sub-part of another documentstatic StringstripFirstLeadingOccurance(String text, String leading)Trims the leading string if it is a leading part of the textstatic byte[]toByteArray(DSSDocument document)Get the contents of anDSSDocumentas abyte[].static byte[]toByteArray(File file)FROM: Apache Reads the contents of a file into a byte array.static byte[]toByteArray(InputStream inputStream)Get the contents of anInputStreamas abyte[].static InputStreamtoByteArrayInputStream(File file)This method returns anInputStreamwhich does not need to be closed, based onByteArrayInputStream.static org.bouncycastle.cms.CMSSignedDatatoCMSSignedData(DSSDocument document)Gets CMSSignedData from thedocumentbytesstatic StringtoHex(byte[] value)Converts an array of bytes into a String representing the hexadecimal values of each byte in order.static InputStreamtoInputStream(File file)This method returns anInputStreamwhich needs to be closed, based onFileInputStream.static StringtoUrnOid(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"
-
Field Details
-
EMPTY_BYTE_ARRAY
public static final byte[] EMPTY_BYTE_ARRAYEmpty byte array -
OID_NAMESPACE_PREFIX
The URN OID prefix (RFC 3061)- See Also:
- Constant Field Values
-
-
Method Details
-
formatInternal
Formats a date to use for internal purposes (logging, toString) 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
Formats the date according to the given format (with system TimeZone) -
formatDateToRFC
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
Formats the date according to the given format and timeZone -
toHex
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
This method converts the given certificate into its PEM string.- Parameters:
cert- the token to be converted to PEM- Returns:
- PEM encoded certificate
-
isStartWithASN1SequenceTag
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
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
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
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
Loads a collection of certificates from a p7c source- Parameters:
is-InputStreamp7c- Returns:
- a collection of
CertificateTokens
-
loadCertificate
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 anDSSExceptionor returnnullwhen the certificate cannot be loaded.- Parameters:
input- array of bytes containing the certificate- Returns:
- the certificate token
-
loadCertificateFromBase64EncodedString
This method loads a certificate from a base 64 encoded String- Parameters:
base64Encoded- the base64 encoded certificate- Returns:
- the certificate token
-
loadPotentialIssuerCertificates
public static Collection<CertificateToken> loadPotentialIssuerCertificates(CertificateToken cert, DataLoader loader)This method loads the potential issuer certificate(s) from the given locations (AIA).- Parameters:
cert- certificate for which the issuer(s) should be loadedloader- the data loader to use- Returns:
- a list of potential issuers
-
getSHA1Digest
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
This method checks if the providedstrrepresents a SHA-1 digest- Parameters:
str-Stringto check- Returns:
- TRUE if the string represents SHA-1 digest, FALSE otherwise
-
digest
This method allows to digest the data with the given algorithm.- Parameters:
digestAlgorithm- the algorithm to usedata- the data to digest- Returns:
- digested array of bytes
-
getMessageDigest
Gets the message digest from theDigestAlgorithm- Parameters:
digestAlgorithm-DigestAlgorithm- Returns:
MessageDigest
-
encodeRSADigest
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 algorithmdigest- the digest value- Returns:
- DER encoded binaries of the related digest info
-
digest
This method allows to digest the data in theInputStreamwith the given algorithm.- Parameters:
digestAlgo- the algorithm to useinputStream- the data to digest- Returns:
- digested array of bytes
-
digest
Computes the digests for thedocument- Parameters:
digestAlgorithm-DigestAlgorithmto usedocument-DSSDocumentto calculate the digest on- Returns:
- digest value
-
digest
Computes the digest on the data concatenation- Parameters:
digestAlgorithm-DigestAlgorithmto usedata- an sequence of byte arrays to compute digest on- Returns:
- digest value
-
toInputStream
This method returns anInputStreamwhich needs to be closed, based onFileInputStream.- Parameters:
file-Fileto read.- Returns:
- an
InputStreammaterialized by aFileInputStreamrepresenting the contents of the file @ if an I/O error occurred
-
toByteArrayInputStream
This method returns anInputStreamwhich does not need to be closed, based onByteArrayInputStream.- Parameters:
file-Fileto read- Returns:
InputStreambased onByteArrayInputStream
-
toByteArray
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 benull- Returns:
- the file contents, never
null
-
splitDocument
This method create a new document from a sub-part of another document- Parameters:
origin- the original documentstart- the start position to retrieveend- the end position to retrieve- Returns:
- a new DSSDocument
-
toByteArray
Get the contents of anDSSDocumentas abyte[].- Parameters:
document- the document to read- Returns:
- the content as byte array
-
toByteArray
Get the contents of anInputStreamas abyte[].- Parameters:
inputStream- the inputstream to read- Returns:
- the content of the inputstream as byte array
-
toCMSSignedData
Gets CMSSignedData from thedocumentbytes- Parameters:
document-DSSDocumentcontained CMSSignedData- Returns:
CMSSignedData
-
isTimestampToken
Checks if the document contains a TimeStampToken- Parameters:
document- theDSSDocumentto be checked- Returns:
- true if the document is a timestamp
-
getFileByteSize
Returns byte size of the given document- Parameters:
dssDocument-DSSDocumentto get size for- Returns:
- long size of the given document
-
saveToFile
This method saves the given array ofbyteto the providedFile.- Parameters:
bytes- the binary to savefile- the file where to store
-
getNormalizedString
This method replaces all special characters by an underscore- Parameters:
str- the string / filename / url to normalize- Returns:
- the normalized
String
-
getDeterministicId
Return a unique id for a date and the certificateToken id.- Parameters:
signingTime- the signing timeid- 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 timeid- the token identifiermasterSignatureId- id of a signature to be counter signed- Returns:
- a unique string
-
getMD5Digest
Returns a Hex encoded of the MD5 digest of binaries- Parameters:
bytes- the bytes to be digested- Returns:
- the hex encoded MD5 digest
-
getX500PrincipalOrNull
This method returns theX500Principalcorresponding to the given string ornullif the conversion is not possible.- Parameters:
x500PrincipalString- aStringrepresentation of theX500Principal- Returns:
X500Principalor null
-
getUtcDate
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
Reads the first byte from the DSSDocument- Parameters:
dssDocument- the document- Returns:
- the first byte
-
compareFirstBytes
Reads firstbyteArray.lengthbytes of thedssDocumentand compares them withbyteArray- Parameters:
dssDocument-DSSDocumentto read bytes frombyteArray-bytearray to compare the beginning string with- Returns:
- TRUE if the document starts from
byteArray, FALSE otherwise
-
concatenate
public static byte[] concatenate(byte[]... arrays)Concatenates all the arrays into a new array. The new array contains all of the element of each array followed by all of the elements of the next array. When an array is returned, it is always a new array.- Parameters:
arrays-bytearrays to concatenate- Returns:
- the new
bytearray
-
decodeUrl
Decodes URI to UTF-8 -
skipAvailableBytes
Skip the definednnumber of bytes from theInputStreamand validates success of the operation- Parameters:
is-InputStreamto skip bytes fromn-longnumber bytes to skip- Returns:
- actual number of bytes have been skipped
- Throws:
IllegalStateException- in case ofInputStreamreading error
-
readAvailableBytes
public static long readAvailableBytes(DSSDocument dssDocument, byte[] b) throws IllegalStateExceptionRead the requested number of bytes fromDSSDocumentaccording to the size of the providedbyte[] buffer and validates success of the operation- Parameters:
dssDocument-DSSDocumentto read bytes fromb-byte[] buffer to fill- Returns:
- the total number of bytes read into buffer
- Throws:
IllegalStateException- in case ofInputStreamreading error
-
readAvailableBytes
Read the requested number of bytes fromInputStreamaccording to the size of the providedbyte[] buffer and validates success of the operation- Parameters:
is-InputStreamto read bytes fromb-byte[] buffer to fill- Returns:
- the total number of bytes read into buffer
- Throws:
IllegalStateException- in case ofInputStreamreading error
-
readAvailableBytes
public static long readAvailableBytes(InputStream is, byte[] b, int off, int len) throws IllegalStateExceptionRead the requested number of bytes fromInputStreamand validates success of the operation- Parameters:
is-InputStreamto read bytes fromb-byte[] buffer to filloff-intoffset in the destination arraylen-intnumber of bytes to read- Returns:
- the total number of bytes read into buffer
- Throws:
IllegalStateException- in case ofInputStreamreading error
-
encodeURI
This method encodes an 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
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 -
getDigest
ReturnsDigestof thedssDocument- Parameters:
digestAlgo-DigestAlgorithmto usedssDocument-DSSDocumentto compute digest on- Returns:
Digest
-
removeControlCharacters
Replaces null ASCII characters 00-31 and 127 with '' -
isUrnOid
Checks if the given id is a URN representation of OID according to IETF RFC 3061- Parameters:
id-Stringto check- Returns:
- TRUE if the provided id is aURN representation of OID, FALSE otherwise
-
toUrnOid
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-Stringto be converted to URN URI- Returns:
- URI based on the algorithm's OID
-
isOidCode
Checks if the givenoidis 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-Stringoid to verify- Returns:
- TRUE if the string is a valid OID code, FALSE otherwise
-
getOidCode
Keeps only code of the oid string e.g. "urn:oid:1.2.3" to "1.2.3"- Parameters:
urnOid-Stringuri to extract OID value from- Returns:
- OID Code
-
getUriOrUrnOid
Returns URI if present, otherwise URN encoded OID (see RFC 3061) Returns NULL if non of them is present- Parameters:
objectIdentifier-ObjectIdentifierused to build an object of 'oid' type- Returns:
StringURI
-
getObjectIdentifier
Normalizes and retrieves aStringidentifier Examples: "http://website.com" = "http://website.com" "urn:oid:1.2.3" = "1.2.3" "1.2.3" = "1.2.3" -
stripFirstLeadingOccurance
Trims the leading string if it is a leading part of the text -
getDocumentNames
Returns a list of document names from the given document list- Parameters:
dssDocuments- a list ofDSSDocuments to get names of- Returns:
- a list of
Stringdocument names
-
enrichCollection
public static <T> void enrichCollection(Collection<T> currentCollection, Collection<T> toAddCollection)Adds all objects fromtoAddCollectionintocurrentCollectionwithout duplicates- Type Parameters:
T- an Object- Parameters:
currentCollection- a collection to enrichtoAddCollection- a collection to add values from
-