Weblogic - java.lang.ClassNotFoundException: org.bouncycastle.jce.provider.JCEMac$DES9797Alg3 - java

I am working with a Java Web application and I need to generate a MAC using 3DES algorithm. Code is working without problems on a Weblogic 10.3 but the problem came when I tried to run the application in a different Weblogic, similar version (10.3.1).
This is my code:
public String getMac(String inkey, String data) throws Exception {
byte[] out = new byte[8];
try {
// if I commend this line, the result is the same
Security.addProvider(new BouncyCastleProvider());
// this loop proves the BC provider is there
for (Provider p : Security.getProviders()) {
log.debug("--");
log.debug(p.getName());
log.debug(p.getInfo());
}
try {
BouncyCastleProvider bc = new BouncyCastleProvider();
// class is there, no problem
log.debug("info" + bc.getInfo());
DES9797Alg3 alg3 = new DES9797Alg3();
// class is there, no problem
log.debug("alg3" + alg3.toString());
} catch (Exception e) {
log.error("error BouncyCastleProvider classes");
}
log.debug("length: " + inkey.length());
if (inkey.length() < 48)
inkey += inkey.substring(0, 16);
byte[] rawkey = hexStringToByteArray(inkey);
DESedeKeySpec keyspec = new DESedeKeySpec(rawkey);
SecretKeyFactory keyfactory = SecretKeyFactory.getInstance("DESede");
SecretKey key = keyfactory.generateSecret(keyspec);
Mac mac = Mac.getInstance("ISO9797Alg3Mac");
mac.init(key);
mac.update(data.getBytes());
mac.doFinal(out, 0);
} catch (Exception e) {
log.error("Error generating MAC X9_19", e);
throw new Exception("Error generating MAC X9_19", e);
}
And this is the error I get:
Caused by: java.security.InvalidKeyException: No installed provider supports this key: com.sun.crypto.provider.DESedeKey
at javax.crypto.Mac.a(DashoA13*..)
at javax.crypto.Mac.init(DashoA13*..)
at es.indra.netplus.sec.services.util.UtilMac.getMac(UtilMac.java:180)
... 73 more
Caused by: java.security.NoSuchAlgorithmException: class configured for Mac(provider: BC)cannot be found.
at java.security.Provider$Service.getImplClass(Provider.java:1268)
at java.security.Provider$Service.newInstance(Provider.java:1220)
... 76 more
Caused by: java.lang.ClassNotFoundException: org.bouncycastle.jce.provider.JCEMac$DES9797Alg3
at weblogic.utils.classloaders.GenericClassLoader.findLocalClass(GenericClassLoader.java:283)
at weblogic.utils.classloaders.GenericClassLoader.findClass(GenericClassLoader.java:256)
at weblogic.utils.classloaders.ChangeAwareClassLoader.findClass(ChangeAwareClassLoader.java:54)
at java.lang.ClassLoader.loadClass(ClassLoader.java:307)
at java.lang.ClassLoader.loadClass(ClassLoader.java:248)
at weblogic.utils.classloaders.GenericClassLoader.loadClass(GenericClassLoader.java:176)
at weblogic.utils.classloaders.ChangeAwareClassLoader.loadClass(ChangeAwareClassLoader.java:35)
at java.security.Provider$Service.getImplClass(Provider.java:1262)
I do no understand why error says that org.bouncycastle.jce.provider.JCEMac$DES9797Alg3 is not there. It is possible that 'java.security' is looking in another place? I have requested to the server administrator to copy the library in the endorsed directory, but not I am not sure if this is going to work and way this is happening.
Notice that even if I remove 'Security.addProvider(new BouncyCastleProvider());' line, in the list of available providers, BC is listed.
This is the list of providers I got:
-- -- --
CSSX509CertificateFactoryProvider
CSS JDK CertPath provider
1.0
-- -- --
SUN
SUN (DSA key/parameter generation; DSA signing; SHA-1, MD5 digests; SecureRandom; X.509 certificates; JKS keystore; PKIX CertPathValidator; PKIX CertPathBuilder; LDAP, Collection CertStores, JavaPolicy Policy; JavaLoginConfig Configuration)
1.6
-- -- --
SunRsaSign
Sun RSA signature provider
1.5
-- -- --
SunJSSE
Sun JSSE provider(PKCS12, SunX509 key/trust factories, SSLv3, TLSv1)
1.6
-- -- --
SunJCE
SunJCE Provider (implements RSA, DES, Triple DES, AES, Blowfish, ARCFOUR, RC2, PBE, Diffie-Hellman, HMAC)
1.6
-- -- --
SunJGSS
Sun (Kerberos v5, SPNEGO)
1.0
-- -- --
SunSASL
Sun SASL provider(implements client mechanisms for: DIGEST-MD5, GSSAPI, EXTERNAL, PLAIN, CRAM-MD5; server mechanisms for: DIGEST-MD5, GSSAPI, CRAM-MD5)
1.5
-- -- --
XMLDSig
XMLDSig (DOM XMLSignatureFactory; DOM KeyInfoFactory)
1.0
-- -- --
SunPCSC
Sun PC/SC provider
1.6
-- -- --
WebLogicCertPathProvider
WebLogic CertPath Provider JDK CertPath provider
1.0
-- -- --
WLSJDKCertPathProvider
WebLogic JDK CertPath provider
1.0
-- -- --
BC
BouncyCastle Security Provider v1.46
1.46
BC is there, moreover, the same version I got inside my war file.
I have googled many hours with no luck, hope someone can point me to the right direction.

After spending many hours on google trying to fix the error doing change in the code, the problem was solved adding the library in the server domain lib directory. Anyway, I still do not understand why this happens.

Related

Could not load [org.bouncycastle.jcajce.provider.digest.GOST3411$Mappings]

I am using tomcat8 Server, .bouncycastle for Document signature.
one war file already running on my server. when i have deployed new war file for my second project then Getting below exception.
I have hit and trial every link on stackoverflow but not luck
org.apache.catalina.loader.WebappClassLoaderBase.checkStateForResourceLoading
Illegal access: this web application instance has been stopped
already. Could not load
[org.bouncycastle.jcajce.provider.digest.GOST3411$Mappings]. The
following stack trace is thrown for debugging purposes as well as to
attempt to terminate the thread which caused the illegal access.
java.lang.IllegalStateException: Illegal access: this web application
instance has been stopped already. Could not load
public static void xmlSigner(File xmlFile,String pfxFilePath){
try{
File pfxFile=new File(pfxFilePath);
Security.addProvider(new BouncyCastleProvider());
log.info("Above key store ");
KeyStore keyStore = KeyStore.getInstance("pkcs12", "BC");
log.info("below key store ");
keyStore.load(new FileInputStream(pfxFile),password.toCharArray());
log.info("load pfx file key store ");
String alias = (String) keyStore.aliases().nextElement();
PrivateKey privateKey = (PrivateKey) keyStore.getKey(alias, password.toCharArray());
Certificate[] certificateChain = keyStore.getCertificateChain(alias);
X509Certificate publickeyCertificate = (X509Certificate) certificateChain[certificateChain.length - 1];
//log.info("privateKey : " + privateKey);
//log.info("xmlSigner : " + xmlFile);
log.info("SignerClient - Above Sign and Zip");
SignerUtil.signAndzipFile(xmlFile, privateKey, publickeyCertificate);
log.info("Successfully Signed");
}
catch(Exception xmlSignerException){
log.error("xmlSigner : ", xmlSignerException);
xmlSignerException.printStackTrace();
}
}
i am getting exception on below line
KeyStore keyStore = KeyStore.getInstance("pkcs12", "BC");
I have face the same issue, Tomcat restart has resolved the issue.
keystore = KeyStore.getInstance("PKCS12", "BC");
// java.security.KeyStoreException: PKCS12 not found
Caused by: java.security.NoSuchAlgorithmException: class configured for KeyStore (provider: BC) cannot be found.
at java.security.Provider$Service.getImplClass(Provider.java:1649)
at java.security.Provider$Service.newInstance(Provider.java:1592)
at sun.security.jca.GetInstance.getInstance(GetInstance.java:236)
at sun.security.jca.GetInstance.getInstance(GetInstance.java:206)
at java.security.Security.getImpl(Security.java:698)
at java.security.KeyStore.getInstance(KeyStore.java:896)
... 11 more
Caused by: java.lang.ClassNotFoundException: Illegal access: this web application instance has been stopped already. Could not load [org.bouncycastle.jcajce.provider.keystore.pkcs12.PKCS12KeyStoreSpi$BCPKCS12KeyStore]. The following stack trace is thrown for debugging purposes as well as to attempt to terminate the thread which caused the illegal access.
at org.apache.catalina.loader.WebappClassLoaderBase.checkStateForClassLoading(WebappClassLoaderBase.java:1354)
at org.apache.catalina.loader.WebappClassLoaderBase.loadClass(WebappClassLoaderBase.java:1211)
at org.apache.catalina.loader.WebappClassLoaderBase.loadClass(WebappClassLoaderBase.java:1172)
at java.security.Provider$Service.getImplClass(Provider.java:1636)
... 16 more
Caused by: java.lang.IllegalStateException: Illegal access: this web application instance has been stopped already. Could not load [org.bouncycastle.jcajce.provider.keystore.pkcs12.PKCS12KeyStoreSpi$BCPKCS12KeyStore]. The following stack trace is thrown for debugging purposes as well as to attempt to terminate the thread which caused the illegal access.
at org.apache.catalina.loader.WebappClassLoaderBase.checkStateForResourceLoading(WebappClassLoaderBase.java:1364)
at org.apache.catalina.loader.WebappClassLoaderBase.checkStateForClassLoading(WebappClassLoaderBase.java:1352)
... 19 more
Please first check that org.bouncycastle has many versions. Keep one version, and if use tomcat, restart tomcat.

Java 8u201: no cipher suites in common [duplicate]

I recently added SSL to my website and it can be accessed over https. Now when my java application tries to make requests to my website and read from it with a buffered reader it produces this stack trace
Im not using a self signed certificate the cert is from Namecheap who uses COMODO SSL as the CA to sign my certificate. im using java 8
javax.net.ssl.SSLHandshakeException: No appropriate protocol (protocol is disabled or cipher suites are inappropriate)
at sun.security.ssl.Handshaker.activate(Handshaker.java:503)
at sun.security.ssl.SSLSocketImpl.kickstartHandshake(SSLSocketImpl.java:1482)
at sun.security.ssl.SSLSocketImpl.performInitialHandshake(SSLSocketImpl.java:1351)
at sun.security.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:1403)
at sun.security.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:1387)
at sun.net.www.protocol.https.HttpsClient.afterConnect(HttpsClient.java:559)
My code is very basic and simply tries to read the page on my site using a buffered reader
private void populateDataList() {
try {
URL url = new URL("https://myURL.com/Data/Data.txt");
URLConnection con = url.openConnection();
con.setRequestProperty("Connection", "close");
con.setDoInput(true);
con.setUseCaches(false);
BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
String line;
int i = 0;
while((line = in.readLine()) != null) {
this.url.add(i, line);
i++;
}
} catch (Exception e) {
e.printStackTrace();
}
}
Ive tried adding my SSL certificate to the JVM's Keystore and Ive also even tried to accept every certificate (which defeats the purpose of SSL I know) with this code
private void trustCertificate() {
TrustManager[] trustAllCerts = new TrustManager[] {
new X509TrustManager() {
public java.security.cert.X509Certificate[] getAcceptedIssuers() {
return new X509Certificate[0];
}
public void checkClientTrusted(
java.security.cert.X509Certificate[] certs, String authType) {
}
public void checkServerTrusted(
java.security.cert.X509Certificate[] certs, String authType) {
}
}
};
try {
SSLContext sc = SSLContext.getInstance("TLS");
sc.init(null, trustAllCerts, new java.security.SecureRandom());
HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
} catch (GeneralSecurityException e) {
}
try {
URL url = new URL("https://myURL.com/index.php");
URLConnection con = url.openConnection();
BufferedReader br = new BufferedReader(new InputStreamReader(con.getInputStream()));
String line;
while((line = br.readLine()) != null) {
System.out.println(line);
}
} catch (Exception e) {
}
}
Im stumped and any help would be much appreciated!
In $JRE/lib/security/java.security:
jdk.tls.disabledAlgorithms=SSLv3, TLSv1, RC4, DES, MD5withRSA, DH keySize < 1024, \
EC keySize < 224, 3DES_EDE_CBC, anon, NULL
This line is enabled, after I commented out this line, everything is working fine. Apparently after/in jre1.8.0_181 this line is enabled.
My Java version is "1.8.0_201.
I also run into this with the Java8 update 1.8.0.229 on Ubuntu 18.04.
I changed the following part:
# Example:
# jdk.tls.disabledAlgorithms=MD5, SSLv3, DSA, RSA keySize < 2048
#jdk.tls.disabledAlgorithms=SSLv3, TLSv1, TLSv1.1, RC4, DES, MD5withRSA, \
# DH keySize < 1024, EC keySize < 224, 3DES_EDE_CBC, anon, NULL, \
# include jdk.disabled.namedCurves
jdk.tls.disabledAlgorithms=SSLv3, RC4, DES, MD5withRSA, \
DH keySize < 1024, EC keySize < 224, 3DES_EDE_CBC, anon, NULL, \
include jdk.disabled.namedCurves
I removed TLSv1 and TLSv1.1 from the list of jdk.tls.disabledAlgorithms inside the file
/etc/java-8-openjdk/security/java.security
After checking this:
Welcome to the MySQL monitor. Commands end with ; or \g.
Your MySQL connection id is 28
Server version: 5.7.33-0ubuntu0.18.04.1 (Ubuntu)
Copyright (c) 2000, 2021, Oracle and/or its affiliates.
Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.
Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.
mysql> SHOW GLOBAL VARIABLES LIKE 'tls_version';
+---------------+-----------------------+
| Variable_name | Value |
+---------------+-----------------------+
| tls_version | TLSv1,TLSv1.1,TLSv1.2 |
+---------------+-----------------------+
1 row in set (0.00 sec)
mysql> exit
protocol is disabled or cipher suites are inappropriate
The key to the problem lies in that statement. What it basically means is either:
The TLS implementation used by the client does not support the cipher suites used by the server's certificate.
The TLS configuration on the server has disabled cipher suites supported by the client.
The TLS configurations on the client disable cipher suites offered by the server.
TLS version incompatibility between the client and server.
This leads to handshake failure in TLS, and the connection fails. Check one or all of the three scenarios above.
You can add the expected TLS protocol to your connection string like this:
jdbc:mysql://localhost:3306/database_name?enabledTLSProtocols=TLSv1.2
That fixed the problem for me.
Edit 04-02-2022:
As Yair's comment says:
Since Connector/J 8.0.28 enabledTLSProtocols has been renamed to tlsVersions.
In my case I am runnig Centos 8 and had the same issue with Imap/Java.
Had to update the system-wide cryptographic policy level.
update-crypto-policies --set LEGACY
reboot machine.
Thats it.
https://access.redhat.com/documentation/en-us/red_hat_enterprise_linux/8/html/considerations_in_adopting_rhel_8/security_considerations-in-adopting-rhel-8#tls-v10-v11_security
We started experiencing this problem after upgrading to jre1.8.0_291. I commented out "jdk.tls.disabledAlgorithms=SSLv3, TLSv1, TLSv1.1, RC4, DES, MD5withRSA,
DH keySize < 1024, EC keySize < 224, 3DES_EDE_CBC, anon, NULL,
include jdk.disabled.namedCurves" in java.security located in C:\Program Files\Java\jre1.8.0_291\lib\security which resolved the problem.
javax.net.ssl.SSLHandshakeException: No appropriate protocol (protocol is disabled or cipher suites are inappropriate)
For posterity, I recently bumped up against this using IBM's JDK8 implementation which specifically disables TLS1.1 and 1.2 by default (sic). If you want to see what TLS versions are supported by the JVM, run something like the following code:
SSLContext context = SSLContext.getInstance("TLS");
context.init(null, null, null);
String[] supportedProtocols = context.getDefaultSSLParameters().getProtocols();
System.out.println(Arrays.toString(supportedProtocols));
The code spits out [TLSv1] by default under AIX JDK8. Not good. Under Redhat and Solaris it spits out [TLSv1, TLSv1.1, TLSv1.2].
I could not find any values in the java.security file to fix this issue but there might be some for your architecture. In the IBM specific case, we have to add:
-Dcom.ibm.jsse2.overrideDefaultTLS=true
In my case I had to upgrade the mysql client library to the latest version and it started working again:
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.24</version>
</dependency>
I have encountered
javax.net.ssl.SSLHandshakeException: No appropriate protocol (protocol is disabled or cipher suites are inappropriate)
error when accessing TLS 1.3 enabled endpoint from a Java 11 application. That is a usual case in GCP, for example.
The problem has gone away without any changes in my code just by upgrading from Java 11 to Java 14.
The Java 11 doesn't deprecate earlier TLS protocol versions by default. Instead of configuring it, simple upgrade of the runtime to Java 14 has helped.
Apparently, if you have TLS 1.0 disabled the emails won't be sent out. TLS Versions 1.1 and 1.2 do not work. Peter's suggestion did the trick for me.
I was face with the same situation on a tomcat7 server, 5.7.34-0ubuntu0.18.04.1, openjdk version "1.8.0_292"
I tried many approaches like disabling SSL in the server.xml file, changing the connection strings etc etc
but in the end all i did was to edit the file java.security with
sudo nano /usr/lib/jvm/java-8-openjdk-amd64/jre/lib/security/java.security
comment out and remove TLSv1 and TLSv1.1
# Comment the line below
#jdk.tls.disabledAlgorithms=SSLv3, TLSv1, TLSv1.1, RC4, DES, MD5withRSA, \
# DH keySize < 1024, EC keySize < 224, 3DES_EDE_CBC, anon, NULL, \
# include jdk.disabled.namedCurves
# your new line should read as beloew
jdk.tls.disabledAlgorithms=SSLv3, RC4, DES, MD5withRSA, \
DH keySize < 1024, EC keySize < 224, 3DES_EDE_CBC, anon, NULL, \
include jdk.disabled.namedCurves
For ME in this case :
javax.net.ssl.SSLHandshakeException: No appropriate protocol (protocol is disabled or cipher suites are inappropriate)
I found that this is JDK/JRE (Java\jdk1.8.0_291\jre\lib\security) config related, and in order to solve it you need to Disable the TLS anon and NULL cipher suites.
You can found how to do this in the oficial documentation here:
https://www.java.com/en/configure_crypto.html
Also before doing this, consider the implications of using LEGACY algorithms.
upgraded from 1 to 2 + modifying the $JRE/lib/security/java.security file did the trick.
before after mysql driver

