BouncycastleProvider throws java.lang.NoSuchFieldError: id_hmacWithSHA3_224 - java

I am learning Bouncycastle and facing some problems.
Is it possible to combine multiple security provider, such as I have modified my java.security like:
security.provider.11=org.bouncycastle.jsse.provider.BouncyCastleJsseProvider
security.provider.12=org.bouncycastle.jce.provider.BouncyCastleProvider
security.provider.13=org.bouncycastle.jcajce.provider.BouncyCastleFipsProvider
Then in my server side I have written:
...
SSLContext sslContext = SSLContext.getInstance("TLS", "BCJSSE");
KeyManagerFactory keyMgrFact = KeyManagerFactory.getInstance(
"PKIX", "BCJSSE");
keyMgrFact.init(Utils.createServerKeyStore(), Utils.SERVER_PASSWORD);
...
It will throw an error in:
public static KeyPair generateRootKeyPair()
throws Exception {
KeyFactory kFact = KeyFactory.getInstance("RSA", "BC");
return new KeyPair(
kFact.generatePublic(new X509EncodedKeySpec(rootPublicKey)),
kFact.generatePrivate(new PKCS8EncodedKeySpec(rootPrivateKey)));
}
Error msg:
Exception in thread "main" java.lang.NoSuchFieldError: id_hmacWithSHA3_224
at org.bouncycastle.jcajce.provider.digest.SHA3$Mappings.configure(Unknown Source)
at org.bouncycastle.jce.provider.BouncyCastleProvider.loadAlgorithms(Unknown Source)
at org.bouncycastle.jce.provider.BouncyCastleProvider.setup(Unknown Source)
at org.bouncycastle.jce.provider.BouncyCastleProvider.access$000(Unknown Source)
at org.bouncycastle.jce.provider.BouncyCastleProvider$1.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at org.bouncycastle.jce.provider.BouncyCastleProvider.<init>(Unknown Source)
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
at java.lang.Class.newInstance(Class.java:442)
at sun.security.jca.ProviderConfig$2.run(ProviderConfig.java:221)
at sun.security.jca.ProviderConfig$2.run(ProviderConfig.java:206)
at java.security.AccessController.doPrivileged(Native Method)
at sun.security.jca.ProviderConfig.doLoadProvider(ProviderConfig.java:206)
at sun.security.jca.ProviderConfig.getProvider(ProviderConfig.java:187)
at sun.security.jca.ProviderList.getProvider(ProviderList.java:233)
at sun.security.jca.ProviderList.getIndex(ProviderList.java:263)
at sun.security.jca.ProviderList.getProviderConfig(ProviderList.java:247)
at sun.security.jca.ProviderList.getProvider(ProviderList.java:253)
at sun.security.jca.GetInstance.getService(GetInstance.java:81)
at sun.security.jca.GetInstance.getInstance(GetInstance.java:206)
at java.security.KeyFactory.getInstance(KeyFactory.java:211)
at Utils.generateRootKeyPair(Utils.java:103)
at Utils.createRootCredential(Utils.java:199)
at Utils.createServerKeyStore(Utils.java:273)
at TLSServerExample.main(TLSServerExample.java:19)
I have researched it for couples of days, I thought the reason for this problem is there is some collisions between packages:
bc-fips-1.0.0
bcprov-jdk15on-158.jar
bctls-fips-1.0.2.jar
How to fix that?
Thx in advancee!

It is mostly because when your application is starting up, the old version of bouncy castle classes are loaded based on the class loading sequence in java.
You can check from which jar bouncy castle classes are loading by adding -verbose:class to command line as mentioned in https://stackoverflow.com/a/6686792 when you start your app. It will print a lot of lines so you will have to search for terms like bcp, com.bouncycastle etc.
For me, it was because of bouncy castle related jars were present in java lib directory (/path/to/java/jdk/jre/lib/ext/). Go to /path/to/java/jdk/jre/ and run below command on terminal if you are using linux.
find . -type f -name "*.jar*" | grep bcp
which will tell us if bouncy castle jars are present or not.
If present you will see below output
./lib/ext/bcprov-jdk15on-1.50.jar
You can either upgrade it or remove it (if it does not affect your/other services on the same box)

