Package eu.europa.esig.dss.spi
Class DSSUtils
java.lang.Object
eu.europa.esig.dss.spi.DSSUtils
-
Field Summary
FieldsModifier and TypeFieldDescriptionstatic final byte
Represents a carriage return '\r' characterstatic final byte[]
Empty byte arraystatic final byte
Represents a new line '\n' characterstatic final String
The URN OID prefix (RFC 3061)static final String
RFC 3339 DateTime format used by defaultstatic final TimeZone
The UTC timezone (GMT+0), used by defaultstatic final String
The UTF-8 encoding name string -
Method Summary
Modifier and TypeMethodDescriptionstatic void
assertSPUserNoticeConfigurationValid
(UserNotice userNotice) This method verifies the validity of thw providedUserNotice
objectstatic SignatureValue
convertECSignatureValue
(SignatureAlgorithm expectedAlgorithm, SignatureValue signatureValue) This method ensures theSignatureValue
has an expected format and converts it when requiredstatic byte[]
convertToDER
(String pemContent) This method converts a PEM encoded certificate/crl/... to DER encodedstatic String
convertToPEM
(CertificateToken cert) This method converts the given certificate into its PEM string.static String
This method decodes a URI to be compliant with the RFC 3986 (see DSS-2411 for details)static 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 thedocument
static byte[]
digest
(DigestAlgorithm digestAlgo, InputStream inputStream) This method allows to digest the data in theInputStream
with 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 String
This method encodes a URI to be compliant with the RFC 3986 (see DSS-1475 for details)static <T> void
enrichCollection
(Collection<T> currentCollection, Collection<T> toAddCollection) Adds all objects fromtoAddCollection
intocurrentCollection
without duplicatesstatic String
formatDateToRFC
(Date date) Formats a date to use according to RFC 3339.static String
formatDateWithCustomFormat
(Date date, String format) Formats the date according to the given format (with system TimeZone)static String
formatDateWithCustomFormat
(Date date, String format, String timeZone) Formats the date according to the given format and timeZone asString
.static String
formatDateWithCustomFormat
(Date date, String format, TimeZone timeZone) Formats the date according to the given format andTimeZone
NOTE : When null TimeZone is provided, the system default timezone is used!static String
getCounterSignatureDeterministicId
(Date signingTime, TokenIdentifier id, String masterSignatureId) Return a unique id for a counter signature.static String
getDeterministicId
(Date signingTime, TokenIdentifier id) Return a unique id for a date and the certificateToken id.static Digest
getDigest
(DigestAlgorithm digestAlgo, DSSDocument dssDocument) ReturnsDigest
of thedssDocument
getDocumentNames
(List<DSSDocument> dssDocuments) Returns a list of document names from the given document liststatic DSSDocument
getDocumentWithLastName
(List<DSSDocument> documents) Returns the last document in the alphabetical ascendant orderstatic DSSDocument
getDocumentWithName
(List<DSSDocument> documents, String fileName) Returns a document with the givenfileName
from the list ofdocuments
, when presentstatic SignatureAlgorithm
getEdDSASignatureAlgorithm
(byte[] signatureValue) This method returns aSignatureAlgorithm
used to create thesignatureValue
NOTE: Only EdDSA algorithm is being returned by this method.static String
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 long
getFileByteSize
(DSSDocument dssDocument) Returns byte size of the given documentstatic String
getMD5Digest
(byte[] bytes) Returns a Hex encoded of the MD5 digest of binariesstatic MessageDigest
getMessageDigest
(DigestAlgorithm digestAlgorithm) Gets the message digest from theDigestAlgorithm
static String
This method replaces all special characters by an underscorestatic String
getObjectIdentifierValue
(String oidOrUriString) Normalizes and retrieves aString
identifier (to be used for non-XAdES processing).static String
getObjectIdentifierValue
(String oidOrUriString, ObjectIdentifierQualifier qualifier) This method returns a URI value of theoidOrUriString
taking into account the definedObjectIdentifierQualifier
(to be used for XAdES processing).static String
getOidCode
(String urnOid) Keeps only code of the oid string e.g.static String
getSHA1Digest
(String stringToDigest) This method digests the given string with SHA1 algorithm and encode returned array of bytes as hex string.static Date
getUtcDate
(int year, int month, int day) This method returns an UTC date base on the year, the month and the day.static X500Principal
getX500PrincipalOrNull
(String x500PrincipalString) This method returns theX500Principal
corresponding to the given string ornull
if the conversion is not possible.static boolean
isEmpty
(DSSDocument document) This method verifies if the document is empty (does not have body)static boolean
isLineBreakByte
(byte b) This method verifies if the given byte represents a line break character (new line or a carriage return)static boolean
Checks if the givenoid
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)static boolean
isSHA1Digest
(String str) This method checks if the providedstr
represents a SHA-1 digeststatic boolean
This method returns true if the inputStream starts with an ASN.1 Sequencestatic boolean
isTimestampToken
(DSSDocument document) Checks if the document contains a TimeStampTokenstatic boolean
Checks if the given id is a URN representation of OID according to IETF RFC 3061static CertificateToken
loadCertificate
(byte[] input) This method loads a certificate from the byte array.static CertificateToken
loadCertificate
(File file) This method loads a certificate from the given location.static CertificateToken
loadCertificate
(InputStream inputStream) This method loads a certificate from the given location.static CertificateToken
loadCertificateFromBase64EncodedString
(String base64Encoded) This method loads a certificate from a base 64 encoded Stringstatic List
<CertificateToken> Loads a collection of certificates from a p7c sourcestatic Date
parseRFCDate
(String str) Parses aString
date toDate
static void
This method lists all defined security providers.static long
readAvailableBytes
(DSSDocument dssDocument, byte[] b) Read the requested number of bytes fromDSSDocument
according to the size of the providedbyte
[] buffer and validates success of the operationstatic long
readAvailableBytes
(InputStream is, byte[] b) Read the requested number of bytes fromInputStream
according to the size of the providedbyte
[] buffer and validates success of the operationstatic long
readAvailableBytes
(InputStream is, byte[] b, int off, int len) Read the requested number of bytes fromInputStream
and validates success of the operationstatic byte
readFirstByte
(DSSDocument dssDocument) Reads the first byte from the DSSDocumentstatic String
Replaces null ASCII characters 00-31 and 127 with ''static String
replaceAllNonAlphanumericCharacters
(String str, String replacement) Replaces all non-alphanumeric characters in thestr
by thereplacement
static void
saveToFile
(byte[] bytes, File file) This method saves the given array ofbyte
to the providedFile
.static long
skipAvailableBytes
(InputStream is, int n) Skip the definedn
number of bytes from theInputStream
and validates success of the operationstatic DSSDocument
splitDocument
(DSSDocument origin, int start, int end) This method create a new document from a sub-part of another documentstatic String
stripFirstLeadingOccurrence
(String text, String leading) Trims the leading string if it is a leading part of the textstatic List
<BigInteger> toBigIntegerList
(int[] integers) Transforms the given array of integers to a list ofBigInteger
sstatic byte[]
toByteArray
(DSSDocument document) Get the contents of anDSSDocument
as 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 anInputStream
as abyte[]
.static InputStream
toByteArrayInputStream
(File file) This method returns anInputStream
which does not need to be closed, based onByteArrayInputStream
.static org.bouncycastle.cms.CMSSignedData
toCMSSignedData
(byte[] encoded) CreatesCMSSignedData
from the DER-encoded binaries representing CMSstatic org.bouncycastle.cms.CMSSignedData
toCMSSignedData
(DSSDocument document) Gets CMSSignedData from thedocument
bytesstatic org.bouncycastle.cms.CMSSignedData
toCMSSignedData
(InputStream inputStream) Gets CMSSignedData from theInputStream
static DigestDocument
toDigestDocument
(DigestAlgorithm digestAlgorithm, byte[] digestValue) Creates aDigestDocument
with the providedDigestAlgorithm
anddigestValue
static DigestDocument
toDigestDocument
(Digest digest) Creates aDigestDocument
with the providedDigest
static String
toHex
(byte[] value) Converts an array of bytes into a String representing the hexadecimal values of each byte in order.static InputStream
toInputStream
(File file) This method returns anInputStream
which needs to be closed, based onFileInputStream
.static String
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"static String
Trims whitespaces and new line characters
-
Field Details
-
EMPTY_BYTE_ARRAY
public static final byte[] EMPTY_BYTE_ARRAYEmpty byte array -
CARRIAGE_RETURN
public static final byte CARRIAGE_RETURNRepresents a carriage return '\r' character- See Also:
-
LINE_FEED
public static final byte LINE_FEEDRepresents a new line '\n' character- See Also:
-
RFC3339_TIME_FORMAT
-
UTC_TIMEZONE
The UTC timezone (GMT+0), used by default -
UTF8_ENCODING
-
OID_NAMESPACE_PREFIX
-
-
Method Details
-
formatDateToRFC
-
parseRFCDate
-
formatDateWithCustomFormat
-
formatDateWithCustomFormat
Formats the date according to the given format and timeZone asString
. NOTE : When null or empty string is provided, the system default timezone is used! -
formatDateWithCustomFormat
Formats the date according to the given format andTimeZone
NOTE : When null TimeZone is provided, the system default timezone is used! -
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
-InputStream
p7c- Returns:
- a list of
CertificateToken
s
-
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 anDSSException
or returnnull
when 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
-
getSHA1Digest
-
isSHA1Digest
-
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
-
toDigestDocument
Creates aDigestDocument
with the providedDigest
- Parameters:
digest
-Digest
to use to create aDigestDocument
- Returns:
DigestDocument
containingDigest
-
toDigestDocument
Creates aDigestDocument
with the providedDigestAlgorithm
anddigestValue
- Parameters:
digestAlgorithm
-DigestAlgorithm
digestValue
- byte array containing digest value- Returns:
DigestDocument
containing the given digest value with the defined algorithm
-
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 theInputStream
with 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
-DigestAlgorithm
to usedocument
-DSSDocument
to calculate the digest on- Returns:
- digest value
-
digest
Computes the digest on the data concatenation- Parameters:
digestAlgorithm
-DigestAlgorithm
to usedata
- a sequence of byte arrays to compute digest on- Returns:
- digest value
-
toInputStream
This method returns anInputStream
which needs to be closed, based onFileInputStream
.- Parameters:
file
-File
to read.- Returns:
- an
InputStream
materialized by aFileInputStream
representing the contents of the file @ if an I/O error occurred
-
toByteArrayInputStream
This method returns anInputStream
which does not need to be closed, based onByteArrayInputStream
.- Parameters:
file
-File
to read- Returns:
InputStream
based 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 anDSSDocument
as abyte[]
.- Parameters:
document
- the document to read- Returns:
- the content as byte array
-
toByteArray
Get the contents of anInputStream
as abyte[]
.- Parameters:
inputStream
- the inputstream to read- Returns:
- the content of the inputstream as byte array
-
toCMSSignedData
Gets CMSSignedData from theInputStream
- Parameters:
inputStream
-InputStream
contained CMSSignedData- Returns:
CMSSignedData
-
toCMSSignedData
Gets CMSSignedData from thedocument
bytes- Parameters:
document
-DSSDocument
contained CMSSignedData- Returns:
CMSSignedData
-
toCMSSignedData
public static org.bouncycastle.cms.CMSSignedData toCMSSignedData(byte[] encoded) CreatesCMSSignedData
from the DER-encoded binaries representing CMS- Parameters:
encoded
- byte array representing CMSSignedData- Returns:
CMSSignedData
-
isEmpty
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
Checks if the document contains a TimeStampToken- Parameters:
document
- theDSSDocument
to be checked- Returns:
- true if the document is a timestamp
-
getFileByteSize
Returns byte size of the given document- Parameters:
dssDocument
-DSSDocument
to get size for- Returns:
- long size of the given document
-
saveToFile
This method saves the given array ofbyte
to the providedFile
.- Parameters:
bytes
- the binary to savefile
- the file where to store
-
getNormalizedString
-
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 theX500Principal
corresponding to the given string ornull
if the conversion is not possible.- Parameters:
x500PrincipalString
- aString
representation of theX500Principal
- Returns:
X500Principal
or 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
-
decodeURI
-
skipAvailableBytes
Skip the definedn
number of bytes from theInputStream
and validates success of the operation- Parameters:
is
-InputStream
to skip bytes fromn
-int
number bytes to skip- Returns:
- actual number of bytes have been skipped
- Throws:
IllegalStateException
- in case ofInputStream
reading error
-
readAvailableBytes
public static long readAvailableBytes(DSSDocument dssDocument, byte[] b) throws IllegalStateException Read the requested number of bytes fromDSSDocument
according to the size of the providedbyte
[] buffer and validates success of the operation- Parameters:
dssDocument
-DSSDocument
to read bytes fromb
-byte
[] buffer to fill- Returns:
- the total number of bytes read into buffer
- Throws:
IllegalStateException
- in case ofInputStream
reading error
-
readAvailableBytes
Read the requested number of bytes fromInputStream
according to the size of the providedbyte
[] buffer and validates success of the operation- Parameters:
is
-InputStream
to read bytes fromb
-byte
[] buffer to fill- Returns:
- the total number of bytes read into buffer
- Throws:
IllegalStateException
- in case ofInputStream
reading error
-
readAvailableBytes
public static long readAvailableBytes(InputStream is, byte[] b, int off, int len) throws IllegalStateException Read the requested number of bytes fromInputStream
and validates success of the operation- Parameters:
is
-InputStream
to read bytes fromb
-byte
[] buffer to filloff
-int
offset in the destination arraylen
-int
number of bytes to read- Returns:
- the total number of bytes read into buffer
- Throws:
IllegalStateException
- in case ofInputStream
reading error
-
encodeURI
-
getExceptionMessage
-
getDigest
ReturnsDigest
of thedssDocument
- Parameters:
digestAlgo
-DigestAlgorithm
to usedssDocument
-DSSDocument
to compute digest on- Returns:
Digest
-
removeControlCharacters
-
replaceAllNonAlphanumericCharacters
-
isUrnOid
-
isOidCode
Checks if the givenoid
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
-
toUrnOid
-
getObjectIdentifierValue
Normalizes and retrieves aString
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" -
getObjectIdentifierValue
public static String getObjectIdentifierValue(String oidOrUriString, ObjectIdentifierQualifier qualifier) This method returns a URI value of theoidOrUriString
taking into account the definedObjectIdentifierQualifier
(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 valuequalifier
-ObjectIdentifierQualifier
when present- Returns:
String
URI
-
trimWhitespacesAndNewlines
-
stripFirstLeadingOccurrence
-
getDocumentNames
Returns a list of document names from the given document list- Parameters:
dssDocuments
- a list ofDSSDocument
s to get names of- Returns:
- a list of
String
document names
-
getDocumentWithName
Returns a document with the givenfileName
from the list ofdocuments
, when present- Parameters:
documents
- a list ofDSSDocument
sfileName
-String
name of the document to extract- Returns:
DSSDocument
when found, NULL otherwise
-
getDocumentWithLastName
Returns the last document in the alphabetical ascendant order- Parameters:
documents
- a list ofDSSDocument
s- Returns:
DSSDocument
-
enrichCollection
public static <T> void enrichCollection(Collection<T> currentCollection, Collection<T> toAddCollection) Adds all objects fromtoAddCollection
intocurrentCollection
without duplicates- Type Parameters:
T
- an Object- Parameters:
currentCollection
- a collection to enrichtoAddCollection
- a collection to add values from
-
convertECSignatureValue
public static SignatureValue convertECSignatureValue(SignatureAlgorithm expectedAlgorithm, SignatureValue signatureValue) This method ensures theSignatureValue
has an expected format and converts it when required- Parameters:
expectedAlgorithm
-SignatureAlgorithm
the target SignatureAlgorithmsignatureValue
-SignatureValue
the obtained SignatureValue- Returns:
SignatureValue
with the targetSignatureAlgorithm
-
getEdDSASignatureAlgorithm
This method returns aSignatureAlgorithm
used to create thesignatureValue
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 providedUserNotice
object- Parameters:
userNotice
-UserNotice
to check- Throws:
IllegalArgumentException
- in case of an invalid configuration
-
toBigIntegerList
Transforms the given array of integers to a list ofBigInteger
s- Parameters:
integers
- array of integers- Returns:
- a list of
BigInteger
s
-
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
-