public class CryptoUtil extends Object
NOTE: By default, getRandom() is initialized with
SecureRandom.getInstance(..). On Windows 'Windows-PRNG' is used and
'NativePRNGNonBlocking' elsewhere. In case it is not found, 'SHA1PRNG' is used as a fallback. The
'SHA1PRNG' is seeded with System.currentTimeMillis() and System.nanoTime(), to
avoid blocking at the application startup. For the others SecureRandom.nextBytes(byte[])
is used ('Windows-PRNG' and 'NativePRNGNonBlocking' should not block here).
IF you require real entropy, and your target systems will be able to provide that without
blocking the application for long periods, you can use setRandom(SecureRandom) override
the default. Please do seed it first though. Some SecureRandom implementations to use might be
SecureRandom.getInstance("DBRG") or SecureRandom.getInstanceStrong(),
however please note that they might block (for some time!) in some environments.
| Modifier and Type | Field and Description |
|---|---|
static boolean |
sendNullInsteadOfEmptyNonce
Setting this to true will cause null ByteStrings to be sent as nonces instead of empty
ByteStrings.
|
| Constructor and Description |
|---|
CryptoUtil() |
| Modifier and Type | Method and Description |
|---|---|
static byte[] |
asymmEncrypt(byte[] input,
Key key,
SecurityAlgorithm algorithm)
Deprecated.
use
encryptAsymm(byte[], PublicKey, SecurityAlgorithm) instead. |
static byte[] |
base64Decode(String string)
Decodes a String having Base64 encoding to an array of bytes.
|
static String |
base64Encode(byte[] bytes)
Base64 encodes a byte array to string.
|
static Mac |
createMac(SecurityAlgorithm algorithm,
byte[] secret)
Create Message Authentication Code (MAC).
|
static ByteString |
createNonce(int bytes)
Create a non-repeatable set of bytes.
|
static ByteString |
createNonce(SecurityAlgorithm algorithm)
Deprecated.
use
createNonce(int) and get the size from
SecurityPolicy.getSecureChannelNonceLength() directly |
static void |
decryptAsymm(PrivateKey decryptingKey,
SecurityConfiguration profile,
byte[] dataToDecrypt,
byte[] output,
int outputOffset)
Convenience method for
CryptoProvider.decryptAsymm(PrivateKey, SecurityAlgorithm, byte[], byte[], int)
Possible to use only SecurityConfiguration instead of specifying SecurityAlgorithm explicitly. |
static byte[] |
encryptAsymm(byte[] input,
PublicKey key,
SecurityAlgorithm algorithm)
|
static void |
encryptAsymm(Certificate encryptingCertificate,
SecurityConfiguration profile,
byte[] dataToEncrypt,
byte[] output,
int outputOffset)
Convenience method for
CryptoProvider.encryptAsymm(PublicKey, SecurityAlgorithm, byte[], byte[], int) Possible
to use only Certificate and SecurityConfiguration instead of specifying PublicKey and
SecurityAlgorithm explicitly. |
static String[] |
filterCipherSuiteList(String[] cipherSuiteSet,
String[] cipherSuitePatterns)
filterCipherSuiteList.
|
static Cipher |
getAsymmetricCipher(SecurityAlgorithm algorithm)
Create signer instance using an algorithm uri.
|
static int |
getAsymmInputBlockSize(SecurityAlgorithm algorithm)
getAsymmInputBlockSize.
|
static int |
getCipherBlockSize(SecurityAlgorithm algorithm,
Key key)
Get cipher block (=output) size in bytes.
|
static String[] |
getCipherSuiteIntersection(String[] cipherSuiteSet1,
String[] cipherSuiteSet2,
boolean omitProtocol)
Create an intersection of two lists of cipher suite lists.
|
static CryptoProvider |
getCryptoProvider()
Returns
CryptoProvider previously set with setCryptoProvider(CryptoProvider). |
static int |
getNonceLength(SecurityAlgorithm algorithm)
Deprecated.
use
SecurityPolicy.getSecureChannelNonceLength() directly instead |
static int |
getPlainTextBlockSize(SecurityAlgorithm securityAlgorithm,
Key key)
Get plain text block (=input) size in bytes.
|
static SecureRandom |
getRandom()
The
SecureRandom instance used in crypto operations of the SDK. |
static int |
getRandomReseedCount()
The ReseedCount defines how often the
getRandom() will reseed the instance. |
static Provider |
getSecurityProvider()
Returns a
Provider that can be used for crypto operations. |
static String |
getSecurityProviderName()
Deprecated.
use
getSecurityProvider() instead |
static String |
getSecurityProviderName(Class<?> clazz)
Deprecated.
use
getSecurityProvider() instead |
static int |
getSignatureSize(SecurityAlgorithm signatureAlgorithm,
Key key)
Get signature size in bytes.
|
static byte[] |
hexToBytes(String string)
Converts a hexadecimal string to an array of bytes.
|
static Integer |
hexToInt(String string)
Converts a hexadecimal string to Integer.
|
static Long |
hexToLong(String string)
Converts a hexadecimal string to Long.
|
static Long |
hexToLong(String string,
int firstIndex,
int maxLen)
Converts a hexadecimal string to Long.
|
static void |
setCryptoProvider(CryptoProvider cryptoProvider)
Define the preferred CryptoProvider.
|
static void |
setRandom(SecureRandom secureRandom)
Replaces the default
SecureRandom instance used in crypto operations of the SDK. |
static void |
setRandomReseedCount(int reseedCount)
Define how often
getRandom() should be reseeded automatically. |
static void |
setSecurityProviderName(String securityProviderName)
Define the preferred SecurityProvider.
|
static SignatureData |
signAsymm(PrivateKey signerKey,
SecurityAlgorithm algorithm,
byte[] dataToSign)
signAsymm.
|
static String |
toHex(byte[] bytes)
Convenience method for "displaying" a hex-string of a given byte array.
|
static String |
toHex(byte[] bytes,
int bytesPerRow)
Convenience method for "displaying" a hex-string of a given byte array.
|
static String |
toHex(byte[] bytes,
int bytesPerRow,
boolean includeLengthPrefix)
Convenience method for "displaying" a hex-string of a given byte array.
|
static String |
toHex(int value)
Convenience method for "displaying" an int value as a hex-string, interpreting it as an
unsigned value.
|
static String |
toHex(long value)
Convenience method for "displaying" an Long value as a hex-string.
|
static boolean |
verifyAsymm(X509Certificate certificate,
SecurityAlgorithm algorithm,
byte[] data,
byte[] signature)
Verify a signature.
|
public static boolean sendNullInsteadOfEmptyNonce
@Deprecated public static byte[] asymmEncrypt(byte[] input, Key key, SecurityAlgorithm algorithm) throws InvalidKeyException, IllegalBlockSizeException, BadPaddingException, ServiceResultException, NoSuchAlgorithmException, NoSuchPaddingException
encryptAsymm(byte[], PublicKey, SecurityAlgorithm) instead.CryptoProvider.encryptAsymm(java.security.PublicKey, com.prosysopc.ua.stack.transport.security.SecurityAlgorithm, byte[], byte[], int). Deprecated: Use
encryptAsymm(byte[], java.security.PublicKey, com.prosysopc.ua.stack.transport.security.SecurityAlgorithm) instead.input - an array of byte.key - a Key object.algorithm - a SecurityAlgorithm object.InvalidKeyException - if any.IllegalBlockSizeException - if any.BadPaddingException - if any.ServiceResultException - if any.NoSuchAlgorithmException - if any.NoSuchPaddingException - if any.public static byte[] base64Decode(String string)
public static String base64Encode(byte[] bytes)
public static Mac createMac(SecurityAlgorithm algorithm, byte[] secret) throws ServiceResultException
algorithm - encryption algorithmsecret - an array of byte.ServiceResultException - Bad_SecurityPolicyRejected
algorithm not supportedpublic static ByteString createNonce(int bytes)
bytes - number of byte@Deprecated public static ByteString createNonce(SecurityAlgorithm algorithm) throws ServiceResultException
createNonce(int) and get the size from
SecurityPolicy.getSecureChannelNonceLength() directlycreateNonce.
algorithm - a SecurityAlgorithm object.ServiceResultException - if any.public static void decryptAsymm(PrivateKey decryptingKey, SecurityConfiguration profile, byte[] dataToDecrypt, byte[] output, int outputOffset) throws ServiceResultException
CryptoProvider.decryptAsymm(PrivateKey, SecurityAlgorithm, byte[], byte[], int)
Possible to use only SecurityConfiguration instead of specifying SecurityAlgorithm explicitly.decryptingKey - a PrivateKey object.profile - a SecurityConfiguration
object.dataToDecrypt - an array of byte.output - outputoutputOffset - output offsetServiceResultException - if any.public static byte[] encryptAsymm(byte[] input,
PublicKey key,
SecurityAlgorithm algorithm)
throws InvalidKeyException,
IllegalBlockSizeException,
BadPaddingException,
ServiceResultException,
NoSuchAlgorithmException,
NoSuchPaddingException
CryptoProvider.encryptAsymm(java.security.PublicKey, com.prosysopc.ua.stack.transport.security.SecurityAlgorithm, byte[], byte[], int).input - an array of byte.key - a PublicKey object.algorithm - a SecurityAlgorithm object.InvalidKeyException - if any.IllegalBlockSizeException - if any.BadPaddingException - if any.ServiceResultException - if any.NoSuchAlgorithmException - if any.NoSuchPaddingException - if any.public static void encryptAsymm(Certificate encryptingCertificate, SecurityConfiguration profile, byte[] dataToEncrypt, byte[] output, int outputOffset) throws ServiceResultException
CryptoProvider.encryptAsymm(PublicKey, SecurityAlgorithm, byte[], byte[], int) Possible
to use only Certificate and SecurityConfiguration instead of specifying PublicKey and
SecurityAlgorithm explicitly.encryptingCertificate - Certificate which public key will be used during encryption.profile - Asymmetric encryption algorithm will be taken from this SecurityConfigurationdataToEncrypt - Data to encryptoutput - outputoutputOffset - output offsetServiceResultException - if any.public static String[] filterCipherSuiteList(String[] cipherSuiteSet, String[] cipherSuitePatterns)
filterCipherSuiteList.
public static Cipher getAsymmetricCipher(SecurityAlgorithm algorithm) throws ServiceResultException
algorithm - UA Specified algorithmServiceResultException - if algorithm is not supported by
the stackpublic static int getAsymmInputBlockSize(SecurityAlgorithm algorithm) throws ServiceResultException
getAsymmInputBlockSize.
algorithm - a SecurityAlgorithm object.ServiceResultException - if any.public static int getCipherBlockSize(SecurityAlgorithm algorithm, Key key) throws ServiceResultException
algorithm - algorithmkey - Optional, required for asymmetric encryption algorithmsServiceResultException - Bad_SecurityPolicyRejected
algorithm not supportedpublic static String[] getCipherSuiteIntersection(String[] cipherSuiteSet1, String[] cipherSuiteSet2, boolean omitProtocol)
cipherSuiteSet1 - enabled cipher suitescipherSuiteSet2 - filter listomitProtocol - if true the first 3 characters are ignored in comparepublic static CryptoProvider getCryptoProvider()
CryptoProvider previously set with setCryptoProvider(CryptoProvider).
If it is not set, tries to load BouncyCastle based on the return value of
getSecurityProviderName(). Throws RuntimeException if cannot be loaded.@Deprecated public static int getNonceLength(SecurityAlgorithm algorithm) throws ServiceResultException
SecurityPolicy.getSecureChannelNonceLength() directly insteadFor symmetric algorithms, returns the algorithm key size (in bytes). For asymmetric algorithms, returns 32.
algorithm - encryption algorithm or null (=no encryption)ServiceResultException - Bad_SecurityPolicyRejected, if the
algorithm is not supportedpublic static int getPlainTextBlockSize(SecurityAlgorithm securityAlgorithm, Key key) throws ServiceResultException
securityAlgorithm - algorithmkey - Optional, required for asymmetric encryption algorithmsServiceResultException - Bad_SecurityPolicyRejected
algorithm not supportedpublic static SecureRandom getRandom()
SecureRandom instance used in crypto operations of the SDK. *
By default, this is SecureRandom.getInstance("SHA1PRNG"), which is available in
all Java systems, but may not provide the best entropy for all crypto operations. By default it
is also seeded with System.currentTimeMillis() and System.nanoTime(), to avoid
blocking at the application startup.
If setRandomReseedCount(int) is defined, the instance will also be automatically
reseeded every now and then to add more entropy to the default instance.
Use #setEnableBlockingRandomInit() to enable default initialization with system
specific (possibly blocking) algorithm, instead.
Or use setRandom(SecureRandom) to use a better entropy source than the default
implementation.
public static int getRandomReseedCount()
getRandom() will reseed the instance.public static Provider getSecurityProvider()
Provider that can be used for crypto operations.@Deprecated public static String getSecurityProviderName()
getSecurityProvider() insteadsetSecurityProviderName(String),
will return "BC". Otherwise returns the set String.@Deprecated public static String getSecurityProviderName(Class<?> clazz)
getSecurityProvider() insteadpublic static int getSignatureSize(SecurityAlgorithm signatureAlgorithm, Key key) throws ServiceResultException
signatureAlgorithm - a SecurityAlgorithm
object.key - a Key object.ServiceResultException - Bad_SecurityPolicyRejected
algorithm not supportedpublic static byte[] hexToBytes(String string)
string - the string to convertNumberFormatException - if the string is not a hexadecimal stringpublic static Integer hexToInt(String string) throws NumberFormatException
string - the string to convertNumberFormatException - if the string is not a hexadecimal stringpublic static Long hexToLong(String string)
string - the string to convertNumberFormatException - if the string is not a hexadecimal stringpublic static Long hexToLong(String string, int firstIndex, int maxLen) throws NumberFormatException
string - the string to convertfirstIndex - the first character to start parsing frommaxLen - max number of characters to parseNumberFormatException - if the string is not a hexadecimal stringpublic static void setCryptoProvider(CryptoProvider cryptoProvider)
setSecurityProviderName(String) from the given provider.cryptoProvider - the cryptoProvider to set, if null will clear the previous one.public static void setRandom(SecureRandom secureRandom)
SecureRandom instance used in crypto operations of the SDK.
By default, getRandom() is initialized with SecureRandom.getInstance(..).
On Windows 'Windows-PRNG' is used and 'NativePRNGNonBlocking' elsewhere. In case it is not
found, 'SHA1PRNG' is used as a fallback. The 'SHA1PRNG' is seeded with
System.currentTimeMillis() and System.nanoTime(), to avoid blocking at the
application startup. For the others SecureRandom.nextBytes(byte[]) is used
('Windows-PRNG' and 'NativePRNGNonBlocking' should not block here).
This should be called at the start of the application before any other interactions with the
SDK. Note that this method does call SecureRandom.setSeed(long) with
System.currentTimeMillis() and System.nanoTime(). for the given
SecureRandom. Depending on the SecureRandom you chose, you might wish to call
SecureRandom.nextBytes(byte[]) before calling this to ensure the initial seed is
obtained internally (note that this operation might block, which is why it is not done by this
method).
IllegalArgumentException - if called with nullpublic static void setRandomReseedCount(int reseedCount)
getRandom() should be reseeded automatically.
Reseeding is not a blocking operation, since it uses the system clock with nanosecond accuracy, but still need not be done too often. Good values might still be between 10 and 100.
If the value is 0, automatic reseeding will not happen.
If you wish to use the system reseeding capabilities, you should provide your own SecureRandom instance and call reseed (Java 9+) for it every now and then.
#setRandomBlockingInitEnabled(boolean),
setRandom(SecureRandom)public static void setSecurityProviderName(String securityProviderName)
NOTE! Calling this with a different provider name than previously set will reset possible calls
made to setCryptoProvider(CryptoProvider).
securityProviderName - the securityProviderName to set, e.g. "BC" for BouncyCastleProviderpublic static SignatureData signAsymm(PrivateKey signerKey, SecurityAlgorithm algorithm, byte[] dataToSign) throws ServiceResultException
signAsymm.
signerKey - the private key used to sign the dataalgorithm - asymmetric signer algorithm, See SecurityAlgorithmdataToSign - the data to signServiceResultException - if the signing fails. Read the
StatusCode and cause for more detailspublic static String toHex(byte[] bytes)
toHex(byte[], int) with bytesPerRow=0 (no line breaks)bytes - the byte array to "display"String object.public static String toHex(byte[] bytes, int bytesPerRow)
bytes - the byte array to "display"bytesPerRow - number of bytes to include on a text row. If it is 0, no line breaks are
added.String object.public static String toHex(byte[] bytes, int bytesPerRow, boolean includeLengthPrefix)
The value is always prefixed with "0x" to distinguish it from any 10-base number.
For example, if bytes = {15, 16} the string will be "0x0F10"
bytes - the byte array to "display"bytesPerRow - number of bytes to include on a text row. If it is 0, no line breaks are
added.includeLengthPrefix - if true, prefix the string with the number of bytes e.g. "[2]
0x4d6d"String object.public static String toHex(int value)
The value is always prefixed with "0x" to distinguish it from a 10-base number and it will always be of full Integer length, e.g. 8 bytes and uses lower case letters ("abcdef").
For example, value = 258 will be converted to "0x00000102", Integer.MIN_VALUE to "0x8000000" and -1 to "0xffffffff".
String object.public static String toHex(long value)
The value is always prefixed with "0x" to distinguish it from a 10-base number and it will always be of full Integer length, e.g. 16 bytes and uses lower case letters ("abcdef").
For example, value = 258 will be converted to "0x0000000000000102", Long.MIN_VALUE to "0x8000000000000000" and -1 to "0xffffffffffffffff".
String object.public static boolean verifyAsymm(X509Certificate certificate, SecurityAlgorithm algorithm, byte[] data, byte[] signature) throws ServiceResultException
certificate - the certificate used to verify the signaturealgorithm - the signature algorithmdata - data to verifysignature - the signature to verifyServiceResultException - if the verification failsCopyright © 2026. All rights reserved.