I was getting similar error with bouncycastle, my case was mismatch or its version

Related

Java Class "BCRSAPublicKey" Intermittently Not Found

Context
Using KNIME 4.1.2, Windows 10, x64, JDK 1.8, Java Edit Snippet
I am attempting to use the Java Snippet to read a CSV file, pgp encrypt it using a public key, and save the resulting file to a temporary folder
I have been attempting to use BounceCastle Library v1.65
try {
encryptFile(
"encryptedfile.csv.pgp",
"original.csv",
"/key/pub.asc",
false,
false);
} catch(Exception e) {
out_result = "fail";
}
The challenge is, I get the following error in the console INTERMITTENTLY and I am unclear what I am incorrectly providing to the library / not including. The confounding is because it is intermittent and sometimes yields the properly encrypted file.
Caused by: java.lang.NoClassDefFoundError: org/bouncycastle/jcajce/provider/asymmetric/rsa/BCRSAPublicKey
at org.bouncycastle.jcajce.provider.asymmetric.rsa.KeyFactorySpi.engineGeneratePublic(Unknown Source)
at java.security.KeyFactory.generatePublic(KeyFactory.java:328)
at org.bouncycastle.openpgp.operator.jcajce.JcaPGPKeyConverter.implGeneratePublic(Unknown Source)
at org.bouncycastle.openpgp.operator.jcajce.JcaPGPKeyConverter.getPublicKey(Unknown Source)
at org.bouncycastle.openpgp.operator.jcajce.JcePublicKeyKeyEncryptionMethodGenerator.encryptSessionInfo(Unknown Source)
at org.bouncycastle.openpgp.operator.PublicKeyKeyEncryptionMethodGenerator.generate(Unknown Source)
at org.bouncycastle.openpgp.PGPEncryptedDataGenerator.open(Unknown Source)
at org.bouncycastle.openpgp.PGPEncryptedDataGenerator.open(Unknown Source)
at JSnippet.encryptFile(JSnippet.java:144)
at JSnippet.encryptFile(JSnippet.java:107)
at JSnippet.snippet(JSnippet.java:174)
at org.knime.base.node.jsnippet.JavaSnippetCellFactory.getCells(JavaSnippetCellFactory.java:300)

Trouble instantiating a JavaKeyStore from file