How to resolve java.security.InvalidKeyException while configuring MFA in WSO2 identity server 5.5.0

I'm using wso2is-5.5.0. I'm trying to enable Multi factor authentication for Identity Server. I have done by following this link https://docs.wso2.com/display/IS530/Configuring+Multi-factor+Authentication+for+WSO2+IS. After restarting while login to management console, it is redirecting to one page showing
SAML 2.0 based Single Sign-On
Error when processing authentication request!
Please try login again!
In console,
Caused by: org.apache.xml.security.encryption.XMLEncryptionException: Illegal key size or default pa
rameters
Original Exception was java.security.InvalidKeyException: Illegal key size or default parameters
at org.apache.xml.security.encryption.XMLCipher.encryptData(XMLCipher.java:1140)
at org.apache.xml.security.encryption.XMLCipher.encryptData(XMLCipher.java:1083)
at org.opensaml.xml.encryption.Encrypter.encryptElement(Encrypter.java:452)
... 66 more
Caused by: java.security.InvalidKeyException: Illegal key size or default parameters
at javax.crypto.Cipher.checkCryptoPerm(Cipher.java:1026)
at javax.crypto.Cipher.implInit(Cipher.java:801)
at javax.crypto.Cipher.chooseProvider(Cipher.java:864)
at javax.crypto.Cipher.init(Cipher.java:1249)
at javax.crypto.Cipher.init(Cipher.java:1186)
at org.apache.xml.security.encryption.XMLCipher.encryptData(XMLCipher.java:1137)
... 68 more
I have downloaded JCE jars for Java 8 and placed in C:\Program Files\Java\jre1.8.0_171\lib\security
Still problem persists.
This exception is thrown, not due to an issue of the Identity Server.
Reason for this issue could be, JCE file is not installed to your JRE properly. But as you have added/replaced local_policy.jar and US_export_policy.jar files, please run the following test code to check whether it is applied properly.
public class JCETest {
public static void main(String args[]) {
int maxKeyLen = 0;
try {
maxKeyLen = Cipher.getMaxAllowedKeyLength("AES");
} catch (NoSuchAlgorithmException e) {
Assert.fail();
}
Assert.assertEquals(2147483647, maxKeyLen);
System.out.println(maxKeyLen);
}
}
You should get the following as output, If JCE is successfully installed:
AES key size should be equal to the 2147483647 if JCE files has been installed successfully.
More information is in http://stackoverflow.com/questions/6481627/java-security-illegal-key-size-or-default-parameters

