FIPS encryption policy API [duplicate] - java

How can I check, in Java code, if the current JVM have unlimited strength cryptography available?

In the same spirit as the answer of Dan Cruz, but with a single line of code and without going trough exceptions:
boolean limit = Cipher.getMaxAllowedKeyLength("RC5")<256;
So a complete program might be:
import javax.crypto.Cipher;
public class TestUCE {
public static void main(String args[]) throws Exception {
boolean unlimited =
Cipher.getMaxAllowedKeyLength("RC5") >= 256;
System.out.println("Unlimited cryptography enabled: " + unlimited);
}
}

If you are on Linux and you have installed the JDK (but Beanshell is not available), you can check with the runscript command provided with the JDK.
jrunscript -e 'exit (javax.crypto.Cipher.getMaxAllowedKeyLength("RC5") >= 256 ? 0 : 1);'; echo $?
This returns a 0 status code if the Unlimited Cryptography is available, or 1 if not available. Zero is the correct 'success' return value for shell functions, and non-zero indicates a failure.

I think you could probably use Cipher.getMaxAllowedKeyLength(), while also comparing the cypher you're using to known lists of "good", secure cyphers, such as AES.
Here's a reference article that lists maximum key size jurisdiction limitations that were current as of Java 1.4 (these likely haven't changed, unless the law has also changed - see below).
If you are operating in a nation that has cryptographic export/import restrictions, you'd have to consult the law in your nation, but it's probably safe to assume in these situations that you don't have unlimited strength cryptography available (by default) in your JVM. Putting it another way, assuming you're using the official JVM from Oracle, and you happen to live in a nation against which the U.S. has leveled export restrictions for cryptography (and since Oracle is a United States company, it would be subject to these restrictions), then you could also assume in this case that you don't have unlimited strength available.
Of course, that doesn't stop you from building your own, and thereby granting yourself unlimited strength, but depending on your local laws, that might be illegal.
This article outlines the restrictions on export to other nations, from the Unites States.

The way how to check if restrictions apply is documented in the method Cipher.getMaxAllowedKeyLength:
If JCE unlimited strength jurisdiction policy files are installed, Integer.MAX_VALUE will be returned.
This means that if any value other than (or indeed lower than) Integer.MAX_VALUE is returned that restrictions do apply.
Even more information is in the JavaDoc of the method below:
/**
* Determines if cryptography restrictions apply.
* Restrictions apply if the value of {#link Cipher#getMaxAllowedKeyLength(String)} returns a value smaller than {#link Integer#MAX_VALUE} if there are any restrictions according to the JavaDoc of the method.
* This method is used with the transform <code>"AES/CBC/PKCS5Padding"</code> as this is an often used algorithm that is an implementation requirement for Java SE.
*
* #return <code>true</code> if restrictions apply, <code>false</code> otherwise
*/
public static boolean restrictedCryptography() {
try {
return Cipher.getMaxAllowedKeyLength("AES/CBC/PKCS5Padding") < Integer.MAX_VALUE;
} catch (final NoSuchAlgorithmException e) {
throw new IllegalStateException("The transform \"AES/CBC/PKCS5Padding\" is not available (the availability of this algorithm is mandatory for Java SE implementations)", e);
}
}
Note that since Java 9 the unlimited crypto policies are installed by default (with those affected by import / export regulations having to install the limited crypto policies instead). So this code would mainly be required for backwards compatibility and/or other runtimes.