I'm trying to get an instance of org.apache.ws.security.components.crypto.Merlin using org.apache.ws.security.components.crypto.CryptoFactory specifically the CryptoFactory.getInstance(properties) method.
This will consistantly throw
java.lang.RuntimeException: org.apache.ws.security.components.crypto.Merlin cannot create instance
which evantually is caused by
java.security.UnrecoverableKeyException: Password verification failed
The password on the keystore file has been checked with the keytool on the command line and is correct.
the keystore is generated via the following process:
Which is in the root directory of the eclipse porject.
The test applciation is as follows:
public class App {
public static void main(String[] args) throws CredentialException,
IOException {
System.out.println("Starting");
Properties p = new Properties();
p.setProperty("org.apache.ws.security.crypto.merlin.keystore.password",
"password");
p.setProperty("org.apache.ws.security.crypto.provider",
"org.apache.ws.security.components.crypto.Merlin");
p.setProperty("org.apache.ws.security.crypto.merlin.keystore.type",
"jks");
p.setProperty("org.apache.ws.security.crypto.merlin.file", "./testkeystore.jks");
Crypto crypto = CryptoFactory.getInstance(p);
System.out.println(" Complete ");
}
}
and the following exception is generated:
Exception in thread "main" java.lang.RuntimeException: org.apache.ws.security.components.crypto.Merlin cannot create instance
at org.apache.ws.security.components.crypto.CryptoFactory.loadClass(CryptoFactory.java:225)
at org.apache.ws.security.components.crypto.CryptoFactory.loadClass(CryptoFactory.java:180)
at org.apache.ws.security.components.crypto.CryptoFactory.getInstance(CryptoFactory.java:73)
at com.restart.test.cryptotest2.App.main(App.java:22)
Caused by: java.lang.reflect.InvocationTargetException
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:57)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Constructor.java:525)
at org.apache.ws.security.components.crypto.CryptoFactory.loadClass(CryptoFactory.java:211)
... 3 more
Caused by: org.apache.ws.security.components.crypto.CredentialException: Failed to load credentials.
at org.apache.ws.security.components.crypto.AbstractCrypto.load(AbstractCrypto.java:174)
at org.apache.ws.security.components.crypto.AbstractCrypto.<init>(AbstractCrypto.java:135)
at org.apache.ws.security.components.crypto.Merlin.<init>(Merlin.java:71)
... 8 more
Caused by: java.io.IOException: Keystore was tampered with, or password was incorrect
at sun.security.provider.JavaKeyStore.engineLoad(JavaKeyStore.java:772)
at sun.security.provider.JavaKeyStore$JKS.engineLoad(JavaKeyStore.java:55)
at java.security.KeyStore.load(KeyStore.java:1214)
at org.apache.ws.security.components.crypto.AbstractCrypto.load(AbstractCrypto.java:168)
... 10 more
Caused by: java.security.UnrecoverableKeyException: Password verification failed
at sun.security.provider.JavaKeyStore.engineLoad(JavaKeyStore.java:770)
... 13 more
The password as indicated in the cmd window is set to "password" , but by all accounts the application is rejecting it, I can change the password using keytool -storepasswd with no issues, So i know the the password I am providing is correct; can anyone suggest what may be going wrong here? I've been trying to debug this unsuccessfully for full a day now.
If there is any additional information I can provide please let me know.
edit --
the folloing maven dependency is required to build this test:
<dependency>
<groupId>org.apache.ws.security</groupId>
<artifactId>wss4j</artifactId>
<version>1.5.8</version>
<scope>provided</scope>
</dependency>
After reading the comments from User I built it against a different version of the JDK/JRE and it worked, after downloading the sources for rt.java and stepping through I found that the CryptoBase class was instantiating two JavaKeyStores, the first (being my .jks file) which instantiated fine, but the second was the cacerts keystore in jre\lib\security> which did not have the default password of changeit which was causing the failure;
I have now changed the password on the jre keystore and I'm working fine in my original jre/jdk.
I think your problem is related with libraries because stacktrace says
'org.apache.ws.security.components.crypto.Merlin cannot create instance'
it means you don't have (o have an incorrect version) of WSS4J library.

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.

Java Applet SOAPMessage causes "SAAJ0540: Error during saving a multipart message"