Key length limit with Java Cryptography Extension

I am aware that the keylenght in the Sun/Oracle JVM is limited for judical reasons. However as far as I understood the concept of the JCE (Java Cryptography Extension) is that a user can choose it's own security provider to compensate this limitation.
For this reason I am trying to operate the Bounce Castle as security provider in conjunction with the Orcale JDK 1.7.
In order to figure out the actual allowed keylegths I am using this code:
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import javax.crypto.Cipher;
import java.security.GeneralSecurityException;
import java.security.Provider;
import java.security.Security;
public class JCETest {
public static void main( String[] args ) throws GeneralSecurityException
{
BouncyCastleProvider bouncyCastleProvider = new BouncyCastleProvider();
Security.addProvider(bouncyCastleProvider);
System.out.println( "\nSecurity-Provider:" );
for( Provider prov : Security.getProviders() ) {
System.out.println( " " + prov + ": " + prov.getInfo() );
}
System.out.println( "\nMaxAllowedKeyLength (for '" + Cipher.getInstance("AES").getProvider() + "' using current 'JCE Policy Files'):\n"
+ " DES = " + Cipher.getMaxAllowedKeyLength( "DES" ) + "\n"
+ " Triple DES = " + Cipher.getMaxAllowedKeyLength( "Triple DES" ) + "\n"
+ " AES = " + Cipher.getMaxAllowedKeyLength( "AES" ) + "\n"
+ " Blowfish = " + Cipher.getMaxAllowedKeyLength( "Blowfish" ) + "\n"
+ " RSA = " + Cipher.getMaxAllowedKeyLength( "RSA" ) + "\n" );
}
}
The output for the Orcale JDK 1.7 and it's build in providers is:
Security-Provider:
SUN version 1.7: SUN (DSA key/parameter generation; DSA signing; SHA-1, MD5 digests; SecureRandom; X.509 certificates; JKS keystore; PKIX CertPathValidator; PKIX CertPathBuilder; LDAP, Collection CertStores, JavaPolicy Policy; JavaLoginConfig Configuration)
SunRsaSign version 1.7: Sun RSA signature provider
SunEC version 1.7: Sun Elliptic Curve provider (EC, ECDSA, ECDH)
SunJSSE version 1.7: Sun JSSE provider(PKCS12, SunX509 key/trust factories, SSLv3, TLSv1)
SunJCE version 1.7: SunJCE Provider (implements RSA, DES, Triple DES, AES, Blowfish, ARCFOUR, RC2, PBE, Diffie-Hellman, HMAC)
SunJGSS version 1.7: Sun (Kerberos v5, SPNEGO)
SunSASL version 1.7: Sun SASL provider(implements client mechanisms for: DIGEST-MD5, GSSAPI, EXTERNAL, PLAIN, CRAM-MD5, NTLM; server mechanisms for: DIGEST-MD5, GSSAPI, CRAM-MD5, NTLM)
XMLDSig version 1.0: XMLDSig (DOM XMLSignatureFactory; DOM KeyInfoFactory)
SunPCSC version 1.7: Sun PC/SC provider
BC version 1.46: BouncyCastle Security Provider v1.46
MaxAllowedKeyLength (for 'SunJCE version 1.7' using current 'JCE Policy Files'):
DES = 64
Triple DES = 128
AES = 128
Blowfish = 128
RSA = 2147483647
But when I apply BC as provider by switching to
Cipher.getInstance("AES", bouncyCastleProvider).getProvider()
It still shows me the limited key length (except for RSA) like this:
MaxAllowedKeyLength (for 'BC version 1.46' using current 'JCE Policy Files'):
DES = 64
Triple DES = 128
AES = 128
Blowfish = 128
RSA = 2147483647
But when I change the JDK to openJDK, I get this output:
MaxAllowedKeyLength (for 'BC version 1.46' using current 'JCE Policy Files'):
DES = 2147483647
Triple DES = 2147483647
AES = 2147483647
Blowfish = 2147483647
RSA = 2147483647
This astonishes me since I was under the impression that not the JDK but the security-provider limiting the key length. But my tests are showing that obviously the JDK is limiting the key length, no matter which provider I choose.
My question is: Did I got something wrong? Is there a way to unleash the keyleght with the Oracle JDK?
The key length limits are determined in the JCE, that is in the JRE, not in the provider. JCE checks the limits before it hands over to the provider.
The correct solution to this is to install the unlimited strength policy files. While this is probably the right solution for your development workstation, it quickly becomes a major hassle (if not a roadblock) to have non-technical users install the files on every computer. There is no way to distribute the files with your program; they must be installed in the JRE directory (which may even be read-only due to permissions).
Bouncy Castle does provide its own API though, which is separate from the JCE. This API does not enforce any key length limits. This is not an ideal solution either, as the API is totally different from the JCE and bound to BC, and BC is an extra 1MB library to distribute with your program.
Finally, there is also a reflection workaround described here in more detail.
OpenJDK does not have any key length limits, which is why they are all simply Integer.MAX_VALUE.