This is a complete copy paste version to allow for testing
import javax.crypto.Cipher;
import java.security.NoSuchAlgorithmException;
class Test {
public static void main(String[] args) {
int allowedKeyLength = 0;
try {
allowedKeyLength = Cipher.getMaxAllowedKeyLength("AES");
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
System.out.println("The allowed key length for AES is: " + allowedKeyLength);
}
}
To run
javac Test.java
java Test
If JCE is not working output: 128
JCE is working something like: 2147483647

If you are using Linux, you can check it easily with this command
java -version ; \
echo 'System.err.println(javax.crypto.Cipher.getInstance("AES/CBC/PKCS5Padding").getMaxAllowedKeyLength("AES"));' \
| java -cp /usr/share/java/bsh-*.jar bsh.Interpreter >/dev/null
If the output is something like that, unlimited strength cryptography is not available
java version "1.7.0_76"
Java(TM) SE Runtime Environment (build 1.7.0_76-b13)
Java HotSpot(TM) 64-Bit Server VM (build 24.76-b04, mixed mode)
128

You can check it in one step from the command line by using groovy :
groovysh -e 'javax.crypto.Cipher.getMaxAllowedKeyLength("AES")'
If the result is 2147483647, you have unlimited cryptography.
On older version of groovy, you have to remove the -e :
groovysh 'javax.crypto.Cipher.getMaxAllowedKeyLength("AES")'

NOTE: Please use jefflunt's answer or KonstantinSpirov's answer. This answer is not a valid answer since it will always return true. I am leaving this answer here only because it is referenced elsewhere in answers and comments and is useful as a reference only.
You could use the following to initialize a static final boolean somewhere that you can then use for testing unlimited crypto support (since AES 256-bit is only supported if the unrestricted policy is installed).
boolean isUnlimitedSupported = false;
try {
KeyGenerator kgen = KeyGenerator.getInstance("AES", "SunJCE");
kgen.init(256);
isUnlimitedSupported = true;
} catch (NoSuchAlgorithmException e) {
isUnlimitedSupported = false;
} catch (NoSuchProviderException e) {
isUnlimitedSupported = false;
}
System.out.println("isUnlimitedSupported=" + isUnlimitedSupported);
// set static final variable = isUnlimitedSupported;

I recently had to do add a JCE check and my solution evolved to the following snippet. This was a groovy script, but it should be easy to convert to standard java method with a try catch. This has been tested with Java 7 & Java 8.
import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import javax.crypto.SecretKey;
// Make a blank 256 Bit AES Key
final SecretKey secretKey = new SecretKeySpec(new byte[32], "AES");
final Cipher encryptCipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
// This line will throw a invalid key length exception if you don't have
// JCE Unlimited strength installed
encryptCipher.init(Cipher.ENCRYPT_MODE, secretKey);
// If it makes it here, you have JCE installed

Related

Why does the following SecureRandom NativePRNG fail on windows?

import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
public class Main {
public static void main(String[] args) throws NoSuchAlgorithmException {
SecureRandom srand = SecureRandom.getInstance("NativePRNG");
System.out.println(srand.nextInt());
}
}
How to run with NativePRNG on windows?
UPD:
By default, in Java 10+, \<JDK>\conf\security\java.security file,
crypto.policy=unlimited. sp nothing need to be changed for Java 10+ in java.security file.
And to use NativePRNG algorithm, we can change it to Windows-PRNG.
SecureRandom srand = SecureRandom.getInstance("Windows-PRNG");
System.out.println(srand.nextInt());
The reason the code fails on Windows is because the "NativePRNG" algorithm is not available on all platforms, including Windows. This is because "NativePRNG" relies on platform-specific sources of randomness, and the implementation may vary across different operating systems.
To run with "NativePRNG" on Windows, you can install the Java Cryptography Extension (JCE) Unlimited Strength Jurisdiction Policy Files, which includes a "NativePRNG" implementation for Windows. Once you have installed the JCE Unlimited Strength Policy Files, you can modify the code to explicitly specify the "NativePRNG" algorithm provider:
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
public class Main {
public static void main(String[] args) throws NoSuchAlgorithmException {
SecureRandom srand = SecureRandom.getInstance("NativePRNG", "SUN");
System.out.println(srand.nextInt());
}
}
Note that you should replace "SUN" with the name of the provider that supports the "NativePRNG" algorithm on your specific platform, as different providers may support different algorithms on different platforms.

Jasypt: Encryption successful but decryption fails for stronger algorithms

I am using Jasypt's CLI for testing encryption and decryption. The encryption is successful for all the algorithms but decryption fails for stronger algorithms. Here is the encryption and decryption for PBEWithMD5AndDES:
Encryption:
prakash#prakash:~$ java -cp ~/.m2/repository/org/jasypt/jasypt/1.9.2/jasypt-1.9.2.jar org.jasypt.intf.cli.JasyptPBEStringEncryptionCLI password=secret algorithm=PBEWITHMD5ANDDES input=encryptThis
----ENVIRONMENT-----------------
Runtime: Oracle Corporation OpenJDK 64-Bit Server VM 11.0.2+9-Ubuntu-3ubuntu118.04.3
----ARGUMENTS-------------------
input: encryptThis
password: secret
algorithm: PBEWITHMD5ANDDES
----OUTPUT----------------------
pZRJ9Egt+OcjBX28cSJUYDbvqiKIUVxR
Decryption:
prakash#prakash:~$ java -cp ~/.m2/repository/org/jasypt/jasypt/1.9.2/jasypt-1.9.2.jar org.jasypt.intf.cli.JasyptPBEStringDecryptionCLI password=secret algorithm=PBEWITHMD5ANDDES input=pZRJ9Egt+OcjBX28cSJUYDbvqiKIUVxR
----ENVIRONMENT-----------------
Runtime: Oracle Corporation OpenJDK 64-Bit Server VM 11.0.2+9-Ubuntu-3ubuntu118.04.3
----ARGUMENTS-------------------
input: pZRJ9Egt+OcjBX28cSJUYDbvqiKIUVxR
password: secret
algorithm: PBEWITHMD5ANDDES
----OUTPUT----------------------
encryptThis
Now If I change the algorithm to PBEWITHHMACSHA1ANDAES_128, here are the results:
Encryption:
prakash#prakash:~$ java -cp ~/.m2/repository/org/jasypt/jasypt/1.9.2/jasypt-1.9.2.jar org.jasypt.intf.cli.JasyptPBEStringEncryptionCLI password=secret algorithm=PBEWITHHMACSHA1ANDAES_128 input=encryptThis
----ENVIRONMENT-----------------
Runtime: Oracle Corporation OpenJDK 64-Bit Server VM 11.0.2+9-Ubuntu-3ubuntu118.04.3
----ARGUMENTS-------------------
input: encryptThis
password: secret
algorithm: PBEWITHHMACSHA1ANDAES_128
----OUTPUT----------------------
tAIe6mUS6uBCG/OkHJWT2LWRagHOMBxwK/v9L7SGZIA=
Decryption:
prakash#prakash:~$ java -cp ~/.m2/repository/org/jasypt/jasypt/1.9.2/jasypt-1.9.2.jar org.jasypt.intf.cli.JasyptPBEStringDecryptionCLI password=secret algorithm=PBEWITHHMACSHA1ANDAES_128 input=tAIe6mUS6uBCG/OkHJWT2LWRagHOMBxwK/v9L7SGZIA=
----ENVIRONMENT-----------------
Runtime: Oracle Corporation OpenJDK 64-Bit Server VM 11.0.2+9-Ubuntu-3ubuntu118.04.3
----ARGUMENTS-------------------
input: tAIe6mUS6uBCG/OkHJWT2LWRagHOMBxwK/v9L7SGZIA=
password: secret
algorithm: PBEWITHHMACSHA1ANDAES_128
----ERROR-----------------------
Operation not possible (Bad input or parameters)
The jasypt version I'm using is 2.0.0 and I've tried this on both java-8 and java-11. In both the machines I've JCE's unlimited strength policy enabled.
The list of Algorithms that were decrypted successfully are:
PBEWITHMD5ANDDES,
PBEWITHMD5ANDTRIPLEDES,
PBEWITHSHA1ANDDESEDE,
PBEWITHSHA1ANDRC2_128,
PBEWITHSHA1ANDRC2_40,
PBEWITHSHA1ANDRC4_128,
PBEWITHSHA1ANDRC4_40.
The algorithms with which decryption fails are:
PBEWITHHMACSHA1ANDAES_128
PBEWITHHMACSHA1ANDAES_256
PBEWITHHMACSHA224ANDAES_128
PBEWITHHMACSHA224ANDAES_256
PBEWITHHMACSHA256ANDAES_128
PBEWITHHMACSHA256ANDAES_256
PBEWITHHMACSHA384ANDAES_128
PBEWITHHMACSHA384ANDAES_256
PBEWITHHMACSHA512ANDAES_128
PBEWITHHMACSHA512ANDAES_256.
I've been stuck at this problem for three days. Someone please help me out!
Edit:
After suggestions from Maarten, I went ahead and copied the code from JasyptPBEStringDecryptionCLI and made my own class in hope to reproduce the error through code and get the stacktrace.
Here is the code I wrote:
package com.example.HelloWorldApiUbuntu;
import java.util.Properties;
import org.jasypt.intf.service.JasyptStatelessService;
public class TestingJasyptStringDecryptionCLI {
public static void main(final String[] args) throws Exception{
final JasyptStatelessService service = new JasyptStatelessService();
String input = "P/25Hp3CKdFj7pz85eJyHETugwX5ZxWEF7PpzJ/fBGI=";
final String result =
service.decrypt(
input,
"secret",
null,
null,
"PBEWITHHMACSHA512ANDAES_128",
null,
null,
"1000",
null,
null,
"org.jasypt.salt.RandomSaltGenerator",
null,
null,
"SunJCE",
null,
null,
/*argumentValues.getProperty(ArgumentNaming.ARG_PROVIDER_CLASS_NAME)*/null,
null,
null,
/*argumentValues.getProperty(ArgumentNaming.ARG_STRING_OUTPUT_TYPE)*/null,
null,
null);
System.out.println(result);
}
}
This class produces same behaviour as JasyptPBEStringDecryptionCLI and works for same algorithms listed above and fails on stronger ones.
Here is the little error stacktrace:
Exception in thread "main" org.jasypt.exceptions.EncryptionOperationNotPossibleException
at org.jasypt.encryption.pbe.StandardPBEByteEncryptor.decrypt(StandardPBEByteEncryptor.java:1055)
at org.jasypt.encryption.pbe.StandardPBEStringEncryptor.decrypt(StandardPBEStringEncryptor.java:725)
at org.jasypt.intf.service.JasyptStatelessService.decrypt(JasyptStatelessService.java:595)
at com.example.HelloWorldApiUbuntu.TestingJasyptStringDecryptionCLI.main(TestingJasyptStringDecryptionCLI.java:12)
I know the problem is with jasypt and not my java because I ran this code to test encryption-decryption on my local with stronger algorithms and it works perfectly.
Edit 2: I also tried the solution given at https://github.com/melloware/jasypt, it gives me the same result.
It works with Jasypt 1.9.3 with additional parameter ivGeneratorClassName=org.jasypt.iv.RandomIvGenerator
Encryption:
java -cp ~/.m2/repository/org/jasypt/jasypt/1.9.3/jasypt-1.9.2.jar org.jasypt.intf.cli.JasyptPBEStringEncryptionCLI password=secret algorithm=PBEWITHHMACSHA1ANDAES_128 input=encryptThis ivGeneratorClassName=org.jasypt.iv.RandomIvGenerator
Decryption:
java -cp ~/.m2/repository/org/jasypt/jasypt/1.9.3/jasypt-1.9.2.jar org.jasypt.intf.cli.JasyptPBEStringDecryptionCLI password=secret algorithm=PBEWITHHMACSHA1ANDAES_128 input=j5oaiHBv5RB8MOxQekM/b/AMWxgOCmgB91X/ObBpyA0lr57z7ecrcVGZN0LtcFan ivGeneratorClassName=org.jasypt.iv.RandomIvGenerator
This is a bug in jasypt. it fixed with this patch. See this link too. I fixed my similar problem with this patch and version 1.9.4 CLI.

Why is -XX:ReservedCodeCacheSize not getting applied?

I tried to understand how -XX:ReservedCodeCacheSize=512m works but it did not get applied when running java as follows:
java --version -XX:ReservedCodeCacheSize=512m
It simply set to the default 48M on x86 at this point:
define_pd_global(uintx, ReservedCodeCacheSize, 48*M);
And then got 5 times increased at that point:
// Increase the code cache size - tiered compiles a lot more.
if (FLAG_IS_DEFAULT(ReservedCodeCacheSize)) {
FLAG_SET_ERGO(uintx, ReservedCodeCacheSize,
MIN2(CODE_CACHE_DEFAULT_LIMIT, (size_t)ReservedCodeCacheSize * 5));
}
causing reservation code space to 48*5 M instead of the value I configured:
size_t cache_size = ReservedCodeCacheSize;
//...
ReservedCodeSpace rs = reserve_heap_memory(cache_size);
I first though that ReservedCodeCacheSize is a development option and therefore not allowed to be overriden, but it is marked as product here so this is not the case.
What's wrong and why was the option silently ignored?
--version is a terminal option. JVM flags should precede terminal options.
Try java -XX:ReservedCodeCacheSize=512m --version

Java - getOpenFileDescriptorCount for Windows

How to get the number of open File descriptors under Windows?
On unix there is this:
UnixOperatingSystemMXBean.getOpenFileDescriptorCount()
But there doesn't seem to be an equivalent for windows?
This was going to be a comment but got a little long winded.
Conflicting answers as to why there may be a lack of equivalence here on ServerFault: Windows Server 2008 R2 max open files limit. TLDR: Windows is only limited by available hardware vs Windows is limited by 32 vs 64 bit implementation (MS Technet Blog Post - Pushing the Limits of Windows: Handles). Granted, this is old information.
But! if you note the JavaDocs for the com.sun.management package, you will of course note the conspicuous absence of a Windows version of the the UnixOperatingSystemMXBean that would extend OperatingSystemMXBean to provide the functionality. Even UnixOperatingSystemMXBean only exists to provide getMaxFileDescriptorCount() and getOpenFileDescriptorCount() so it seems unlikely that Windows has the same concept.
Edit:
I did find a nice little program that sort of shows this off, which I tweaked.
Descriptors.java
import java.lang.management.ManagementFactory;
import java.lang.management.OperatingSystemMXBean;
import java.lang.reflect.Method;
class Descriptors {
public static void main(String [ ] args) {
System.out.println(osMxBean.getClass().getName());
OperatingSystemMXBean osMxBean = ManagementFactory.getOperatingSystemMXBean();
try {
Method getMaxFileDescriptorCountField = osMxBean.getClass().getDeclaredMethod("getMaxFileDescriptorCount");
Method getOpenFileDescriptorCountField = osMxBean.getClass().getDeclaredMethod("getOpenFileDescriptorCount");
getMaxFileDescriptorCountField.setAccessible(true);
getOpenFileDescriptorCountField.setAccessible(true);
System.out.println(getOpenFileDescriptorCountField.invoke(osMxBean) + "/" + getMaxFileDescriptorCountField.invoke(osMxBean));
} catch (Exception e) {
e.printStackTrace();
}
}
}
On Linux:
com.sun.management.UnixOperatingSystem
11/2048
On Windows:
sun.management.OperatingSystemImpl
java.lang.NoSuchMethodException:
sun.management.OperatingSystemImpl.getMaxFileDescriptorCount()
at java.lang.Class.getDeclaredMethod(Unknown Source)
at Descriptors.main(Descriptors.java:10)

32-Bit 64-Bit Difference While Calculating Cipher

I have a simple Xades/BES implementation and two situations.
On Windows 7 32Bit
with java
java version "1.7.0_25"
Java(TM) SE Runtime Environment (build 1.7.0_25-b17)
Java HotSpot(TM) Client VM (build 23.25-b01, mixed mode)
On Windows 2008 Server 64 Bit, and with the same JVM.
My application works perfectly fine on 32 bit Windows 7, however when I try to run the compiled code in Windows 2008 Server I get an error:
javax.crypto.BadPaddingException: Data must start with zero
at sun.security.rsa.RSAPadding.unpadV15(Unknown Source)
at sun.security.rsa.RSAPadding.unpad(Unknown Source)
at com.sun.crypto.provider.RSACipher.doFinal(RSACipher.java:349)
at com.sun.crypto.provider.RSACipher.engineDoFinal(RSACipher.java:382)
at javax.crypto.Cipher.doFinal(Cipher.java:2087)
Problematic code field is as follows:
public static byte[] getDecryptedSignatureValue(XMLSignature signature) throws XadesElementException, InvalidKeyException
{
byte[] signatureValue = null;
try {
KeyInfo keyInfo = signature.getKeyInfo();
PublicKey key = keyInfo.getPublicKey();
Cipher cipher = getCipher("RSA/ECB/PKCS1Padding");
cipher.init(Cipher.DECRYPT_MODE, key);
signatureValue = signature.getSignatureValue();
byte[] cipherData = cipher.doFinal(signatureValue);
return cipherData;
} catch (KeyResolverException | XMLSignatureException | IllegalBlockSizeException | BadPaddingException ex) {
Logger.getLogger(KeyUtils.class.getName()).log(Level.SEVERE, null, ex);
Logger.getLogger(KeyUtils.class.getName()).log(Level.SEVERE, null, "SignatureValue:"+ BaseUtils.toBase64String(signatureValue));
} finally {
}
return null;
}
The only thing I can come up with is the architecture difference. Am I missing something here? What can be the problem?
Thanks in advance.
EDIT:
Here are my new findings.
1. I have tested my application on Windows 7 64 bit and there was no problem, while signing and verifying.
2. More interestingly, I have tested the application on another Windows 2008 Server 64 bit and it worked with a success.
I think there is a configuration setting for something but I could not figure it out what.
This is likely due to the chosen provider and/or provider implementation. Note that there is a difference between PKCS#1 padding for encryption (EME-PKCS1-v1_5 decoding) and PKCS#1 padding for signature verification (EMSA-PKCS1-v1_5 encoding). Some providers will choose a padding depending on the key type (public or private), others will keep to a single padding scheme depending if you are using Cipher or Signature.
If possible try and use Signature for signature verification, not Cipher decryption with a public key. Otherwise check which providers are chosen (using e.g. Cipher.getProvider() and try to find one that works. Note that - as you may already have discovered - it depends on the implementation, not on the interface specification if decryption succeeds or fails.
So currently it is trying to decode this:
EM = 0x00 || 0x02 || PS || 0x00 || M
with a random, nonzero PS and message M
You expect however to verify this:
EM = 0x00 || 0x01 || PS || 0x00 || T
with a PS with values FF, and T being an ASN.1 DER encoded algorithm OID and hash value.

Categories