I have a problem which I have boiled down to this simple example.
import java.applet.Applet;
import javax.xml.soap.MessageFactory;
import javax.xml.soap.SOAPMessage;
public class SOAPTest2 extends Applet {
private static final long serialVersionUID = -1;
public void init(){
try{
MessageFactory mf = MessageFactory.newInstance();
SOAPMessage sm = mf.createMessage();
System.out.println("About to fail");
sm.writeTo(System.out);
System.out.println();
System.out.println("If you see this, it didn't fail.");
} catch (Exception e) {
e.printStackTrace();
}
}
}
When I run this in eclipse (JDK 1.6.0_27) It works as I would expect, and I get the following output:
About to fail
<SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/"><SOAP-ENV:Header/><SOAP-ENV:Body/></SOAP-ENV:Envelope>
If you see this, it didn't fail.
When I run this in a browser as an applet I get the following error in the java console.
About to fail
14-Sep-2011 1:20:51 PM com.sun.xml.internal.messaging.saaj.soap.MessageImpl saveChanges
SEVERE: SAAJ0540: Error during saving a multipart message
com.sun.xml.internal.messaging.saaj.SOAPExceptionImpl: Error during saving a multipart message
at com.sun.xml.internal.messaging.saaj.soap.MessageImpl.saveChanges(Unknown Source)
at com.sun.xml.internal.messaging.saaj.soap.MessageImpl.writeTo(Unknown Source)
at SOAPTest2.init(SOAPTest2.java:16)
at sun.plugin2.applet.Plugin2Manager$AppletExecutionRunnable.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)
Caused by: java.lang.ExceptionInInitializerError
at java.lang.Class.forName0(Native Method)
at java.lang.Class.forName(Unknown Source)
at com.sun.xml.internal.messaging.saaj.util.FastInfosetReflection.<clinit>(Unknown Source)
at com.sun.xml.internal.messaging.saaj.util.transform.EfficientStreamingTransformer.transform(Unknown Source)
at com.sun.xml.internal.messaging.saaj.soap.impl.EnvelopeImpl.output(Unknown Source)
at com.sun.xml.internal.messaging.saaj.soap.impl.EnvelopeImpl.output(Unknown Source)
at com.sun.xml.internal.messaging.saaj.soap.SOAPPartImpl.getContentAsStream(Unknown Source)
at com.sun.xml.internal.messaging.saaj.soap.MessageImpl.getHeaderBytes(Unknown Source)
... 5 more
Caused by: java.security.AccessControlException: access denied (java.util.PropertyPermission com.sun.xml.internal.fastinfoset.parser.string-interning read)
at java.security.AccessControlContext.checkPermission(Unknown Source)
at java.security.AccessController.checkPermission(Unknown Source)
at java.lang.SecurityManager.checkPermission(Unknown Source)
at java.lang.SecurityManager.checkPropertyAccess(Unknown Source)
at java.lang.System.getProperty(Unknown Source)
at com.sun.xml.internal.fastinfoset.Decoder.<clinit>(Unknown Source)
... 13 more
I am at a loss as to why this is occurring. I am simply creating en empty SOAPMessage and trying to write it to System.out. I am not accessing any local resources. I have done much searching on MessageImpl.saveChanges and FastInfosetReflection to no avail. Please give the example a try, and let me know if you have any ideas.
Respectfully, I ask that any answers that tell me to sign my Jar be accompanied by a reasonable explanation given the minimal example above that does not access local resources.
The exception is self explanatory:
Caused by: java.security.AccessControlException: access denied
(java.util.PropertyPermission
com.sun.xml.internal.fastinfoset.parser.string-interning read)
SAAJ imposes security restrictions and you have no problem when you run in Eclipse but when running from Applet, you run inside a sandbox and security manager stops the flow
Definitely a signing issue.
http://java.sun.com/developer/onlineTraining/Programming/JDCBook/signed.html
You can try it out with the exact values from that link (in this sample the only thing that is different is that the jar is called sample.jar):
Build a jar called sample.jar
Run: keytool -genkey -alias signFiles -keystore compstore -keypass kpi135 -dname "cn=jones" -storepass ab987c
Run: jarsigner -keystore compstore -storepass ab987c -keypass kpi135 -signedjar Ssample.jar sample.jar signFiles
I should add that I know this is the solution since I work with FuryComputers ... I have no idea why it is the solution though - anyone else have any ideas?

Exception When Reading OCSP Signing Certs in Java