unable to digitally sign pdf using itext and java

i am trying to put a basic digital signature on a pdf file. i am trying to use the code provided on the itext website.The code is as follows-
public class DigiSign {
public static void main(String a[])
{
try {
KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
ks.load(new FileInputStream("C:\\WSR\\keystore.ks"), "password".toCharArray());
String alias = (String) ks.aliases().nextElement();
PrivateKey key = (PrivateKey) ks.getKey(alias, "password".toCharArray());
java.security.cert.Certificate[] chain = ks.getCertificateChain(alias);
PdfReader reader = new PdfReader("C:\\WSR\\a.pdf");
FileOutputStream fout = new FileOutputStream("C:\\WSR\\signed.pdf");
PdfStamper stp = PdfStamper.createSignature(reader, fout, '\0');
PdfSignatureAppearance sap = stp.getSignatureAppearance();
sap.setCrypto(key, chain, null, PdfSignatureAppearance.WINCER_SIGNED);
sap.setReason("arpit");
sap.setLocation("arpit");
// comment next line to have an invisible signature
sap.setVisibleSignature(new Rectangle(10, 10, 20, 20), 1, null);
stp.close();
} catch (Exception ex) {
Logger.getLogger(DigiSign.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
i created the key using
keytool -genkey -keyalg RSA -alias myname -keypass password -keystore keystore.ks -dname "cn=Paulo Soares, c=PT"
and set abc123 as my password.
Now when i run this code i get this exception
Exception in thread "main" java.lang.NoClassDefFoundError: org/bouncycastle/asn1/DEREncodable
at com.lowagie.text.pdf.PdfSignatureAppearance.getAppearance(Unknown Source)
at com.lowagie.text.pdf.PdfSignatureAppearance.preClose(Unknown Source)
at com.lowagie.text.pdf.PdfSignatureAppearance.preClose(Unknown Source)
at com.lowagie.text.pdf.PdfStamper.close(Unknown Source)
at DigiSign.main(DigiSign.java:42)
Caused by: java.lang.ClassNotFoundException: org.bouncycastle.asn1.DEREncodable
at java.net.URLClassLoader$1.run(URLClassLoader.java:202)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:190)
at java.lang.ClassLoader.loadClass(ClassLoader.java:306)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:301)
at java.lang.ClassLoader.loadClass(ClassLoader.java:247)
What am i doing wrong?
(Just to formulate the cause as an answer which has been presented as a comment before:)
For security low level operations iText is based on the BouncyCastle libraries. This especially concerns creation and verification of integrated PDF signatures but also handling of encrypted documents. In these use cases, therefore, the appropriate BouncyCastle provider libs are required on the class path of the application.
The primary exception information
java.lang.NoClassDefFoundError: org/bouncycastle/asn1/DEREncodable
indicates that this requirement is not fullfilled, either BouncyCastle is not present at all or at least not present in the required version. This meanwhile has been confirmed by #user1946152 for his configuration.
P.S.: Obviously in the case at hand the OP still uses a pre-5.x version of iText. While there are certain conditions enforcing this (e.g. a management not being willing to decide when to buy a license sigh), you should definitively update to a current version of iText. There meanwhile have been many big changes, especially in the fields of electronic signatures, content parsing, and creation of PDF/A documents.

Categories

Resources