I'm currently working on getting a Java application (JRE 1.5+) to talk to a Windows 2008 OCSP Responder, and I'm getting a strange error on trying to read the Responder's signing cert.
I get the following exception on trying to perform an OCSP validation.
Caused by: java.security.cert.CertificateParsingException: java.io.IOException: short read on DerValue buffer
at sun.security.x509.X509CertInfo.<init>(Unknown Source)
at sun.security.x509.X509CertImpl.parse(Unknown Source)
at sun.security.x509.X509CertImpl.<init>(Unknown Source)
at sun.security.provider.certpath.OCSPResponse.<init>(Unknown Source)
at sun.security.provider.certpath.OCSPChecker.check(Unknown Source)
... 6 more
Caused by: java.io.IOException: short read on DerValue buffer
at sun.security.util.DerValue.getOctetString(Unknown Source)
at sun.security.x509.Extension.<init>(Unknown Source)
at sun.security.x509.CertificateExtensions.init(Unknown Source)
at sun.security.x509.CertificateExtensions.<init>(Unknown Source)
at sun.security.x509.X509CertInfo.parse(Unknown Source)
... 11 more
This suggested there was a problem reading the signing cert, so I tried importing that separately using a method similar to the below:
public static List<Certificate> readCerts(String certFile,
CertificateFactory cf, boolean withCRL) throws Exception {
FileInputStream fis = new FileInputStream(certFile);
BufferedInputStream bis = new BufferedInputStream(fis);
List<Certificate> certs = new LinkedList<Certificate>();
while (bis.available() > 0) {
Certificate cert = cf
.generateCertificate(bis);
X509Certificate cx509 = (X509Certificate) cert;
certs.add(cert);
}
return certs;
}
which gave me the same error. This only seems to happen with certificates generated from the OCSP Signing template, user certificates can be read fine.
Has anyone else encountered similar problems with X509 support in Java?
Regards,
Tom
UPDATE: The cert I'm having trouble with is as below:
-----BEGIN CERTIFICATE-----
MIIDzDCCArSgAwIBAgIKYQWrDAAAAAAABjANBgkqhkiG9w0BAQUFADBFMRMwEQYK
CZImiZPyLGQBGRYDaW50MRUwEwYKCZImiZPyLGQBGRYFbG9ucWExFzAVBgNVBAMT
DmxvbnFhLVRFLUNBLUNBMB4XDTA5MDkyMTE2NDIxNloXDTA5MTAwNTE2NDIxNlow
GjEYMBYGA1UEAxMPdGUtY2EubG9ucWEuaW50MIIBIjANBgkqhkiG9w0BAQEFAAOC
AQ8AMIIBCgKCAQEA6rYO7X/PztBE2Do9u95ws3Ob86cySJ1iLrHLSF+VjvTQkZ3J
e0uKxoK4doSikqCZH9zXZ6qFFVMZlzq/FnIP9TLhv3uFom0y+Z0HmPAW7RtrZ8R6
1EAmcQDGpyRhzCWJqrEzgbW1v1QtF854kium97GwUWnVijGv3jQqT3hbmD7++9lh
9ILaLXMAKdTFpL1ao2eHWYf2mChRpuAox2juO1g4xjot9GXsEMhTwAg9F/pZnbKE
hhpeo1c0kgP3uus7ULlwdRnZ4O+tp79GeVKsdJbphmnC6Fc/PdT0KuHSk9Q0v192
Ger5nTQaZk/dmsyGBd8g4Q+0g0Ri+wgpUUsykQIDAQABo4HoMIHlMDYGCSsGAQQB
gjcVBwQpMCcGHysGAQQBgjcVCIHPgWyXxQ2ChYcyg8LhMoWky3ppASACAWUCAQAw
EwYDVR0lBAwwCgYIKwYBBQUHAwkwDgYDVR0PAQH/BAQDAgeAMBsGCSsGAQQBgjcV
CgQOMAwwCgYIKwYBBQUHAwkwDQYJKwYBBQUHMAEFBAAwHQYDVR0OBBYEFNblspp7
Hu07mraeMSyuBUTUnbl3MB8GA1UdIwQYMBaAFK/r521FB+GNls/fe8hrNE8UpQhv
MBoGA1UdEQQTMBGCD3RlLWNhLmxvbnFhLmludDANBgkqhkiG9w0BAQUFAAOCAQEA
FASEVcUJQlrmCD/ysycOxAIAoc2BVLhteOMoZ7V65a5/+Q5JM7Od+gKqoxLVrjb2
BDLlDFp5U8CirQ4lyWV5i1gQpLFTDcjgonp9Ky50KA0Ginn5CmTELB2THwFSQwfm
OFenSaV1mAcEzdyp/hi2xSuMqhveSanQFD0r6y45oZsd9ubdFEWI6nBRrj4hhfw0
Wo2GKUgslXqAqEezdin5JNgsPdj3qsi4+U4llyrd3gG20eoWzGHF4h7wfFiQV+fs
yEPY06Rg9G9m3GlIv+7Gp3sixb+cvZe+e0gO32mVRydTXMaAZu7ZiFk3M6AqxfDw
dO//eCu2dZCLTw6xTbUc9A==
-----END CERTIFICATE-----
I assume you get your factory like this,
cf = CertificateFactory.getInstance("X509");
The default X509 factory has many limitations. It looks like your cert contains an extension the factory doesn't know how to parse. If you post the cert, I can help you to identify the offending extension.
EDIT: The offending extension is
1.3.6.1.5.5.7.48.1.5 - id-pkix-ocsp-nocheck
The only option is to remove this from the cert with Java built-in JCE. You can also try another JCE like BouncyCastle.

Categories

Resources